gpt4 book ai didi

Android java.lang.IllegalArgumentException : Service not registered

转载 作者:IT老高 更新时间:2023-10-28 21:34:49 26 4
gpt4 key购买 nike

我有一个看起来像这样的设置:

class MyFragment implements SomeEventListener {

Application mAppContext;

boolean mBound;
boolean mDidCallUnbind;
MyIBinder mBinder;
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBound = true;
mBinder = (MyIBinder) service;
mBinder.getThings();...
}

@Override
public void onServiceDisconnected(ComponentName name) {
mDidCallUnbind = false;
mBound = false;
mBinder = null;
}
};

...

@Override
public void onSomeEvent() {
mAppContext.bindService(...);
}

void unbindService() {
if (mBound && !mDidCallUnbind) {
mDidCallUnbind = true;
mAppContext.unbindService(mConnection);
}
}

@Override
public void onPause() {
unbindService();
super.onPause();
}
}

但是,我仍然不时看到标题中的错误:java.lang.IllegalArgumentException: Service not registered are generated when unbindService() is called .我错过了什么愚蠢的事情,还是还有更多的事情发生?我应该注意,可能存在不止一个相同的 fragment 。

编辑

由于实际上似乎没有人在阅读代码,所以让我解释一下。 unbindService() 不会调用 Context.unbindService(ServiceConnection) 除非服务已绑定(bind) (mBound) 并且 它在 onServiceDisconnected(...) 回调因之前可能对 unbindService() 的调用而被命中之前,之前没有被调用过。

请记住,在任何情况下,Android 会为您取消绑定(bind)您的服务,以使该服务变为未绑定(bind)但不会调用 onServiceDisconnected 从而使我处于陈旧状态?

另外,我正在使用我的应用程序上下文进行初始绑定(bind)。假设如下:

@Override
public void onCreate() {
mApplication = getContext().getApplicationContext();
}

最佳答案

使用 mIsBound里面 doBindService()doUnbindService()而不是在ServiceConnection实例。

ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinder = (MyIBinder) service;
}

@Override
public void onServiceDisconnected(ComponentName name) {
mBinder = null;
}
};

...

public void doBindService() {
mIsBound =bindService(new Intent(this, MyService.class),
mConnection, Context.BIND_AUTO_CREATE);
}

public void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}

这就是 http://developer.android.com/reference/android/app/Service.html 中的处理方式

关于Android java.lang.IllegalArgumentException : Service not registered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079909/

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