我正在尝试为Android应用程序创建远程服务。我或多或少已经从Android Developers网站复制了代码,出于我的目的对其进行了重新设计。但是,当我进入bindService步骤时,我在android.content.Context.getPackageName()上得到了NullPointerException。我究竟做错了什么?

我已经在应用程序的早期版本中使用了进程内服务,但是对于我想要的应用程序来说,这还不够。除了必要的代码更改之外,两者之间的服务本身保持不变。我已经查看了此处的所有结果,但它们要么无关,要么无济于事。

我试过将调用从onCreate移动到onStart。没有不同。 BinderActivity的onCreate从未执行。我尝试使用startService而不是bindService,但是它给了我同样的错误。我检查过这个,意图和mConnection都是非空的(它们是)。我知道该服务尚未启动,但是我正在使用Context.BIND_AUTO_CREATE(如果没有启动,应该启动它)。由于没有为问题挥舞死鸡,我不确定在这里还有什么可做的。

我的主要活动:

package com.example.trainchecker;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;


import android.os.Message;
import android.os.Messenger;

import java.io.*;
import java.util.ArrayList;


import android.widget.TextView;


public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BinderActivity ba = new BinderActivity();
        ba.BindService();
    }
}


这是BinderActivity,应该在其中发生魔术。相反,该错误会:

package com.example.trainchecker;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.os.Message;
import android.os.Handler;
import android.os.Messenger;



public class BinderActivity extends Activity {
    public Messenger ms = null;
    private MainActivity ma;

    class IncomingHandler extends Handler{
        @Override
        public void handleMessage(Message msg){
                super.handleMessage(msg);
        }
    }

    final Messenger mm = new Messenger(new IncomingHandler());

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d("MCon","Sentinel Online");
            ms = new Messenger(service);
            try {
                Message msg = Message.obtain(null,TCService.MSG_REGISTER_CLIENT);
                msg.replyTo = mm;
                ms.send(msg);
            } catch (RemoteException e){   e.printStackTrace();}
        }
        public void onServiceDisconnected(ComponentName className) {
            Log.d("MCon","Sentinel Offline");
            try {
                Message msg = Message.obtain(null,2);
                msg.replyTo = mm;
                ms.send(msg);
            } catch (RemoteException e){   e.printStackTrace();}
        }
    };



    public void BindService() {
        bindService(new Intent(this, TCService.class), mConnection, Context.BIND_AUTO_CREATE);
    }


}




最后,服务本身。那里不多,但是是我的:

package com.example.trainchecker;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import android.os.Message;
import android.os.Messenger;

public class TCService extends Service {

    ArrayList<Messenger> mc = new ArrayList<>();

    @Override
    public IBinder onBind(Intent i) {
        Log.d("TCS", "Binding Now");
        return mm.getBinder();
    }


    static final int MSG_REGISTER_CLIENT = 1;

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mc.add(msg.replyTo);
                    break;
                case 2:
                    mc.remove(msg.replyTo);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    final Messenger mm = new Messenger(new IncomingHandler());
}



这是整个错误:

09-15 11:39:04.518 15448-15448/com.example.trainchecker E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.trainchecker, PID: 15448
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trainchecker/com.example.trainchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.access$900(ActivityThread.java:150)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:171)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
        at android.content.ComponentName.<init>(ComponentName.java:128)
        at android.content.Intent.<init>(Intent.java:4468)
        at com.example.trainchecker.BinderActivity.BindService(BinderActivity.java:58)
        at com.example.trainchecker.MainActivity.onCreate(MainActivity.java:65)
        at android.app.Activity.performCreate(Activity.java:6285)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
        at android.app.ActivityThread.access$900(ActivityThread.java:150) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:171) 
        at android.app.ActivityThread.main(ActivityThread.java:5417) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

最佳答案

以编程方式实例化Activity实例不会触发生命周期,因此您的上下文在那里无效。将其传递给您的BindService()调用。从技术上讲,您的BinderActivity不需要存在,可以存在于MainAcitivity或服务中。

07-27 19:16