Use of Application class

1 concept

Application, like Activity and Service, is a system component of the android framework. When the android program starts, the system creates an application object to store some information of the system. Usually we don’t need to specify an Application. At this time, the system will automatically create it for us. If we need to create our own Application, it is also very simple to create a class that inherits Application and register it in the application tag of the manifest (just need to add to the Application tag A name attribute can enter the name of your Application). Android system will create an Application class object for each program runtime and only create one, so Application can be said to be a class in singleton mode. And the life cycle of the application object is the longest in the entire program, it The life cycle is equal to the life cycle of this program. Because it is a global singleton, the objects obtained in different Activities and Services are all the same object. Therefore, some operations such as data transfer, data sharing, and data caching are carried out through Application.

2 Features

● When each Android App runs, it will first automatically create the Application class and instantiate the Application object, and there is only one.

   即 Application类 是单例模式(singleton)类

● You can also customize the Application class and instance by inheriting the Application class, which must be registered in the application tag of the manifest (you only need to add a name attribute to the Application tag to enter the name of your own Application)

3. Method

Insert picture description here

3.1 onCreate()

● Calling time: Called when the Application instance is created

Android系统的入口是Application类的 onCreate(),默认为空实现

● Function
Initialize application-level resources, such as global objects, environment configuration variables, image resource initialization, registration of push services, etc.

注:请不要执行耗时操作,否则会拖慢应用程序启动速度

3.2 onConfigurationChanged()

● Function: monitor changes in application configuration information, such as screen rotation, etc.
● Calling time: call when application configuration information changes.
Specific use:

registerComponentCallbacks(new ComponentCallbacks2() {
    
    

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
    
    
              ...
            }

        });

The configuration information refers to the value of the Activity tag attribute android:configChanges under the Manifest.xml file, as follows:

<activity android:name=".MainActivity">
      android:configChanges="keyboardHidden|orientation|screenSize"
// 设置该配置属性会使 Activity在配置改变时不重启,只执行onConfigurationChanged()
// 上述语句表明,设置该配置属性可使 Activity 在屏幕旋转时不重启
 </activity>

3.3onLowMemory()

● Function: monitor when the overall memory of the Android system is low
● Calling moment: when the overall memory of the Android system is low

registerComponentCallbacks(new ComponentCallbacks2() {
    
    

  @Override
  public void onLowMemory() {
    
    
    }
        });

Application scenario: Detect memory usage before Android 4.0 , so as to avoid being killed by the system directly & optimize the performance experience of the application

作用类似于 OnTrimMemory()

Special attention: OnTrimMemory() & OnLowMemory() relationship

OnTrimMemory()是 OnLowMemory() Android 4.0后的替代 API
OnLowMemory() = OnTrimMemory()中的TRIM_MEMORY_COMPLETE级别
若想兼容Android 4.0前,请使用OnLowMemory();否则直接使用OnTrimMemory()即可

3.4 onTrimMemory()

● Function: Notify the application of the current memory usage (identified by the memory level)

Android 4.0 后提供的一个API

Insert picture description here ● Application scenario: According to the current memory usage, release its own memory resources to different degrees to avoid being directly killed by the system & optimize the performance experience of the application

系统在内存不足时会按照LRU Cache中从低到高杀死进程;优先杀死占用内存较高的应用
若应用占用内存较小 = 被杀死几率降低,从而快速启动(即热启动 = 启动速度快)
可回收的资源包括:
a. 缓存,如文件缓存,图片缓存
b. 动态生成 & 添加的View

There are two typical application scenarios:
Insert picture description here● Specific use:

registerComponentCallbacks(new ComponentCallbacks2() {
    
    

@Override
  public void onTrimMemory(int level) {
    
    

  // Android系统会根据当前内存使用的情况,传入对应的级别
  // 下面以清除缓存为例子介绍
    super.onTrimMemory(level);
  .   if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
    
    

        mPendingRequests.clear();
        mBitmapHolderCache.evictAll();
        mBitmapCache.evictAll();
    }

        });

