Android global variable

前端 未结 14 1089
眼角桃花
眼角桃花 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 extend the base android.app.Application class and add member variables like so:

    public class MyApplication extends Application {
    
        private String someVariable;
    
        public String getSomeVariable() {
            return someVariable;
        }
    
        public void setSomeVariable(String someVariable) {
            this.someVariable = someVariable;
        }
    }
    

    In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication" attribute to the existing application tag):

    
    

    Then in your activities you can get and set the variable like so:

    // set
    ((MyApplication) this.getApplication()).setSomeVariable("foo");
    
    // get
    String s = ((MyApplication) this.getApplication()).getSomeVariable();
    

提交回复
热议问题