Cannot 're-bind' to same service

30 views Asked by At

I'm building a timer app. The timer runs on a service and updates the ui. The app starts the service inside onCreate().

getApplication().startService(intentService);
getApplication().bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);

It works. Except it doesn't. Specifically on configuration changes.

I know that the calling activity gets destroyed (onDestroy) and then recreated, onCreate is called again and... bindService() is supposed to bind to the same service. I'm calling it with the same exact Intent, same serviceConnection, from the same (application) context.

It doesn't. It binds to a new service object somehow. (I can see it in the debugger, the object returned to the activity is different). That breaks my timer.

It's interesting to me that when I exit the activity and reenter it through the Notification (it's a foreground service, and the notification brings you to the same activity), onCreate() gets called again, startService and bindService too, but that time, it's somehow able to bind properly to the running Service.

What am I missing?

EDIT: Here are the main parts of the Service code:

public class MyService extends IntentService {
    // variables ...
    public MyService() { super("MyService"); }
    protected void onHandleIntent(@Nullable Intent intent) {
         if (!hasStarted) {
              initializeTimer();
              startTimer();
         }
    }

    public IBinder onBind(Intent intent) {
         return new RecordBinder(this);
    }

    public void onDestroy() {
          super.onDestroy();
          if (timer != null)
              timer = null;
    }
    // there are also a bunch of private methods and stuff...
}
0

There are 0 answers