preface

  • ApplicaitonClass inAndroidIt’s very common in development, but you really knowApplicaitonThe class?
  • This article will be fully analyzedApplicaitonClass, including features, method introduction, application scenarios and specific use, I hope you will like it.

directory


Definition 1.

  • Represents the application (i.eAndroid App) class, also belongs toAndroidA system component in
  • Inheritance relationship: Inherited fromContextWarpper


Characteristics of 2.

2.1 Instance Creation Mode: Singleton mode

  • eachAndroid AppAt runtime, it is created automatically firstApplicationClass and instantiateApplicationObject, and only one

That is, the Application class is a singleton class

  • It can also be inheritedApplicationKind of customApplicationClass and instance

2.2 Instance Type: Global instance

That is, different components (such as activities, services) can get the Application object and all of them are the same object

2.3 Life cycle: Equal to the life cycle of the Android App

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


3. Method introduction

So what does this Application class do? Next, I’ll show you how to use the Application class’s methods

3.1 the onCreate ()

  • Call time:ApplicationCalled when the instance is created

The entry point for Android is the Application class onCreate (), which defaults to an empty implementation

  • role
    1. Initialize application-level resources, such as global objects, environment configuration variables, image resource initialization, push service registration, and so on

Note: Do not perform time-consuming operations; otherwise, the application startup speed will be slowed down

  1. Data sharing, data caching Sets globally shared data, such as globally shared variables, methods, and so on

Note: This shared data is only valid for the life of the application. When the application is killed, this data is also wiped, so only temporary shared data can be stored

  • The specific use
Private static Final String VALUE ="Carson"; // Initialize global variable @override public voidonCreate() { super.onCreate(); VALUE = 1; }}Copy the code

3.2 registerComponentCallbacks () & unregisterComponentCallbacks ()

  • Function: Register and unregisterComponentCallbacks2Callback interface

This is essentially a copy of the methods in the Callback interface for ComponentCallbacks2 to implement more operations, as described below

  • The specific use
registerComponentCallbacks(new ComponentCallbacks2@override public void onTrimMemory(int level) {} @override public void onTrimMemory(int level)onLowMemory() {

            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {

            }
        });
Copy the code

3.3 onTrimMemory ()

  • Function: Notifies the application of current memory usage (identified by memory level)

An API that comes with Android 4.0

  • Application scenario: Release its own memory resources to different degrees according to the current memory usage to avoid being killed by the system & optimize the performance experience of application programs
  1. The system runs out of memoryLRU CacheMedium from low to high kill process; Applications that occupy large memory resources are killed first
  2. If the application occupies a small memory, it is less likely to be killed and starts quickly. (Hot start = fast start)
  3. Reclaimable resources include: a. cache, such as file cache, image cache b. dynamically generated & added View

There are two typical application scenarios:

  • The specific use
