How To Handle Mediaplayer Object Inside A Fragment Inside View Pager
I have viewpager which holds fragments, each fragment is having MediaPlayer object i.e each fragment is having audio attached to it. My requirement is if i swipe the viewpager,curr
Solution 1:
It is better to override onPause() and onResume() in fragment. And we need to save the current position for media player. So, I am using the shared preference to save the position for media player.
In onCreateView, mediaPlayer_position = getActivity().getSharedPreferences("PLAY_PAUSE", Activity.MODE_PRIVATE).getInt("CHECK_PLAY_PAUSE", 0);
@OverridepublicvoidonResume() {
super.onResume();
int position = getActivity().getSharedPreferences("PLAY_PAUSE", Activity.MODE_PRIVATE).getInt("CHECK_PLAY_PAUSE", 0);
if(position > 0) {
try {
mediaPlayer.setDataSource(mp3_link); //mp3_link from url to mediaplayer data source
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.seekTo(position);
mediaPlayer.start();
}
}
@OverridepublicvoidonPause() {
super.onPause();
if(mediaPlayer.isPlaying()) {
mediaPlayer_position = mediaPlayer.getCurrentPosition();
getActivity().getSharedPreferences("PLAY_PAUSE", Context.MODE_PRIVATE).edit().putInt("CHECK_PLAY_PAUSE", mediaPlayer_position).apply();
mediaPlayer.pause();
}
}
Ref: "https://www.hrupin.com/2011/02/example-of-streaming-mp3-mediafile-with-android-mediaplayer-class"
Post a Comment for "How To Handle Mediaplayer Object Inside A Fragment Inside View Pager"