How to completely destroy Media Player on back pressed in an activity?

My problem is that I have used the MediaPlayer class in an activity to play music. The music is played online from a link, and I have used the prepareAsync method for audio. At the first time, the opening speed of the activity is very good and the music plays well. But after pressing the back button, and re-entering the activity, the opening speed of the activity becomes very slow. What should be done? Is it beacase of not well releasing the MediaPlayer?

Creating and control the Media player in my code:

` mediaPlayerMain = new MediaPlayer();
    mediaPlayerMain.setAudioStreamType(AudioManager.STREAM_MUSIC);

   //  below line is use to set our url to our media player.
    try {
        mediaPlayerMain.setDataSource(selectedAudioLink);

        // below line is use to prepare our media player.
        mediaPlayerMain.prepareAsync();

    } catch (IOException e) {
        e.printStackTrace();
    }


    mediaPlayerMain.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {

           playFile();

        }
    });


    }
    private void playFile(){

         // playing
        mediaPlayerMain.start();

    }
    private void pauseFile(){

      mediaPlayerMain.pause();
    }
       `

Stopping the media player in OnBackPressed method in my Activity:

   ` @Override
    public void onBackPressed() {

        try {
        if (mediaPlayerMain != null) {
            if (mediaPlayerMain.isPlaying())
                mediaPlayerMain.stop();
        }
        } catch (Exception e) {
        e.printStackTrace();
        }
      super.onBackPressed();
     }`

Upvotes: 0

Views: 34

Answers (1)

dev.bmax
dev.bmax

Reputation: 10621

You must call release() once you have finished using an instance of MediaPlayer to release acquired resources, such as memory and codecs.

Failing to release resources (resource leak) can cause starvation.

It's best practice to release resources (such as MediaPlayer) in accordance with the Activity / Fragment lifecycle (e.g. in onPause(), onStop(), onDestroy()).

Upvotes: 0

Related Questions