registerComponentCallbacks(new ComponentCallbacks2() {@override public void onTrimMemory(int level) { Super.ontrimmemory (level); .if(level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { mPendingRequests.clear(); mBitmapHolderCache.evictAll(); mBitmapCache.evictAll(); }});Copy the code
  • Callable object & corresponding method
Application.onTrimMemory()
Activity.onTrimMemory()
Fragment.OnTrimMemory()
Service.onTrimMemory()
ContentProvider.OnTrimMemory()
Copy the code

Special attention:onTrimMemory()In theTRIM_MEMORY_UI_HIDDENwithOnStop ()The relationship between

  • onTrimMemory()In theTRIM_MEMORY_UI_HIDDENWhen all UI components in the application are not visible at all
  • ActivitytheOnStop ()Callback time: when an Activity is completely invisible
  • Usage suggestions:
    1. inOnStop ()Release andActivityRelated resources, such as canceling network connections or unregistering broadcast receivers
    2. inonTrimMemory()In theTRIM_MEMORY_UI_HIDDENRelease andUIRelated resources to ensure that usersUIRelated resources do not need to be reloaded, thus improving the response time

Note: onTrimMemory’s TRIM_MEMORY_UI_HIDDEN level is called before the onStop () method

3.4 onLowMemory ()

  • Function: MonitorAndroidThe overall system memory is low
  • Call time:AndroidThe overall system memory is low
registerComponentCallbacks(new ComponentCallbacks2() {

  @Override
            public void onLowMemory() {}});Copy the code
  • Application Scenarios:The Android 4.0Pre-detection of memory usage to avoid being killed directly by the system & optimize the application’s performance experience

Similar to OnTrimMemory ()

  • Special attention:OnTrimMemory () & OnLowMemory ()Relationship between
    1. OnTrimMemory ()isOnLowMemory () The Android 4.0After the replacementAPI
    2. OnLowMemory () = OnTrimMemory ()In theTRIM_MEMORY_COMPLETElevel
    3. If you want to compatibleThe Android 4.0Please useOnLowMemory (); Otherwise useOnTrimMemory ()Can be

3.5 onConfigurationChanged ()

  • Function: Listens for changes in application configuration information, such as screen rotation
  • Call time: called when the application configuration information changes
  • The specific use
registerComponentCallbacks(new ComponentCallbacks2() { @Override public void onConfigurationChanged(Configuration newConfig) { ... }});Copy the code
  • The configuration information refers to:Manifest.xmlUnder the fileActivityTag attributesandroid:configChanges, as follows:
<activity android:name=".MainActivity">
      android:configChanges="keyboardHidden|orientation|screenSize"</ Activity > </ Activity > </ Activity > </ Activity >Copy the code

3.6 registerActivityLifecycleCallbacks () & unregisterActivityLifecycleCallbacks ()

  • Effect: Register/deregister for all within the applicationActivityLife cycle monitor
  • Call time: when in the applicationActivityCalled when the life cycle changes

Is actually called registerActivityLifecycleCallbacks ActivityLifecycleCallbacks in () method in the interface

  • The specific use
/ / need to copy is actually ActivityLifecycleCallbacks method in the interface registerActivityLifecycleCallbacks (newActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.d(TAG,"onActivityCreated: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.d(TAG,"onActivityStarted: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                Log.d(TAG,"onActivityResumed: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.d(TAG,"onActivityPaused: " + activity.getLocalClassName());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.d(TAG, "onActivityStopped: " + activity.getLocalClassName());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.d(TAG,"onActivityDestroyed: "+ activity.getLocalClassName()); }}); OnActivityPaused: MainActivity onActivityStopped: MainActivity onActivityStarted: MainActivity onActivityResumed: MainActivityCopy the code

3.7 onTerminate ()

Call time: called when the application ends

However, this method is only used for Android emulator testing and is not called on Android production machines


4. Application scenarios

As can be seen from the method of the Applicaiton class, the application scenarios are :(sorted by priority)

  • Initializes application-level resources such as global objects, environment configuration variables, and so on
  • Data sharing, data caching, such as setting global shared variables, methods, etc
  • Gets the current memory usage of the application and frees resources in time to avoid being killed by the system
  • Listen for changes in application configuration information, such as screen rotation
  • Listen for the life cycle of all activities within the application

5. Specific use

  • If you want to duplicate the above methods, you need to customize themApplicationclass
  • The specific process is as follows

Step 1: Create an Application subclass

That is, inherit the Application class

public class CarsonApplication extends Application { ... Private static final String VALUE = onCreate() private static final String VALUE ="Carson"; // Initialize global variable @override public voidonCreate() { super.onCreate(); VALUE = 1; }}Copy the code

Step 2: Configure a custom Application subclass

The manifest.xml file is configured in the

tag

Manifest.xml

<application

        android:name=".CarsonApplication"CarsonApplication </ Application >Copy the code

Step 3: Use a custom Application class instance

private CarsonApplicaiton app; / / just call Activity. GetApplication () or Context. GetApplicationContext () you can gain an Application object app = (CarsonApplication) getApplication(); App.exitapp (); app.exitApp();Copy the code

That’s it for the Applicaiton class.


6. Summary

  • I summarize the above article with a picture

  • So I’m going to continue with thisAndroidIn the knowledge of in-depth explanation, interested can continue to pay attention toCarson_Ho android Development Notes

Thumb up, please! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat