Each time an application runs, the application class of the application remains instantiated. You can complete the following three tasks by extending the applicaiton class:
1. Respond to application-level events broadcast during android runtime, such as low and low events.
2. Transfer objects (global variables) between application components ).
3. manage and maintain resources used by multiple application components.
The next two tasks will be better done by using the singleton class. The application is instantiated when an application process is created.
The following is the sample code for extending the Application:
Import android. app. application; public class MyApplication extends Application {private static MyApplication singleton; // return to the Application instance public static MyApplication getInstance () {return singleton;} @ Overridepublic void onCreate () {super. onCreate (); singleton = this ;}}After creating your own Application, register the application in mainfest as follows:
For get and set:
Assume that MyApplication has the str variable and provides getter and setter, as follows:
Package com. example. i18n; import android. app. application; public class MyApplication extends Application {private static MyApplication singleton; private String str; // return to the Application instance public static MyApplication getInstance () {return singleton;} @ Overridepublic void onCreate () {super. onCreate (); singleton = this;} public String getStr () {return str;} public void setStr (String str) {this. str = str ;}}
Use str and assign values:
MyApplication.getInstance().setStr("hello,bitch!");String mystr = MyApplication.getInstance().getStr();Log.e("str",mystr+"");
Write it here first. Good night.