Android global variable

前端 未结 14 1087
眼角桃花
眼角桃花 2020-11-21 23:32

How can I create global variable keep remain values around the life cycle of the application regardless which activity running.

14条回答
  •  离开以前
    2020-11-22 00:04

    You can use a Singleton Pattern like this:

    package com.ramps;
    
    public class MyProperties {
    private static MyProperties mInstance= null;
    
    public int someValueIWantToKeep;
    
    protected MyProperties(){}
    
    public static synchronized MyProperties getInstance() {
            if(null == mInstance){
                mInstance = new MyProperties();
            }
            return mInstance;
        }
    }
    

    In your application you can access your singleton in this way:

    MyProperties.getInstance().someValueIWantToKeep
    

提交回复
热议问题