Search code examples
androidandroid-servicebackground-process

How to bind to a Service that was started by another instance of the application


I have a background Service that need to be running even if the application gets killed by Android. This is currently working perfectly.

My problem is that when I restart the application (with the background service still running), I want my Activity to bind to the service to have access to some of its methods. When I try to bind with a ServiceConnection, the onServiceConnected is never called.

final private ServiceConnection serviceConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        Log.d(TAG, "onServiceConnected");  //this is never called
        MyBackgroundService.ServiceBinder binder = (MyBackgroundService.ServiceBinder) service;
        backgroundService = binder.getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d(TAG, "onServiceDisconnected");
        backgroundService = null;
    }

};

private void bindBackgroundService(){
    this.bindService(new Intent(this, MyBackgroundService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}

Am I doing this the wrong way? Is it better to stop the Service and restart it?


Solution

  • Since the class that binded the background service is a singleton and my alarm broadcast receiver that is making sure the background service is always running instantiates this singleton, I had access to this singleton and I was trying to bind to the service that was already binded.