I am going to create a simple Android application to play the sound at the click of a button, but I am struggling with understanding a singleton design pattern that would be very useful in this application. What I'm trying to achieve is to have a number of actions and use only one instance of MediaPlayer among them, so that the user presses the play button and if he press the same button or another button with the same or different activity, the sound will stop.
Here is my code, but after clicking the button another instance of MediaPlayer is created twice, and you can play the same sound here simultaneously
public class MyMediaPlayer {
MediaPlayer mp;
private static volatile MyMediaPlayer instance = null;
private MyMediaPlayer() { }
public static MyMediaPlayer getInstance() {
if (instance == null) {
synchronized (MyMediaPlayer.class) {
if (instance == null) {
instance = new MyMediaPlayer();
}
}
}
return instance;
}
}
and MainActivity.java:
public class MainActivity extends Activity {
private MyMediaPlayer player = getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playSound(View view){
player.mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
player.mp.start();
}
}
, , Singleton. , . , MediaPlayer, ?
!