In the course of project development, there may be a lot of use of global variables, in Android development, most people prefer to use application to save global variables. So let's get to the bottom of Android, what exactly is application? What's the effect?
The application class is used to maintain the global state of the application. We can provide our own implementation and indicate its name in the <application> tag of the Androidmanifest.xml file, which will result in the instantiation of our own application class when the application is created. The Android system creates an object of the application class for each program runtime and creates only one, so application can be said to be a class of singleton patterns. And the life cycle of the Application object is the longest in the whole program, and its life cycle is equal to the life cycle of the program. Because it is globally unique, objects that are obtained in different activity,service are the same object. Therefore, some data transfer, data sharing, data caching and other operations are carried out through application.
First create the MyApplication class that inherits from application, define the variable score, and create the Get and set methods.
1 Packagecom.example.whs.myapplication;2 3 Importandroid.app.Application;4 5 /**6 * Created by WHS on 17/5/1.7 */8 9 Public classMyApplicationextendsApplication {Ten Private intScore = 100; One A Public intGetscore () { - returnscore; - } the - Public voidSetScore (intscore) { - This. score =score; - } +}
Here is how to use the global variables we created, in Mainactivity, first to obtain the MyApplication object, because MyApplication inherits from application, so use the Getapplication () method to , you can then call MyApplication's Get or set method to access the global variable.
MyApplication application = (myapplication)this. getapplication (); Application.setscore ($); int score = Application.getscore ();
Note that android:name = "in <application> of the Androidmanifest.xml file needs to be modified before using MyApplication. MyApplication ", so that the system provides no access to the application, and access to our own created.
Global variables for the Android development series