在做Service的绑定和解绑项目的时候,绑定成功,解绑也成功,但是如果解除绑定后再点击给解除绑定的指令(项目中就是点击按钮解除绑定),会报这个错误:
AndroidRuntime(99):java.lang.IllegalArgumentException:Service not registered:com.m99.servicetest.MainActivity$1@41ddfcc0
错误提示Service没有注册,事实上我在Manifest.xml中已经注册过这个Service了。
修改前代码:
@Override
publicvoidonClick(Viewv){
switch(v.getId()){
caseR.id.start_service:
Intent startIntent=newIntent(this, MyService.class);
startService(startIntent);// 启动服务
break;
caseR.id.stop_service:
Intent stopIntent=newIntent(this, MyService.class);
stopService(stopIntent);// 停止服务
break;
caseR.id.bind_service:
Intent bindIntent=newIntent(this, MyService.class);
// 绑定服务
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
caseR.id.unbind_service:
unbindService(connection);// 解绑服务
break;
default:
break;
}
}
查询官方文档中关于unbindService()这个方法的介绍:
public abstract void unbindService (ServiceConnection conn)
Added in API level 1
Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.
Parameters
conn The connection interface previously supplied to bindService(). This parameter must not be null.
最后一句看到这个传入的conn参数不能为null,也就是必须有绑定存在,才能解绑,小项目中绑定成功后第一次点击解绑不会报错,解绑后这个参数就是null了,再次点击解绑就会报错,那么我们为解绑加一个判断就可以了。
修改后代码如下:
privatebooleanisBound=false;
@Override
publicvoidonClick(Viewv){
switch(v.getId()){
caseR.id.start_service:
Intent startIntent=newIntent(this, MyService.class);
startService(startIntent);// 启动服务
break;
caseR.id.stop_service:
Intent stopIntent=newIntent(this, MyService.class);
stopService(stopIntent);// 停止服务
break;
caseR.id.bind_service:
Intent bindIntent=newIntent(this, MyService.class);
// 绑定服务
isBound=bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
caseR.id.unbind_service:
if(isBound){
unbindService(connection);// 解绑服务
isBound=false;
}
break;
default:
break;
}
}