Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain single instance of MediaPlayer [Android]

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.

like image 538
User7723337 Avatar asked May 15 '12 06:05

User7723337


2 Answers

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.

like image 133
K_Anas Avatar answered Nov 15 '22 06:11

K_Anas


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().

like image 35
xandy Avatar answered Nov 15 '22 06:11

xandy