【发布时间】:2013-12-12 05:08:45
【问题描述】:
在我的活动中,我有实例变量LocalBinder mBinder ;ServiceConnection mConnection; andboolean mBound;`
在onCreate 中,我实例化了一个ServiceConnection 并将其设置为mConnection,如下所示:
mConnection=new ServiceConnection()
{
public void onServiceConnected(ComponentName class name,IBinder service){
Log.d(TAG,"Service connected");
mBinder=(LocalService.LocalBinder)service;
}
我在 onServiceDisconnected(ComponentName className) 中将 mBinder 设置为 null
问题似乎是调用绑定服务使用:
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 未传递给 Activity 导致NullPointerException
【问题讨论】:
-
你什么时候尝试访问 mBinder?
-
在
onResume和mBinder.getRandomNumber();一样在for 循环中,这就是LogCat 中出现异常的地方 -
尝试Log.d的bindService()返回值
-
bindService返回的值是true,我知道是bind服务返回然后用IBinder调用ServiceConnection -
但您在 logcat 中没有看到“服务已连接”?
标签: android nullpointerexception android-service android-service-binding