Android: Comprehensive analysis of familiar and unfamiliar application class use

Source: Internet
Author: User

Objective
    • ApplicaitonClasses are Android very common in development, but do you really know about Applicaiton classes?
    • This article will be a comprehensive analysis of the Applicaiton class, including features, method introduction, application scenarios and specific use, I hope you will like.
Table of Contents 1. Defined
    • A class that represents an application (that is Android App ), or Android a system component in
    • Inheritance relationship: Inheriting from ContextWarpper class
2. Features 2.1 instance creation mode: Single case mode
    • Android Appat each runtime, the class is automatically created Application and Application the object is instantiated, with only one

That Application is, the class is a singleton mode ( singleton ) class

    • You can also Application customize Application classes and instances by inheriting classes
2.2 Instance form: global instance

That is, different components (such as Activity、Service ) can get Application objects and are all of the same object

2.3 Life cycle: equals Android App life cycle

ApplicationThe life cycle of an object is the longest in the entire program, that is, Android App the life cycle that is equal to

3. Method Introduction

So what does this kind of work do? Application Below, I'll introduce Application the methods of the class using the

3.1 OnCreate ()
    • Call time: Application Called when an instance is created

AndroidThe entry for the system is Application class onCreate() , and the default is an empty implementation

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

Note: Do not take a time-consuming action, or you will slow down the application startup speed

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

Note: These shared data are only valid for the lifetime of the application, and when the application is killed, the data is emptied, so only some temporary shared data can be stored

    • Specific use
// 复写方法需要在Application子类里实现private static final String VALUE = "Carson";    // 初始化全局变量    @Override    public void onCreate()    {        super.onCreate();                 VALUE = 1;    }}
3.2 registercomponentcallbacks () & Unregistercomponentcallbacks ()
    • Role: Registering and Unregistering ComponentCallbacks2 callback interfaces

In essence ComponentCallbacks2 , the method in the replication callback interface to achieve more operations, detailed below will be described in detail

    • Specific use
