In Java, if you want to use a global variable, you typically define a variable of the public static type. But this approach does not conform to the Android framework, and Android uses the application context.
Application is a base class, and the function of the base class is to get the entire app's state, and we need to define a class to inherit the base class ourselves. The code is as follows:
Package COM.TIANJF;
Import android.app.Application;
public class MyApplication extends application {
private boolean mhaspassword;
public Boolean Ismhaspassword () {return
mhaspassword;
}
public void Setmhaspassword (Boolean mhaspassword) {
This.mhaspassword = Mhaspassword;
}
@Override public
void OnCreate () {
Mhaspassword = true;
Super.oncreate ();
}
We define a myapplication inherited from application, define a global variable Mhaspassword, and then copy the OnCreate method of the base class, OnCreate is responsible for assigning initial values to all global variables.
We also need to add the custom application class to the Androidmanifest.xml code as follows:
<application
android:name= "MyApplication" ........ ......... .....
...................
</application>
The purpose of this: When the app's process is created, the class is instantiated, the OnCreate method is executed, and the initial value is assigned to all global variables.
In this way, all the activity will share the variables within the class.
Here are two activity tests, and when an activity changes the value of a global variable, see if another activity can take the changed value.
Applicationdemoactivity.java
package COM.TIANJF;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener; public class Applicationdemoactivity extends activity implements Onclicklistener {private static
Final String TAG = "applicationdemoactivity";
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Findviewbyid (R.id.button). Setonclicklistener (this); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.butt
On:myapplication MyApplication = (myapplication) getapplication ();
LOG.I (TAG, String.valueof (Myapplication.ismhaspassword ())); Myapplication.setmhaspassword (FALSE);
Intent Intent = new Intent (this, anotheractivity.class);
StartActivity (Intent);
Break
Default:break; }
}
}