最初,我尝试使用MainActivity中的函数启动和绑定我的服务,如下所示:
public void startTimerService(){
Intent intent = new Intent(this, TimerService.class);
startService(intent);
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("MainActivity", "onServiceConnected");
TimerService.LocalBinder binder = (TimerService.LocalBinder) iBinder;
timerService = binder.getService();
boundToTimer = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
boundToTimer = false;
Log.d("MainActivity", "onServiceDisconnected");
}
};
Intent intent2 = new Intent(this, TimerService.class);
bindService(intent2, mConnection, Context.BIND_AUTO_CREATE);
timerService.startTimer();
}
当我尝试访问timerService.startTimer();
时,这给了我一个nullPointerException但是,当我将代码移动到onStart()
方法时:
@Override
public void onStart(){
super.onStart();
Intent intent = new Intent(this, TimerService.class);
startService(intent);
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("MainActivity", "onServiceConnected");
TimerService.LocalBinder binder = (TimerService.LocalBinder) iBinder;
timerService = binder.getService();
boundToTimer = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
boundToTimer = false;
Log.d("MainActivity", "onServiceDisconnected");
}
};
Intent intent2 = new Intent(this, TimerService.class);
bindService(intent2, mConnection, Context.BIND_AUTO_CREATE);
}
并且只在timerService.startTimer();
方法中调用startTimerService()
方法调用,一切正常。唯一的问题是我不知道为什么会这样,也许有人可以启发我。