Android Combat Simple Tutorial-the 30th gun (instance parsing application usage)

Source: Internet
Author: User

First, 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.

second, global settings and get variables

Let's use an example to understand its usage and get the global user name.

1.myapplication.java:

Package Com.example.applicationdemo;import Android.app.application;public Class MyApplication extends Application { private static final String VALUE = "Jay";        private String value;        @Override public    void OnCreate ()    {        super.oncreate ();        SetValue (VALUE); Initialize global variable    } public        void SetValue (String value)    {        this.value = value;    }        Public String GetValue ()    {        return value;    }}

2.mainactivity.java:

Package Com.example.applicationdemo;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.util.log;public class Mainactivity extends activity{    private MyApplication app;        @Override public    void OnCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);                App = (myapplication) getapplication (); Get CustomApplication object                log.i ("firstactivity", "Initial value =====" + app.getvalue ());//Get the global variable value in the process to see if it is an initialization value                App.setvalue ("Harvey Ren"); Reset the value                log.i ("Firstactivity", "Modified =====" + app.getvalue ());//Get the global variable value in the process again to see if it is modified                Intent Intent = new Intent ();        Intent.setclass (this, secondactivity.class);        StartActivity (intent);    }}

3.secondactivity.java:

Package Com.example.applicationdemo;import Android.app.activity;import Android.os.bundle;import android.util.Log; public class Secondactivity extends activity{    private MyApplication app;        @Override    protected void onCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main2);        App = (myapplication) getapplication (); Get Application       log.i ("secondactivity", "Current value =====" + app.getvalue ());//Get Global Value    }}

4. Note the changes to the configuration file:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.applicationdemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses -SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowba" Ckup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:name= "COM.E Xample.applicationdemo.MyApplication "Android:theme=" @style/apptheme "> <activity android: Name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <activity android:name=". Secondactivity "Android:label= "@string/app_name" > </activity> </application></manifest> 

Code that needs to be added (individually labeled):

Run the following example:


third, global access to the context objectcontext objects are often used in Android, such as toasts, manipulating databases, starting activity, and sending broadcasts, so let's look at how to get the context object globally. 1. Modify Myapplication.java:
Package Com.example.applicationdemo;import Android.app.application;import Android.content.context;public class MyApplication extends application {private static final String VALUE = "Jay";p rivate String value;private static Context C Ontext; @Overridepublic void OnCreate () {super.oncreate (); SetValue (VALUE);//Initialize global variable context = Getapplicationcontext () ;//Get Global context}public void SetValue (String value) {this.value = value;} Public String GetValue () {return value;} public static Context GetContext () {//Return context object return context;}}
2. Modify Secondactivity.java:
Package Com.example.applicationdemo;import Android.app.activity;import Android.os.bundle;import android.util.Log; Import Android.widget.toast;public class Secondactivity extends activity{    private MyApplication app;        @Override    protected void onCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main2);        App = (myapplication) getapplication (); Get the application       log.i ("secondactivity", "Current value =====" + app.getvalue ());//Get Global value              toast.maketext ( Myapplication.getcontext (), "Get Global context! with Application", 3). Show ();    }}
3. Run the following example:


is not very good, no longer in the method to pass the context object, this is not very convenient?

My favorite friends are interested in me! Thanks for your support!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat Simple Tutorial-the 30th gun (instance parsing application usage)

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.