Android 源码分析Application的生命周期及共享数据详解

推荐阅读:

Android 深刻理解Activity生命周期的作用及意义

一、概述

Application源码介绍,如下所示:

/**
 * Base class for maintaining global application state. You can provide your own
 * implementation by creating a subclass and specifying the fully-qualified name
 * of this subclass as the <code>"android:name"</code> attribute in your
 * AndroidManifest.xml's <code><application></code> tag. The Application
 * class, or your subclass of the Application class, is instantiated before any
 * other class when the process for your application/package is created.
 *
 * <p class="note"><strong>Note: </strong>There is normally no need to subclass
 * Application.  In most situations, static singletons can provide the same
 * functionality in a more modular way.  If your singleton needs a global
 * context (for example to register broadcast receivers), include
 * {@link android.content.Context#getApplicationContext() Context.getApplicationContext()}
 * as a {@link android.content.Context} argument when invoking your singleton's
 * <code>getInstance()</code> method.
 * </p>
 */

概述:      Application类是为了那些需要保存全局变量设计的基本类,你可以在AndroidManifest.xml的<application>标签中通过”android:name”属性进行使用,自定义的application作为基类会影响该程序中每个类的建立,只需要调用Context的getApplicationContext或者Activity的getApplication方法来获得一个application对象,就能做出相应的处理。

二、程序生命周期

1、onCreate():程序创建

/**
 * Called when the application is starting, before any activity, service,
 * or receiver objects (excluding content providers) have been created.
 * Implementations should be as quick as possible (for example using
 * lazy initialization of state) since the time spent in this function
 * directly impacts the performance of starting the first activity,
 * service, or receiver in a process.
 * If you override this method, be sure to call super.onCreate().
 */
@CallSuper
public void onCreate() {
}

介绍:这个函数是当应用开始之时就被调用了,比其他对象创建的早,这个实现要尽可能的快一点,因为创建时间直接在进程中影响到我们第一个activity/service或者receiver。如果你要重写这个方法必须调用super.onCreate()。

2、onTerminate():程序终止

/**
 * This method is for use in emulated process environments.  It will
 * never be called on a production Android device, where processes are
 * removed by simply killing them; no user code (including this callback)
 * is executed when doing so.
 */
@CallSuper
public void onTerminate() {
}

介绍:应用程序对象终止时调用。但不保证一定被调用,当程序是被内核终止以便为其他应用程序释放资源,那 么将不会提醒,即不调用应用程序的对象的onTerminate方法而直接终止当前进程。

3、onLowMemory():程序低内存

/**
 * This is called when the overall system is running low on memory, and
 * actively running processes should trim their memory usage.  While
 * the exact point at which this will be called is not defined, generally
 * it will happen when all background process have been killed.
 * That is, before reaching the point of killing processes hosting
 * service and foreground UI that we would like to avoid killing.
 */
void onLowMemory();

介绍:当后台程序已经终止资源还匮乏时会调用这个方法。好的应用程序一般会在这个方法里面释放一些不必 要的资源来应付当后台程序已经终止,前台应用程序内存还不够时的情况。

4、onTrimMemory():程序内存清理

/**
 * Called when the operating system has determined that it is a good
 * time for a process to trim unneeded memory from its process.  This will
 * happen for example when it goes in the background and there is not enough
 * memory to keep as many background processes running as desired.  You
 * should never compare to exact values of the level, since new intermediate
 * values may be added -- you will typically want to compare if the value
 * is greater or equal to a level you are interested in.
 */
void onTrimMemory(@TrimMemoryLevel int level);

介绍:当系统回调确认该进程是时候回收不必要的内存了,这将例如发生在后台时,没有足够的内存保持尽可能多的后台进程运行一样。一般发生在点击Home键、Task任务菜单键时被执行。

三、实例演示


*记得把自定义的MyApplication类在AndroidManifest.xml中Application标签中设置到Android:name属性中。

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        // 程序创建的时候执行
        Log.d(TAG, "onCreate");
        super.onCreate();
    }
    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        Log.d(TAG, "onTerminate");
        super.onTerminate();
    }
    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        Log.d(TAG, "onLowMemory");
        super.onLowMemory();
    }
    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        Log.d(TAG, "onTrimMemory");
        super.onTrimMemory(level);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }
}

//打开oneActivity  
01-19 15:16:27.142: D/CARLOZ - Application(28202):   onCreate   //创建  
01-19 15:16:27.172: D/CARLOZ - oneActivity(28202):   onCreate  
01-19 15:16:27.232: D/CARLOZ - oneActivity3(28202):  onStart  
01-19 15:16:27.232: D/CARLOZ - oneActivity3(28202):  onResume  
//跳转twoActivity  
01-19 15:16:27.272: D/CARLOZ -  oneActivity(28202):  onPause  
01-19 15:16:27.272: D/CARLOZ -  twoActivity(28202):  onCreate  
01-19 15:16:27.322: D/CARLOZ - twoActivity3(28202): onStart  
01-19 15:16:27.342: D/CARLOZ - twoActivity3(28202): onResume  
01-19 15:16:27.352: D/CARLOZ - oneActivity3(28202):  onStop  
01-19 15:16:27.362: D/CARLOZ - oneActivity3(28202):  onDestory  
//返回oneActivity  
01-19 15:16:27.272: D/CARLOZ -  twoActivity(28202):  onPause  
01-19 15:16:27.272: D/CARLOZ -  oneActivity(28202):  onRestart  
01-19 15:16:27.322: D/CARLOZ -  oneActivity3(28202): onStart  
01-19 15:16:27.342: D/CARLOZ -  oneActivity3(28202): onResume  
01-19 15:16:27.352: D/CARLOZ - twoActivity3(28202):  onStop  
01-19 15:16:27.362: D/CARLOZ - twoActivity3(28202):  onDestory  
//按HOME键退出应用程序  
01-19 15:16:55.372: D/CARLOZ - oneActivity(28202):  onPause  
01-19 15:16:55.942: D/CARLOZ - oneActivity(28202):  onStop  
01-19 15:16:55.952: D/CARLOZ - Application(28202):  onTrimMemory  //回收内存  
//重新打开oneActivity  
01-19 15:17:20.962: D/CARLOZ - oneActivity(28202): onRestart  
01-19 15:17:20.962: D/CARLOZ - oneActivity(28202): onStart  
01-19 15:17:20.962: D/CARLOZ - oneActivity(28202): onResume  
//按MENU键启动Recent TASK最近任务  
01-19 15:17:28.972: D/CARLOZ - oneActivity(28202): onPause  
01-19 15:17:28.992: D/CARLOZ - oneActivity(28202): onStop  
01-19 15:17:29.022: D/CARLOZ - Application(28202): onTrimMemory //回收内存  
//彻底关闭应用程序  
01-19 15:17:31.542: D/CARLOZ - oneActivity(28202): onDestroy

四、共享数据

*新建一个MyApplication类继承Application。封装一个自动进行拆装箱。

public class MyApplication extends Application {
    
    private String str = "大家一起享用这个蛋糕";

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}

*然后在Activity或其他组件中,调用Activity.getApplication方法或Context.getApplicationContext来获得一个application对象。 在oneActivity中:

 textview.setText("共享数据one:" + application.getStr());
 application.setStr("oneActivity已经吃了一口");

在twoActivity中:

 textview.setText("共享数据two:" + application.getStr());

结果显示:

共享数据one:大家一起享用这个蛋糕
共享数据two:oneActivity已经吃了一口


    原文作者:Android源码分析
    原文地址: https://blog.csdn.net/csdn_aiyang/article/details/79108006
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