Don't destroy a bound Service on Activity destroy

Viewed 1241

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.

2 Answers
Related