How to maintain single instance of MediaPlayer [Android]

后端 未结 3 1074
渐次进展
渐次进展 2021-01-18 21:40

I am using android media player class for playing notification sound in my android Application.

MediaPlayer player = MediaPlayer.create(getApplicationContext         


        
3条回答
  •  一个人的身影
    2021-01-18 22:10

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

提交回复
热议问题