Static way to get 'Context' in Android?

前端 未结 19 2736
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  被撕碎了的回忆
    2020-11-21 07:11

    I use a variation of the Singleton design pattern to help me with this.

    import android.app.Activity;
    import android.content.Context;
    
    public class ApplicationContextSingleton {
        private static Activity gContext;
    
        public static void setContext( Activity activity) {
            gContext = activity;
        }
    
        public static Activity getActivity() {
            return gContext;
        }
    
        public static Context getContext() {
            return gContext;
        }
    }
    

    I then call ApplicationContextSingleton.setContext( this ); in my activity.onCreate() and ApplicationContextSingleton.setContext( null ); in onDestroy();

提交回复
热议问题