Search code examples
javaandroidandroid-activityservice

Don't destroy a bound Service on Activity destroy


Currently, I need a bound (Music)Service, because I need to interact with it. But I also want it to not be stopped, even when all components have unbound themselves.

As the Android Developer Guide says

"[...] Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed."

The Guide also says

"[...] your service can work both ways—it can be started (to run indefinitely) and also allow binding."

In my application, the service is started when the application starts. I want to have this service destroyed only by a user-click on a close-button I am displaying in a custom notification. But currently, when I am destroying my MainActivity the service also stops.

This is where I am now, this is called when I want to create my Service:

public void createServiceConnection(){
     musicConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
            musicSrv = binder.getService();
            attachMusicService();
        }
    };
}

...which calls this:

public void attachMusicService(){
    playerFragment.setMusicService(musicSrv);
    musicSrv.attach(context); //need this for my listeners, nevermind
    bindService(context);
}

...which calls this:

    public void bindService(Context act){
        if(playIntent==null){
            playIntent = new Intent(act, MusicService.class);
            act.startService(playIntent);

            act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        }else{
            act.startService(playIntent);
            act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        }

//finished. I can do stuff with my Service here.
    }

Have I misunderstood something? I feel like the service should keep running, even the activity is destroyed, because I first made a started service and then bound to it.


Solution

  • Seems like the code was correct.

    According to this Question I found out that my problem was the notification I displayed, wich is pretty interesting.

    Seems like that a Service that is created for running indefinitely needs to have a Notification wich is displayed by startForeground(NOTIFY_ID, notification);.

    I showed my notification with notificationmanager.notify(NOTIFY_ID, notification); before, now I have

     `notificationmanager.notify(NOTIFY_ID, notification);
      startForeground(NOTIFY_ID, notification);`
    

    and the service won't stop anymore after all my bound Activities are destroyed.