Issue
I have music start playing in Activity A. When Activity B opens, Activity A closes, as well as the music from Activity A stops playing. When I return to Activity A, I would like the music to pick up playing from where it left off. How do I do this?
Solution
you need to store (persistently) the position that your media was at in onPause()
or onStop()
of activity A, and then in onResume()
check the value that was stored and call seekTo()
on your mediaplayer. Something like this:
to get your SharedPreferences objects:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEdit = prefs.edit();
To store and recall the position.
public void onPause(){
super.onStop();
//It might make more sense to do this right before you call startActivity()
//to launch activityB then here.
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
public void onResume(){
super.onResume();
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
}
Note if you use this method you'll also need to set the position to 0 when you are exiting ActivityA without going to B. Otherwise when you come back to it the music is not going to start at the beginning.
Answered By - FoamyGuy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.