There are questions with a similar title, but them all about Context that you get in constructor.
There are RecyclerView with items and some other views where play\pause button is present.
This class allows this views to play only one file at a time. If view_1 is playing and you press play at view_2 - file_2 will be played.
There is an ImageButton mPlayPauseButton in this class. It is needed to set ImageButton at view_1 to paused_state. And set ImageButton at view_2 to playing_state.
Lint Warning
Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run) A static field will leak contexts.
public class CommentsAudioPlayer {
private static MediaPlayer mPlayer;
private static ImageButton mPlayPauseButton;
private static void init(ImageButton imageButton){
mPlayer = new MediaPlayer();
mPlayPauseButton = imageButton;
}
public static void startPlaying(String dataSource, ImageButton imageButton) {
init(imageButton);
try {
mPlayer.setDataSource(dataSource);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopPlaying();
}
});
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mPlayer.start();
}
});
mPlayer.prepareAsync();
if (mPlayPauseButton != null) mPlayPauseButton.setSelected(true);
} catch (Exception e) {
Log.e("Player", "Error trying to start playing:\n" + e.toString());
}
}
public static void stopPlaying() {
if (mPlayPauseButton != null)
mPlayPauseButton.setSelected(false);
mPlayPauseButton = null;
if (mPlayer!=null)
mPlayer.release();
mPlayer = null;
}
}