Static way to get 'Context' in Android?

前端 未结 19 2687
猫巷女王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:13

    If you for some reason want Application context in any class, not just those extending application/activity, maybe for some factory or helper classes. You can add the following singleton to your app.

    public class GlobalAppContextSingleton {
        private static GlobalAppContextSingleton mInstance;
        private Context context;
    
        public static GlobalAppContextSingleton getInstance() {
            if (mInstance == null) mInstance = getSync();
            return mInstance;
        }
    
        private static synchronized GlobalAppContextSingleton getSync() {
            if (mInstance == null) mInstance = 
                    new GlobalAppContextSingleton();
            return mInstance;
        }
    
        public void initialize(Context context) {
            this.context = context;
        }
    
        public Context getApplicationContext() {
            return context;
        }
    }
    

    then initialize it in your application class's onCreate with

    GlobalAppContextSingleton.getInstance().initialize(this);
    

    use it anywhere by calling

    GlobalAppContextSingleton.getInstance().getApplicationContext()
    

    I don't recommend this approach to anything but application context however. As it can cause memory leaks.

提交回复
热议问题