Initially, I attempted to start and bind my services using a function in my MainActivity like so:
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();
}
This gave me a nullPointerException when I tried to access timerService.startTimer();
However, when I moved the code to the onStart()
method as such:
@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);
}
and put only the timerService.startTimer();
method call in the startTimerService()
method, everything works perfectly. The only problem is that I have no idea why this is case, perhaps someone can enlighten me.