I am using android media player class for playing notification sound in my android Application.
MediaPlayer player = MediaPlayer.create(getApplicationContext(), R.raw.notify);
player.setLooping(false);
player.start();
I need to play different notification sounds in different Activities, so every time i need to play the sound i need to create media player instance and then i need to say start.
But instead of doing this, How can i maintain single instance of the media player throughout the application and use it in all the activities to play the sounds.
Can someone please suggest me the better way of implementing it. From my point of view i will create one singleton class and i will add all the MediaPlayer related function in this class.
Thanks.
You should consider the Singleton pattern. Make a class MyPlayer that has a static method getMediaPlayer()
that returns the same instance of MediaPlayer each time called.
I always do similar thing with a modified version of Singleton Pattern. Since context is needed everywhere in Android, I pass the context to the instance:
public class Asset{
public static Asset(Context context);
}
You can also have different singleton across different context scope, in this implementation, for example:
private static Hashtable<Context, Asset> instances;
public static Asset(Context context){
if (!instances.containKey(context)){
instances.put(context, new Asset(context));
return instances.get(context);
}
The advantage of this compare to classic singleton, is you can define the scope of your singletons. Sometimes you just need the instance stay in same Activity, but second Activity may have different instance. If you need it across different Activity, you just need to pass context.getApplicationContext().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With