registerComponentCallbacks(new ComponentCallbacks2() {// 接口里方法下面会继续介绍            @Override            public void onTrimMemory(int level) {            }            @Override            public void onLowMemory() {            }            @Override            public void onConfigurationChanged(Configuration newConfig) {            }        });
3.3 Ontrimmemory ()
    • Role: Notifies the application of current memory usage (identified at memory level)

Android 4.0An API that is provided after

    • Scenario: Different levels of memory resources are freed according to current memory usage to avoid being directly killed by the system & optimize the application performance experience
  1. The system will LRU Cache kill the process from low to high in memory, and kill the high-memory-consuming application preferentially.
  2. Fast boot (i.e. hot start = fast boot speed) if the application consumes less memory = reduced chance of being killed
  3. The resources that can be recycled include:
    A. Caching, such as file caching, picture caching
    B. Dynamically generated & added view

There are two typical application scenarios:

    • 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: The onTrimMemory() TRIM_MEMORY_UI_HIDDEN onStop() relationship between

    • onTrimMemory()TRIM_MEMORY_UI_HIDDENcallback moments in: When all UI components in the application are not visible
    • ActivityonStop()callback moment: When an activity is completely invisible
    • Usage Recommendations:
      1. onStop()中releasing Activity associated resources, such as canceling a network connection or unregistering a broadcast receiver
      2. onTrimMemory() TRIM_MEMORY_UI_HIDDEN Release UI related resources in, thereby ensuring that users are using the application process, UI the related resources do not need to reload, thereby increasing the response speed

Note: onTrimMemory The TRIM_MEMORY_UI_HIDDEN rank is onStop() before the method 调用

3.4 Onlowmemory ()
    • Function: Monitor Android system overall memory low time
    • Call time: Android when the overall system memory is low
registerComponentCallbacks(new ComponentCallbacks2() {  @Override            public void onLowMemory() {            }        });
    • Scenario: Android 4.0 pre-detect memory usage to avoid being directly killed by the system & optimize application Performance Experience

Similar toOnTrimMemory()

    • Special Note: OnTrimMemory() & OnLowMemory() Relationship
      1. OnTrimMemory()Is OnLowMemory() Android 4.0 after the substitutionAPI
      2. OnLowMemory()= OnTrimMemory() level in TRIM_MEMORY_COMPLETE
      3. If you want to Android 4.0 be compatible, use it OnLowMemory() or use it directly. OnTrimMemory()
3.5 onconfigurationchanged ()
    • Role: Monitor changes in application configuration information, such as screen rotation
    • Call time: Called when application configuration information changes
    • Specific use
registerComponentCallbacks(new ComponentCallbacks2() {            @Override            public void onConfigurationChanged(Configuration newConfig) {              ...            }        });
    • This configuration information refers to the Manifest.xml Activity value of the tag attribute under the file android:configChanges , as follows:
<activity android:name=".MainActivity">      android:configChanges="keyboardHidden|orientation|screenSize"// 设置该配置属性会使 Activity在配置改变时不重启,只执行onConfigurationChanged()// 上述语句表明,设置该配置属性可使 Activity 在屏幕旋转时不重启 </activity>
3.6 Registeractivitylifecyclecallbacks () & Unregisteractivitylifecyclecallbacks ()
    • Role: Registration/Logoff for all Activity life cycle monitoring in the application
    • Call time: Called when the Activity life cycle in the application changes

is actually registerActivityLifecycleCallbacks() ActivityLifecycleCallbacks the method in the calling interface.

    • Specific use
What actually needs to be replicated is the method in the Activitylifecyclecallbacks interface 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, "Onactivitys            tarted: "+ activity.getlocalclassname ()); } @Override public void onactivityresumed (activity activity) {LOG.D (TAG, "Onactivityr            Esumed: "+ activity.getlocalclassname ()); } @Override public void onactivitypaused (activity activity) {LOG.D (TAG, "Onactivitypa            Used: "+ activity.getlocalclassname ()); } @Override public void onactivitystopped (activity activity) {LOG.D (TAG, "onactivity Stopped: "+ Activity.getlocalclassnaMe ());            } @Override public void onactivitysaveinstancestate (activity activity, Bundle outstate) { } @Override public void onactivitydestroyed (activity activity) {LOG.D (TAG, "Onactivi            Tydestroyed: "+ activity.getlocalclassname ()); }}); <--test: Cut the application from the foreground to the background and open it to see activcity changes--onactivitypaused:mainactivity onactivitystopped:mainactivity Onactivitystarted:mainactivity onactivityresumed:mainactivity
3.7 Onterminate ()

Call time: Called when the application ends

However, this method is only used for Android simulator testing, which Android is not called in the product machine.

4. Application Scenarios

As Applicaiton can be seen from the method of the class, Applicaiton the scenario of the class is: (sorted by priority)

    • Initialize 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.
    • Get your application's current memory usage and release resources in a timely manner to avoid being killed by the system
    • Monitor changes in application configuration information, such as screen rotation
    • Monitor the life cycle of all activity within an application
5. Specific Use
    • If you need to implement the above method of replication, you need to customize the Application class
    • The specific process is as follows
Step 1: Create a new application subclass

That is, inheriting Application classes

public class CarsonApplication extends Application  {    ...    // 根据自身需求,并结合上述介绍的方法进行方法复写实现    // 下面以onCreate()为例  private static final String VALUE = "Carson";    // 初始化全局变量    @Override    public void onCreate()    {        super.onCreate();        VALUE = 1;    }  }
Step 2: Configure your custom application subclass

Configure in the tags in the Manifest.xml file <application>

Manifest.xml

<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();

So far, the Applicaiton class has been explained.

6. Summary
    • I summarize the above article with a picture

Android: Comprehensive analysis of familiar and unfamiliar application class use

Related Article

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.