Android Singleton with Global Context

前端 未结 2 1767
我寻月下人不归
我寻月下人不归 2020-11-28 03:28

Per the Android Documentation it states:

There is normally no need to subclass Application. In most situation, static singletons can provide the sam

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:28

    I have such class in my application :

    public class ApplicationContext {
    
        private Context appContext;
    
        private ApplicationContext(){}
    
        public void init(Context context){
            if(appContext == null){
                appContext = context;
            }
        }
    
        private Context getContext(){
            return appContext;
        }
    
        public static Context get(){
            return getInstance().getContext();
        }
    
        private static ApplicationContext instance;
    
        public static ApplicationContext getInstance(){
            return instance == null ?
                    (instance = new ApplicationContext()):
                        instance;
        }
    }
    

    and then for example in Launch Activity initialize it :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //init
        ApplicationContext.getInstance().init(getApplicationContext());
        //use via ApplicationContext.get()
        assert(getApplicationContext() == ApplicationContext.get());
    }
    

提交回复
热议问题