问题
I have created a media player . I run the application properly. But I want to resume my song when I restart my activity. Why does my audio restart when I restart my activity?
How can I do this? I don't understand. Can any one help me??
Here is my code.
public class Audio_Activity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null) {
length=mp.getCurrentPosition();
Log.e("Current ","Position -> " + length);
if(length > 0){
mp.seekTo(length);
mp.start();
btnChapter.setEnabled(false);
}
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
}
}
回答1:
To prevent this you should use a service for playing sounds while your activity goes to background. Refer to the android's documentation about the life-cycle of an activity to see what actually happens: https://developer.android.com/training/basics/activity-lifecycle/index.html
回答2:
Can you try:
mp.start();
mp.seekTo(length);
Referring to documentation of MediaPlayer:
public void start ()
Starts or resumes playback. If playback had previously been paused, playback will continue from where it was paused. If playback had been stopped, or never started before, playback will start at the beginning.
回答3:
Save the mp.getCurrentPosition in a persistence of some sort, sharedprefs for instance in onPause, call pause() on the mediaplayer.
In onResume, do mp.start(), mp.seekTo(savedPosition).
来源:https://stackoverflow.com/questions/17524681/resume-song-in-android