Get application context from non activity singleton class

前端 未结 3 1948
日久生厌
日久生厌 2020-11-27 18:14

In my android project, I have ImageAdapter class in which I pass app context for some further needs.

public class ImageAdapter extends BaseAdapter {
    priv         


        
3条回答
  •  执念已碎
    2020-11-27 18:20

    Update: 06-Mar-18

    Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself.

    public class MyApplication extends Application {
    
        private static MyApplication mContext;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mContext = this;
        }
    
        public static MyApplication getContext() {
            return mContext;
        }
    }
    

    Previous Answer

    You can get the the application context like this:

    public class MyApplication extends Application {
    
        private static Context mContext;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mContext = getApplicationContext();
        }
    
        public static Context getContext() {
            return mContext;
        }
    }
    

    Then, you can call the application context from the method MyApplication.getContext()

    Don't forget to declare the application in your manifest file:

    
    

提交回复
热议问题