Application class usage in Android

Source: Internet
Author: User

Application class

Application and Activity,service are a system component of the Android framework, and when the Android program starts, a Application object is created to store some information about the system.

The Android system automatically 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 (singleton) mode.

Usually we do not need to specify a application, the system will automatically help us to create, if you need to create their own application, it is very simple! Create a class to inherit the application and register it in the application tag in the Androidmanifest.xml file (just add the Name property to the application tag, adding your own application's name).

When application is started, a PID, the process ID, is created, and all activity is run on this process. Then we initialize the global variables when the application is created, all the activity of the same application can fetch the values of these global variables, in other words, we change the values of these global variables in one activity, Then the value of the other activity in the same application will change.

The life cycle of an Application object is the longest in the entire program, and its life cycle is equal to the program's life cycle. Because it is a global singleton, the objects obtained in different activity,service are the same object. So you can do some things through application, such as: data transfer, data sharing and data caching.

Application Scenarios:

In Android, you can implement application-level global variables by inheriting the application class, a global variable that is more secure than a static class, and will not be released until all of the app's activity is destory out.

See the following code:

 PackageCom.tugepclp_driver.config;ImportJava.io.File;Importjava.util.ArrayList;Importjava.util.List;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;Importandroid.app.Application;ImportAndroid.app.NotificationManager;ImportAndroid.content.Context;ImportAndroid.content.pm.PackageInfo;ImportAndroid.content.pm.PackageManager;Importandroid.content.pm.PackageManager.NameNotFoundException;Importandroid.os.Environment;ImportAndroid.os.StrictMode;ImportCom.baidu.mapapi.SDKInitializer;Importcom.tugepclp_driver.utils.NetworkUtils; Public classAppapplicationextendsApplication { Public StaticString Mappname;//App Name     Public Static intMnetworkstate = Networkutils.networn_none;//Network     Public StaticString Mdownloadpath;//Download Path     Public Static intMversioncode;//version     Public Static intMlatestversioncode;//New version number     Public StaticString Mversionname;//Version name     Public Static BooleanMshowupdate =true;//whether to show updates     Public StaticString Msdcarddatadir;//SD card Path     Public StaticString Mapkdownloadurl =NULL;//apk Download Path    PrivateList<activity> activities;//used to save pages    Private Staticappapplication minstance; PrivateNotificationmanager Mnotificationmanager; Private intBiaomsgnum = 0;//task acceptance, number of darts    Private intEmailmsgnum = 0;//message notification, number of messages@Override Public voidonCreate () {minstance= This; Activities=NewArraylist<activity>();        Initdb ();        Initmap ();        Initenv ();        Initlocalversion (); Sysbasedata.getinstance (). Photo_string= ""; Mnotificationmanager=(Notificationmanager) Getsystemservice (Android.content.Context.NOTIFICATION_SERVICE); }    /*** Database*/     Public voidInitdb () {sdkinitializer.initialize ( This); }     PublicNotificationmanager Getnotificationmanager () {if(Mnotificationmanager = =NULL) Mnotificationmanager=(Notificationmanager) Getsystemservice (Android.content.Context.NOTIFICATION_SERVICE); returnMnotificationmanager; }    /*** Map*/     Public voidInitmap () {}/*** Mode (this method is for 4.2, multithreading calls problem processing)*/@SuppressLint ("Newapi")     Public voidCheckmode () {intFV =Android.os.Build.VERSION.SDK_INT; if(FV > 10) {Strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()            . Penaltylog (). build ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects ()        . Penaltylog (). Penaltydeath (). build ()); }    }     Public voidinitenv () {mappname= "Tugepclp_driver"; Mdownloadpath= "/tugepclp_driver/download"; if(Environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED)) {Fil E file=NewFile (Environment.getexternalstoragedirectory (). GetPath ()+ "/tugepclp_driver/config/"); if(!file.exists ()) {                if(File.mkdirs ()) {Msdcarddatadir=File.getabsolutepath (); }            } Else{Msdcarddatadir=File.getabsolutepath (); }} mnetworkstate= Networkutils.getnetworkstate ( This); //Checkdomain (Mdomain, false);    }     Public voidExitapp (Context context) { for(Activity a:activities) {if(A! =NULL) {a.finish (); }        }        //android.os.Process.killProcess (Android.os.Process.myPid ());System.exit (0); }     Public Staticappapplication getinstance () {returnminstance; }     Public voidaddactivity (activity activity) {Activities.add (activity); }     Public voidExitclass () { for(Activity a:activities) {if(A! =NULL) {a.finish (); }        }    }     Public intGetbiaomsgnum () {returnBiaomsgnum; }     Public voidSetbiaomsgnum (intbiaomsgnum) {         This. Biaomsgnum =Biaomsgnum; }     Public intGetemailmsgnum () {returnEmailmsgnum; }     Public voidSetemailmsgnum (intemailmsgnum) {         This. Emailmsgnum =Emailmsgnum; }     Public voidinitlocalversion () {PackageInfo pinfo; Try{pinfo= This. Getpackagemanager (). Getpackageinfo ( This. Getpackagename (), packagemanager.get_configurations); Mversioncode=Pinfo.versioncode; Mversionname=Pinfo.versionname; } Catch(namenotfoundexception e) {e.printstacktrace (); }    }}

Mainfest configuration:

< Application             Android:name = "Com.tugepclp_driver.config.AppApplication"             android:allowbackup= "true"            android:icon= "@drawable/ic_launcher"              android:label= "@string/app_name"            android:theme= "@ Android:style/theme.notitlebar ">

Application class usage in Android

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.