Reputation: 112
I've created a simple app that has two buttons that will play and stop a song. Everything is working as it should.
However I want it to pause the song when the app goes onPause and Resume playing the song when the app is up again.
I have tried:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mp.start();
}
But that starts the song automatically when the app starts the first time. And it also messes up the app when you click play, the song hacks and the app crashes.
Here is the onPause and onDestroy:
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mp.pause();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.stop();
mp.release();
} }
Upvotes: 2
Views: 191
Reputation: 2307
In the onResume()
Method check if the song is already playing you shouldn't start it again.
So now your onResume becomes
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (mp != null && mp.getCurrentPosition() > 0) {
mp.start();
}
}
This will fix your crash.
Now for the second part, how do you resume playing from the position where it was paused.
As per the Documentation MediaPlayer
class has two method getCurrentPosition()
and seekTo(int msec)
You can use SharedPreferences
to store the currentPosition in onPause()
Method and in your onResume()
get the position for the SharedPreferences
and seekTo(int msec)
that position and then start playback again.
Upvotes: 4
Reputation: 984
Try the below code
@Override
protected void onResume() {
super.onResume();
if (mp != null && mp.getCurrentPosition() > 0) {
mp.start();
}
}
Upvotes: 2