最近在学Android四大组件之一的服务(Service),写了一个绑定服务的小demo,出了点小意外:
程序直接闪退,运行日志如下:
java.lang.RuntimeException:Unable to start activity ComponentInfo{com.example.musicbaidu/com.example.musicbaidu.MainActivity}: java.lang.IllegalArgumentException: connection is null
这个错误的意思是说在bindService()里缺少一个“ServiceConnection的实现对象”参数
connection is null!但是我的确在bindService()方法里给出了ServiceConnection的对象的参数,而且我的代码几乎就是照着书上打的,感觉没有问题。
后来我在stackoverflow上看到了差不多的问题,解答是这样的:
So it turns out this was caused by a null connection (myConnection) that I was passing to bindService(). This did not cause problems on the emulator running android 2.1 but on my phone which is running android 4.2.2 it did. It seems some of the changes in the newer versions of android cause this issue.
It was fixed by creating a new instance of myConnection instead of just declaring it.
按他的操作,我改了一下代码,发现可以了!
说明一下过程:
我一开始的思路是,在MainActivity中建一个内部类,继承ServiceConnection类来创建对象,就像这样:
public class MainActivity extends Activity {
private MyConn mcn; //注意这一点
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mcn = new MyConn();
bindService(...)
......
}
public class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
......
}
public void onServiceDisconnected(ComponentName name) {
}}}
然而,这位外国网友给出的建议是直接new一个ServiceConnection出来。因为是一个接口,需要重写内部的方法才能创建对象。于是就改成这样了。
public class MainActivity extends Activity {
private ServiceConnection mcn; //直接创建ServiceConnection
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mcn = new new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
bindService(...)
......
}
//自己写的继承类就不需要了
}
据说出现异常是与不同的Android版本有关,我的手机是Android6.0,完美闪退,修改之后好了,不知道其他的系统表现会如何。我暂时也没明白为什么会这样,望大神解答。