Skip to content Skip to sidebar Skip to footer

In Android, When I Play Audio And Go To Other Activity, Audio Doesn't Stop After Coming Back

I'm new in Android environment, my problem is while I Play audio file and go to other activity or press back button, and again open my application where I've played audio, it doesn

Solution 1:

For a quick solution you can create a method like this:

void resetMediaPlayer() {
   if(mediaPlayer!=null) {
       try {
             mediaPlayer.reset();
       }
       catch(Exception e) {
           e.printStackTrace();
       }
   }
}

Then override the onBackPressed method in your activity and call resetMediaPlayer :

@Override
public void onBackPressed(){
    super.onBackPressed();
  resetMediaPlayer()
}

Or call it anywhere you need to stop your media player.

This is not a good way to stop media player though. for a better implementation you have to change your resetMediaPlayer method like this:

void resetMediaPlayer() {
    if(mediaPlayer!=null) {
        try {
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

And whenever you want to start Media Player you have to create a new instance of Media Player for example:

voidstartMediaPlayer(int selectedSong) {
    try {
        mediaPlayer = MediaPlayer.create(activity, selectedSong);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And also call resetMediaPlayer in onDestroy method of your activity:

@Override
protected void onDestroy() {
    super.onDestroy();
    resetPlayView();
}

Post a Comment for "In Android, When I Play Audio And Go To Other Activity, Audio Doesn't Stop After Coming Back"