zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java.lang.IllegalArgumentException: Service not registered

JAVA not Service lang IllegalArgumentException registered
2023-09-14 09:11:44 时间

java.lang.IllegalArgumentException: Service not registered

首先检查一下,Service是否在AndroidManifest文件中注册。格式如下:

  <service   android:name=".MyService"  ></service>

如果Service已经注册了,还是会报这个错误的话,可能是

1、bindService没有成功,就直接unbindService;

2、也可能是已经unbindService成功了,还多次进行unbindService。

解决方法:

每次绑定服务时,用一个布尔值记状态为true,
解除绑定服务时,检验布尔值是否为true,如果是true,就解除服务,并把布尔值设为false,

这样即使多次解除服务,也不会报“service not registered”了。

示例代码如下:

private boolean mIsBound=false ;
public void doBindService() {
  Intent bindIntent = new Intent(this, MyService.class);
   bindService(bindIntent,connection,BIND_AUTO_CREATE);
    mIsBound = true;
}
 
public void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

 更详细的解答见stack overflow:

http://stackoverflow.com/questions/22079909/android-java-lang-illegalargumentexception-service-not-registered