我正在绑定到一个 android 服务,如JavaDoc中所示
private boolean bound = false;
private MyService service = null;
private final ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "Service connected");
service = (MyService) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "Service disconnected");
service = null;
}
};
@Override
public void onResume() {
super.onResume();
Intent intent = new Intent(this, MyService.class);
if (bindService(intent, connection, Context.BIND_ABOVE_CLIENT)) {
bound = true;
} else {
Log.w(TAG, "Service bind failed");
}
}
@Override
public void onPause() {
if (bound) {
unbindService(connection);
bound = false;
}
super.onPause();
}
有时,Service 停止自身调用stopSelf或被 停止stopService,导致所有客户端未绑定。但是这里的变量bound依然为真,所以onPause会抛出如下异常:
java.lang.IllegalArgumentException: Service not registered: de.ncoder.sensorsystem.android.app.MainActivity$1@359da29
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1022)
at android.app.ContextImpl.unbindService(ContextImpl.java:1802)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:550)
at de.ncoder.sensorsystem.android.app.MainActivity.onPause(MainActivity.java:121)
at android.app.Activity.performPause(Activity.java:6044)
...
有没有一种简单的方法来检查服务是否仍然绑定和活动?据我所知,onServiceDisconnected这将使绑定保持活动状态(因为它仅在极端情况下调用,服务有望很快重新启动),因此设置bound为 false 将无济于事。