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.
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:
In short, it should work if you invert these two lines:
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
getSherlockActivity().startService(playIntent);