Search code examples
androidnotificationsactivity-finish

Notification getting killed after finish


I have a service class which plays background music and when I come out of the app also the music plays and notification is shown like how I want . I have 2 pages. 1(main activity) and 2(another activity) . Now I have requirement of starting (1) from (2) so I start activity (1) and call finish on activity(2) . My control goes to (1) where I press a button to select songs and add to playlist and I start activity(2) again calling finish on (1) . I do this finish because without finish if I press back on (2) I would again get (1) where I added songs which I dont want. Now if I go to (1) and play song and press back notification cancels and music stops . I dont know what could be wrong. Can anyone please help?

Activity 1:

@Override
public void onDestroy() {

    if (musicBound) {

        getSherlockActivity().unbindService(musicConnection);
        musicBound = false;

    }

    Log.d(TAG, "on destroy=" + musicSrv.isPlaying()); 
    if (musicSrv != null && musicSrv.isPlaying() == false) { //doesnt go inside still music stops and not killed
        getSherlockActivity().stopService(playIntent);
        musicSrv.cancelNotification();
        musicSrv = null;
    }
    countTime = 0;

    super.onDestroy();

}

@Override
public void onStart()

{
    super.onStart();

    if (playIntent == null) {
        playIntent = new Intent(getSherlockActivity(), MusicService.class);
    }

    getSherlockActivity().bindService(playIntent, musicConnection,
            Context.BIND_AUTO_CREATE);

    getSherlockActivity().startService(playIntent);

}

P.S. I am not calling stopForeground or stopService also anywhere . This piece of code works fine if finish was not called . Why finish is spoiling things here? Confused.


Solution

  • If you start a service with bindService(), it will be destroyed when you call unbindService(). Just start it with startService() if you don't want this behavior but remember to call stopService() (or stopSelf() from the service) when in can be destroyed.

    See the documentation about started and bound services. A small extract:

    • Started - A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
    • Bound - A service is "bound" when an application component binds to it by calling bindService(). (...) A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

    In short, it should work if you invert these two lines:

    bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
    getSherlockActivity().startService(playIntent);