gpt4 book ai didi

android - IAE : Service not registered on unbindService after Service. stopSelf

转载 作者:行者123 更新时间:2023-11-29 20:58:34 26 4
gpt4 key购买 nike

我正在绑定(bind)到 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();
}

有时,服务会停止自身调用 stopSelf 或被 stopService 停止,导致所有客户端解除绑定(bind)。但是这里的变量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)
...

是否有一种简单的方法来检查服务是否仍处于绑定(bind)状态且处于 Activity 状态?据我所知,onServiceDisconnected将使绑定(bind)保持 Activity 状态(因为它仅在极端情况下被调用,服务有望很快重新启动),因此将 bound 设置为 false 将无济于事。

最佳答案

在大多数情况下,您希望服务在绑定(bind) Activity 时运行。这种情况的解决方案 - 将标志 BIND_AUTO_CREATE 添加到服务绑定(bind)调用,即使调用了 stopService 或 stopSelf,服务也会一直运行,直到您调用 unbind。

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

关于android - IAE : Service not registered on unbindService after Service. stopSelf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com