● Callback object & corresponding method

Application.onTrimMemory()
Activity.onTrimMemory()
Fragment.OnTrimMemory()
Service.onTrimMemory()
ContentProvider.OnTrimMemory()

Special attention: onTrimMemory () in TRIM_MEMORY_UI_HIDDEN and onStop () relationship
onTrimMemory TRIM_MEMORY_UI_HIDDEN callback time () is: When all UI components in your application all the invisible
Activity of onStop () callback time: when a Activity completely When it is visible,
use suggestion:
release resources related to Activity in onStop(), such as canceling the network connection or canceling the broadcast receiver, etc.
Release the resources related to UI in TRIM_MEMORY_UI_HIDDEN in onTrimMemory(), so as to ensure that users are using the application During the process, UI-related resources do not need to be reloaded, thereby improving response speed

注:onTrimMemory的TRIM_MEMORY_UI_HIDDEN等级是在onStop()方法之前调用的

3.5 onTerminate()

Calling time: Called when the application ends

但该方法只用于Android仿真机测试,在Android产品机是不会调用的

3.6 rregisterActivityLifecycleCallbacks() & unregisterActivityLifecycleCallbacks()

● Function: Register/Unregister to monitor the life cycle of all Activities in the application
● Calling moment: Called when the Activity life cycle in the application changes.
In fact , it calls the method in the ActivityLifecycleCallbacks interface in registerActivityLifecycleCallbacks():

Specific use:

// 实际上需要复写的是ActivityLifecycleCallbacks接口里的方法
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
    
    
            @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());
            }
        });

<-- 测试:把应用程序从前台切到后台再打开,看Activcity的变化 -->
 onActivityPaused: MainActivity
 onActivityStopped: MainActivity
 onActivityStarted: MainActivity
 onActivityResumed: MainActivity

3.7 registerComponentCallbacks() & unregisterComponentCallbacks()

● Function: Register and unregister ComponentCallbacks2 callback interface

本质上是复写 ComponentCallbacks2回调接口里的方法从而实现更多的操作,具体下面会详细介绍

Specific use:

registerComponentCallbacks(new ComponentCallbacks2() {
    
    
// 接口里方法下面会继续介绍
            @Override
            public void onTrimMemory(int level) {
    
    

            }

            @Override
            public void onLowMemory() {
    
    

            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
    
    

            }
        });

4. Application Scenario

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

初始化 应用程序级别 的资源,如全局对象、环境配置变量等
数据共享、数据缓存,如设置全局共享变量、方法等
获取应用程序当前的内存使用情况,及时释放资源,从而避免被系统杀死
监听 应用程序 配置信息的改变,如屏幕旋转等
监听应用程序内 所有Activity的生命周期

5. Specific use

1. If you need to replicate the above method, you need to customize the Application class to inherit Application
2. Add the name tag to the application in AndroidMainfest.xm

Step 1: Create a new Application subclass

public class CarsonApplication extends Application
  {
    
    
    ...
    // 根据自身需求,并结合上述介绍的方法进行方法复写实现

    // 下面以onCreate()为例
  private static final String VALUE = "Carson";
    // 初始化全局变量
    @Override
    public void onCreate()
    {
    
    
        super.onCreate();

        VALUE = 1;

    }

  }

Step 2: Configure the custom Application subclass
in AndroidMainfest.xml. Configure it in the tags in the Manifest.xml file

<application

        android:name=".CarsonApplication"
        // 此处自定义Application子类的名字 = CarsonApplication
    
</application>

Step 3: Use a custom Application class instance

private CarsonApplicaiton app;

// 只需要调用Activity.getApplication() 或Context.getApplicationContext()就可以获得一个Application对象
app = (CarsonApplication) getApplication();

// 然后再得到相应的成员变量 或方法 即可
app.exitApp();

6. Summary

Insert picture description here
Reprinted from: https://www.jianshu.com/p/f665366b2a47

Guess you like

Origin blog.csdn.net/weixin_41477306/article/details/105928766