Sartheris Stormhammer
Sartheris Stormhammer

Reputation: 2564

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);
}
}

Upvotes: 5

Views: 4871

Answers (2)

codeMan
codeMan

Reputation: 5758

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

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

Upvotes: 5

user2273765
user2273765

Reputation:

You need to find the last position first, then start playing again. Do this:

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

Upvotes: 1

Related Questions