在我的活动中,我有实例变量LocalBinder mBinder ;ServiceConnection mConnection; andboolean mBound;`
在onCreate我实例化 aServiceConnection并将其设置为mConnection如下所示:
mConnection=new ServiceConnection()
{
public void onServiceConnected(ComponentName class name,IBinder service){
Log.d(TAG,"Service connected");
mBinder=(LocalService.LocalBinder)service;
}
我将 mBinder 设置为 nullonServiceDisconnected(ComponentName className)
问题似乎是调用绑定服务使用:
Intent intent=new Intent(MainActivity.this,LocalService.class);
bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
永远不会发生...因此永远不会调用 ServiceConnection...当我在LocalBinder类中使用公共方法时,它会引发异常,因为 binder 为 null。
我有一个非空ServiceConnection对象,并且正在使用正确的上下文。Activity 在应用程序启动时启动。LocalBinder您可能已经猜到了LocalService.
本地服务如下所示:
static class LocalBinder
{
public int getRandomNumber()
{
return (int)(Math.random()*100);
}
}
public IBinder onBind(Intent intent)
{
LocalBinder binder=new LocalBinder();
return binder;
}
该服务在我实现时启动onStartCommand,startService(intent);但它不会绑定...即使bindService返回 true,Service Connected 也不会显示...因此 IBinder 未传递给导致 NullPointerException 的 Activity