Android Advanced Programming Note (iii) Introduction to the Application class

Source: Internet
Author: User

Each time you run the app, the application class remains instantiated. Unlike activity, configuration changes do not cause the application to restart. By inheriting the application class, you can complete 3 tasks:

· The application-level events for the Android runtime broadcast are made accordingly.

· Passes an object between application components.

· Manage and maintain resources used by multiple application components.

The latter two work better by using a single-state class. The implementation of application is inherently single, and should be implemented as a single state in order to provide access to its methods and member variables.

I. Extension and use of the application class

The following program expands the framework code of the application class and implements it as a single state.

1  Public classMyApplicationextendsApplication {2     Private StaticMyApplication Singleton;3     4      Public StaticMyApplication getinstance () {5         returnSingleton;6     }7     8 @Override9      Public Final voidonCreate () {Ten         Super. OnCreate (); OneSingleton = This; A     } -}

It is important to note that after you create a new application class, you need to register it in the application node of manifest as follows:

1 <Application2         Android:allowbackup= "true"3 Android:name=". MyApplication "4 Android:icon= "@drawable/ic_launcher"5 Android:label= "@string/app_name"6 Android:theme= "@style/apptheme" >7         <Activity8             Android:name=". Mainactivity "9 Android:label= "@string/app_name" >Ten             <Intent-filter> One                 <ActionAndroid:name= "Android.intent.action.MAIN" /> A  -                 <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> -             </Intent-filter> the         </Activity> -</Application>

The application implementation will be instantiated when the application starts running. Create a new state variable and a global resource, which we can use in the program in the following ways:

1 MyApplication myApp = Myapplication.getinstance (); // get the Application class instantiation object 2 myapp.settest ("test data"); // Change state variables 3 String test = Myapp.gettest (); // Get state variable

We know that there are many ways to transfer variables in activity, such as intent, but like some commonly used state variables (such as user userid), it can easily lead to logical confusion if it is passed through the intent way every time. At this point, we can save this common public variable to the application class, which is convenient to get directly from the application class, no matter which activity needs it. The following is a simple example of how the application class achieves the shared variable effect:

Example Description: Create two activity, use one of the activity to change the variable in application, and then verify the change in another activity. (example is simple, can explain the problem) First look at:

1, first create MyApplication to inherit application class

1  Public classMyApplicationextendsApplication {2     Private StaticMyApplication Singleton;3     PrivateString test;4      Public StaticMyApplication getinstance () {5         returnSingleton;6     }7      PublicString gettest () {8         returntest;9     }Ten      Public voidsettest (String test) { One          This. Test =test; A     } - @Override -      Public Final voidonCreate () { the         Super. OnCreate (); -Singleton = This; -     } -}

The above code, in the MyApplication class, contains a MyApplication instance variable and a test variable.

2. Get the instantiated object of MyApplication in mainactivity and change the value of the test variable in MyApplication.

1  Public classMainactivityextendsActivity {2     PrivateMyApplication myApp;3 EditText ettest;4 Button Bngo;5 @Override6     protected voidonCreate (Bundle savedinstancestate) {7         Super. OnCreate (savedinstancestate);8 Setcontentview (r.layout.activity_main);9MYAPP = Myapplication.getinstance ();//get the Application class instantiation objectTenEttest = (EditText) Findviewbyid (r.id.et_test);//Bound Control OneBngo = (Button) Findviewbyid (R.ID.BN_GO);//Bound Control ABngo.setonclicklistener (NewOnclicklistener () { - @Override -              Public voidOnClick (View arg0) { theMyapp.settest (Ettest.gettext (). toString ());//change the value of the test variable in MyApplication -Intent Intent =NewIntent (Mainactivity.this, testactivity.class); - startactivity (intent); -             } +         }); -     } +}

3. Remove the test value from the MyApplication in testactivity and display it on the TextView.

1  Public classTestactivityextendsActivity {2     PrivateString test;3 @Override4     protected voidonCreate (Bundle savedinstancestate) {5         Super. OnCreate (savedinstancestate);6 Setcontentview (r.layout.activity_test);7TextView tvShow =(TextView) Findviewbyid (r.id.tv_show);8Test =myapplication.getinstance (). Gettest ();9 tvshow.settext (test);Ten     } One}

Second, rewrite the application lifecycle events

The application class provides event handlers for the creation and termination of applications, low-availability memory, and configuration changes.

By rewriting the method, you can implement your own application behavior for several of these scenarios:

· OnCreate called when an application is created. This method can be overridden to instantiate the application's configuration and to create and instantiate state variables and shared resources for any application.

· Onlowmemory: When the system is in a resource-deficient state, an application with good behavior can free up additional memory. This method is typically called only if the background process has terminated, but the foreground application is still missing memory. You can either empty the cache or release unnecessary resources by overriding this method.

· Ontrimmemory: As an application-specific alternative to onlowmemory, it is introduced in Android 4.0 (API level 13).

· Onconfigurationchanged: When configuration changes, application objects are not terminated and restarted. If the value used by your application needs to be reloaded when the configuration changes, you can do so by overriding this method.

The following is the code for what cycle events are rewritten (no specific functionality is implemented):

1  Public classMyApplicationextendsApplication {2     Private StaticMyApplication Singleton;3      Public StaticMyApplication getinstance () {4         returnSingleton;5     }6     7 @Override8      Public Final voidonCreate () {9         Super. OnCreate ();TenSingleton = This; One     } A      - @Override -      Public Final voidonlowmemory () { the         Super. Onlowmemory (); -     } -      - @Override +      Public voidOntrimmemory (intLevel ) { -         //This method is introduced in Android 4.0 (API level 13), please note when using.  +         Super. Ontrimmemory (level); A     } at      - @Override -      Public voidonconfigurationchanged (Configuration newconfig) { -         Super. onconfigurationchanged (newconfig); -     } -}

Android Advanced Programming note (iii) Introduction to application class

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.