Android IAE:服务未在服务后取消绑定服务上注册。stopSelf

Android IAE:服务未在服务后取消绑定服务上注册。stopSelf,android,service,android-service,android-service-binding,Android,Service,Android Service,Android Service Binding,我正在绑定到一个android服务,如 有时,服务会停止自身调用stopSelf,或被stopService停止,从而导致所有客户端解除绑定。但是变量bound在这里仍然为true,因此onPause将抛出以下异常: java.lang.IllegalArgumentException: Service not registered: de.ncoder.sensorsystem.android.app.MainActivity$1@359da29 at android

我正在绑定到一个android服务,如

有时,服务会停止自身调用
stopSelf
,或被
stopService
停止,从而导致所有客户端解除绑定。但是变量
bound
在这里仍然为true,因此
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)
            ...
有没有一种简单的方法来检查服务是否仍然绑定并处于活动状态?
据我所知,将保持绑定处于活动状态(因为它仅在极端情况下调用,服务有望很快重新启动),因此将
bound
设置为false将没有帮助。

当您在服务中调用
stopSelf()
时,您的
onSerivceDisconnected()
将被调用

因此,在
活动的
onSerivceDisconnected()
中将
bound
值更改为
false

 @Override
public void onServiceDisconnected(ComponentName name) {
    Log.i(TAG, "Service disconnected");
    bound=false;
    service = null;
}

在大多数情况下,您希望在绑定活动时运行服务。这种情况的解决方案是:将标志BIND_AUTO_CREATE添加到服务绑定调用中,即使调用了stopService或stopSelf,服务也将一直运行,直到调用unbind为止


否则,据我所知,唯一的选择就是捕获异常

但是onServiceDisconnected的JavaDoc声明它不会删除ServiceConnection本身,并且与该服务的绑定将保持活动状态。如果我不解除绑定该服务,则如果以前使用
stopSelf
停止该服务,我会收到
ServiceConnectionLeaked
警告<只有通过
stopSelf
而不是通过
stopService
停止服务时,才会调用code>onServiceDisconnected
 @Override
public void onServiceDisconnected(ComponentName name) {
    Log.i(TAG, "Service disconnected");
    bound=false;
    service = null;
}