androidandroid-mediaplayerandroid-lifecycleonresumeonpause

MediaPlayer not playing after reopening the app


When i add mediaplayer.start in onResume i was expecting to start the audio when i reopen the the app but it dindt start it

public MediaPlayer mediaPlayer;
int length = 0;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
  mediaPlayer = MediaPlayer.create(this, R.raw.andhadhun);
        mediaPlayer.start();
}
 @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mediaPlayer.pause();
        length = mediaPlayer.getCurrentPosition();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mediaPlayer.setOnPreparedListener(MediaPlayer::start);

    }

Solution

  • This will work, It pauses the MediaPlayer in onStop and resume in onResume

    public class MainActivity extends AppCompatActivity {
        private MediaPlayer mediaPlayer;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mediaPlayer = MediaPlayer.create(this, R.raw.audio);
            mediaPlayer.start();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if (!mediaPlayer.isPlaying() && mediaPlayer != null) {
                mediaPlayer.start();
            }
        }
    }