java.lang.IllegalArgumentException: Service not registered

在5.0的手机上覆写onDestory()方法时调用unbindService(conn)并没有出现这个问题,但是在4.4的机子上跑的时候,退出发现就报上述错误了。可能有人会想,明明有使用bindService绑定服务呀,而且查看进程服务也在运行。没错,我一开始就是这么认为的,然后我点进bindService这个方法去看源码,发现它返回类型不是void,而是boolean(作者比较粗心,学习的时候没注意),然后看看官方的说明

@param service Identifies the service to connect to.  The Intent mayspecify either an explicit component name, or a logical description (action, category, etc) to match an{@link IntentFilter} published by a service.
@param conn Receives information as the service is started and stopped. This must be a valid ServiceConnection object; it must not be null.

英语勉强还行的可以看懂第二个@param的说明,所以解决办法就是
预先判断ServiceConnection 是否为空,不空再解绑服务。

相关代码

//定义一个全局变量用来标记
private boolean isConnected = false;

//在bindService处添加
isConnected = bindService();

@Override
protected void onDestroy() {
    super.onDestroy();
    if(isConnected){
        unbindService(conn);//conn表示ServiceConnection 对象
        isConnected = false;
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值