Comprehensive analysis of the use of Application

Comprehensive analysis of the use of Application

[[435976]]

Preface

The Application class is something we will encounter in every development. Every APP will have an Application instance, which has the same life cycle as the APP. The Application and the APP "live and die together";

Let's talk about it today, strengthen your foundation and inner strength, and make yourself more confident;

1. What is Application?

  • The Android system creates one and only one Application class object for each program running, so Application can be said to be a class in singleton mode;
  • The life cycle of the application object is the longest in the entire program, and its life cycle is equal to the life cycle of the program. Since it is a global singleton, the objects obtained in different Activities and Services are the same object;
  • Application, like Activity and Service, is a system component of the Android framework. When an Android program is started, the system will create an Application object to store some system information;
  • Usually we don't need to specify an Application, the system will automatically create one for us. If you need to create your own Application, it is also very simple. Create a class that inherits Application and register it in the application tag in the AndroidManifest.xml file;
  • When you start an application, the system creates a PID, or process ID, and all activities run on this process.
  • The life cycle of the Application object is the longest in the entire program. Its life cycle is equal to the life cycle of the program. Because it is a global singleton, the objects obtained in different Activities and Services are the same object. Therefore, some operations such as data transfer, data sharing, and data caching can be performed through the Application.

2. Methods of the Application class

1. onCreate() method

Inherited from ContextWarpper class

  1. public class Application extends ContextWrapper implements ComponentCallbacks2 {
  2. ...
  3. ...
  4. }
  5. public void onCreate() {
  6. }
  • It is called when the Application is created, and is generally used to initialize some things, such as global objects and environment configuration;
  • Set up global shared data, such as global shared variables, methods, etc.;

Notice:

Shared data is only valid during the life cycle of the application. When the application is killed, the data will also be cleared, so only some temporary shared data can be stored.

Please do not perform time-consuming operations, otherwise it will slow down the application startup;

2. onConfigurationChanged(Configuration newConfig)

Rewrite this method to monitor some configuration information change events of APP (such as screen rotation, etc.);

This method is called when the configuration information changes;

  1. registerComponentCallbacks(new ComponentCallbacks2() {
  2. @Override
  3. public void onConfigurationChanged(Configuration newConfig) {
  4. ...
  5. }
  6. });

3. onLowMemory() method

  • Rewrite this method to monitor events when the overall memory of the Android system is low;
  • Calling time: when the overall memory of the Android system is low;
  1. registerComponentCallbacks(new ComponentCallbacks2() {
  2. @Override
  3. public void onLowMemory() {
  4. }
  5. });

4. onTerminate() method

  • Notify the application of current memory usage (identified by memory level)
  • Release memory resources to different degrees according to current memory usage to avoid being killed directly by the system & optimize the performance experience of the application;
  • When the system is low on memory, it will kill processes from the lowest to the highest in the LRU Cache, giving priority to killing applications that occupy the most memory.
  1. registerComponentCallbacks(new ComponentCallbacks2() {
  2. @Override
  3. public void onTrimMemory( int   level ) {
  4. // The Android system will pass in the corresponding level based on the current memory usage
  5. // The following example uses clearing the cache as an example
  6. super.onTrimMemory( level );
  7. . if ( level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
  8. mPendingRequests.clear();
  9. mBitmapHolderCache.evictAll();
  10. mBitmapCache.evictAll();
  11. }
  12. });

5. registerActivityLifecycleCallbacks() and unregisterActivityLifecycleCallbacks()

These two methods are used to register or unregister the life cycle monitoring of all Activities in the APP;

When the life cycle of the Activity in the APP changes, the method in ActivityLifecycleCallbacks will be called:

  1. registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
  2. @Override
  3. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  4. Log.e(TAG, "onActivityCreated: " + activity.getLocalClassName());
  5. }
  6. @Override
  7. public void onActivityStarted(Activity activity) {
  8. Log.e(TAG, "onActivityStarted: " + activity.getLocalClassName());
  9. }
  10. @Override
  11. public void onActivityResumed(Activity activity) {
  12. Log.e(TAG, "onActivityResumed: " + activity.getLocalClassName());
  13. }
  14. @Override
  15. public void onActivityPaused(Activity activity) {
  16. Log.e(TAG, "onActivityPaused: " + activity.getLocalClassName());
  17. }
  18. @Override
  19. public void onActivityStopped(Activity activity) {
  20. Log.e(TAG, "onActivityStopped: " + activity.getLocalClassName());
  21. }
  22. @Override
  23. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  24. }
  25. @Override
  26. public void onActivityDestroyed(Activity activity) {
  27. Log.e(TAG, "onActivityDestroyed: " + activity.getLocalClassName());
  28. }
  29. });

