在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;
}
}