0

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.

Matthias
  • 71
  • 1
  • 1
  • 7
  • Timerservice is still null. It is set in the callback, which probably has not yet been called. – Fildor Jul 24 '15 at 04:32
  • But why would the callback have been called in the latter situation, but not the former? – Matthias Jul 24 '15 at 04:41
  • `bindService` is an async call, you have to wait for `onServiceConnected` to be called before you start doing anything with the service – pskink Jul 24 '15 at 05:36

0 Answers0