Search code examples
javaandroidandroid-mediaplayermedia-player

How to resume MediaPlayer when paused


I want the MediaPlayer music to be paused when the app is minimized, and to resume from the same point when it's restored, but I can't do it, every time it starts from the beggining...

Here's what I have:

public class Main extends Activity {
MediaPlayer music;
int length;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    music = MediaPlayer.create(Main.this, R.raw.song);
    music.setLooping(true);
    music.start();

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    music.pause();
    length = music.getCurrentPosition();
}

@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();
    music.start();
    music.seekTo(length);
}
}

Solution

  • U seem to have put the statements in the wrong sequence, try this instead:

    music.seekTo(length);
    music.start();