holo foil
holo foil

Reputation: 11

Media player plays after service is destroyed

I have a bound service that I want to stop through a notification click.

In my main_activity I do this onDestroy to unbind my service:

public void onDestroy(){ 
        super.onDestroy();
        if(mediaPlayerBound){
                 System.out.println(mediaPlayerBound);
                 unbindService(mServCon);
                 mMediaPlayerServiceBound = false;
        }

This part works fine as I get that mediaPlayerBound is true and so the service is getting unbound.

Then in my service: I call the following after receiving a broadcast.

stopForeground(true);
stopSelf();

Lastly:

in OnDestroy within the service I use:

public void onDestroy(){
    this.unregisterReceiver(nextBroadCast);
    System.out.println("Stopped Service");
    }

Now my question is, I started playing a song with the mediaPlayer but it persists even after I have gotten confirmation that that the service has reached onDestroy. What do I do to stop it from playing as soon as I call stopSelf(); ?

Upvotes: 1

Views: 822

Answers (3)

Divyesh Kalotra
Divyesh Kalotra

Reputation: 204

add this code in your service file . onTaskRemoved is call when your app is closing.so it stop service

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
 if(player.isPlaying())
 {
    player.stop();
 } 

    player.release();

    stopSelf();
}


@Override
public void onDestroy() {
 if(player.isPlaying())
 {
    player.stop();
 }

    player.release();
    stopSelf();

}

And in Your Activity place code when you want stop runing service .

    Intent i=new Intent(this, MediaSongServiece.class);
    stopService(i);

Upvotes: 1

Dev.Faith
Dev.Faith

Reputation: 59

A short note is that if you used MediaPlayer to play music, you would stop MediaPlayer.

Put this source in Destroy().

private void stopPlay() {
   this.unregisterReceiver(nextBroadCast);
   if (mediaPlayer != null) {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
    }
}

Upvotes: 0

A.s.ALI
A.s.ALI

Reputation: 2082

In service I read it somewhere that you will not always watch onDestroyed has been called. There are many terms and condition. but as you said you are receiving this event then try the below code. but I am guessing you are able to get your media player instance in it. so here is a workaround

 @Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(nextBroadCast);
yourMediaPlayer= MediaPlayer.create(x.this,R.raw.sound);
if(yourMediaPlayer.isPlaying())
{
  yourMediaPlayer.stop();
  yourMediaPlayer.release();
}
}

Upvotes: 1

Related Questions