Check the log printout as follows:

  1. onActivityPaused: MainActivity
  2.  
  3. onActivityStopped: MainActivity
  4.  
  5. onActivityStarted: MainActivity
  6.  
  7. onActivityResumed: MainActivity

6. registerComponentCallbacks() and unregisterComponentCallbacks() methods

Register and unregister ComponentCallbacks2 callback interface

  1. registerComponentCallbacks(new ComponentCallbacks2() {
  2. @Override
  3. public void onTrimMemory( int   level ) {
  4. }
  5. @Override
  6. public void onConfigurationChanged(Configuration newConfig) {
  7. }
  8. @Override
  9. public void onLowMemory() {
  10. }
  11. });

3. Application Scenarios and Customization

1. Application scenarios

  1. Initialize application-level resources, such as global objects;
  2. Data sharing and data caching;
  3. Get the current memory usage of the application and release resources in time to avoid being killed by the system;
  4. Monitor changes in application configuration information, such as screen rotation;
  5. Monitor the life cycle of all Activities in the application;

2. Customize Application

(1) Inherit Application

  1. public class MyApplication extends Application{
  2. /**Declare variables*/
  3. private String value;
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. // Initialize global variables
  8. setValue(VALUE);
  9. }
  10. public void setValue(String value){
  11. this.value = value;
  12. }
  13. public String getValue(){
  14. return value;
  15. }
  16. }

Note: Inherit the Application class and mainly rewrite the onCreate() method (the onCreate() method of the android.app.Application package is the real entry point of the Android program), which is to initialize the value of the variable when creating it. Then you can operate on the variable in each file in the entire application;

(2) Configure a custom Application in the ApplicationManifest.xml file

  1. <application
  2. android: name = "MyApplication" >
  3. </application>

(3) Using a custom Application class instance

  1. private MyApplication app;
  2. // Just call Activity.getApplication() or Context.getApplicationContext() to get an Application object
  3. app = (MyApplication) getApplication();
  4. //Then get the corresponding member variables or methods
  5. app.getValue();

Summarize

When each Android App is running, it will first automatically create an Application class and instantiate an Application object, and there is only one Application class, which is a singleton class;

That is, different components (such as Activity, Service) can obtain the Application object and they are all the same object;

The life cycle of the Application object is the longest in the entire program, which is equal to the life cycle of the Android App.

<<:  Mobile Internet speed rankings released, check if your phone is included

>>:  iOS15.1.1 official version: It turns out that the poor signal is not our fault

Recommend

The most comprehensive core strategy for user operations!

"Operation is to keep users," this stat...

The most powerful copywriting for 520 Confession Day in history is here! !

520 is other people’s Valentine’s Day , but it is...

Mixue Ice City: The wealth code from "0" to "1"

Out of curiosity, I looked up the development his...

360's new phone will adopt a borderless design, OPPO may be the first to ship

According to information on the website of the St...

36 Sales Strategies, Sales Skills That Never Go Out of Style

Mr. Bao once worked for a Fortune 500 company, st...

Kuaishou Information Stream Ads oCPC Smart Delivery Guide

In the process of investing in Kuaishou informati...

Useful Tips | 230 essential jargon words for marketers!

We hate slang, but we can't completely get ri...

Urban survival tool, WI-1000XM2 or QuietControl 30 noise reduction is better?

Noise-cancelling headphones have become a standar...

If you want to minimize your intake of nitrite, how should you eat vegetables?

You may have heard that nitrite can be used to pr...