从源码角度看Activity知识点(一)

来源:互联网 发布:xp升级 软件 编辑:程序博客网 时间:2024/06/05 12:39

Activity各生命周期阶段的方法具体做了啥?

首先说下正常情况下Activity的生命周期:
onCreate——onStart——onResume——onPause——onStop——onDestroy。
这是最简单的生命流程,从创建到获取焦点显示在界面上到失去焦点不显示最后销毁。

onCreate

在此方法内,仅仅做个打印信息功能,是最简单的方法调用~

 @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Log.d(TAG, "onCreate");    }

Read the fucking source code,还是老样子,看源码先看类注释和方法注释哦~(由于篇幅,此处仅贴方法注释了)

    /**     * Called when the activity is starting.  This is where most initialization     * should go: calling {@link #setContentView(int)} to inflate the     * activity's UI, using {@link #findViewById} to programmatically interact     * with widgets in the UI, calling     * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve     * cursors for data being displayed, etc.     *     * <p>You can call {@link #finish} from within this function, in     * which case onDestroy() will be immediately called without any of the rest     * of the activity lifecycle ({@link #onStart}, {@link #onResume},     * {@link #onPause}, etc) executing.     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @param savedInstanceState If the activity is being re-initialized after     *     previously being shut down then this Bundle contains the data it most     *     recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>     *     * @see #onStart     * @see #onSaveInstanceState     * @see #onRestoreInstanceState     * @see #onPostCreate     */

第一段说明方法的作用,表明该方法是在activity启动的时候被调用。接着举例说明了很多需要初始化的工作在这里处理,如在setContentView方法里将xml布局文件转成View,调用findViewById方法从该布局中获取正确的视图组件。通过managedQuery方法获取用于显示的数组索引。

第二段说你可以在此方法内调用finish,这种情况该activity生命周期会不执行其他阶段而立刻结束。

第三段说父类方法须通过super方法执行,否则会出现异常。

第四段说之前被创建的activity在被仓促销毁后又重建,可以通过savedInstanceState方法内的bundle存储的数据得以恢复。

个人分述:onCreate方法就是activity生命周期开始阶段,在此阶段负责与界面绘制相关的资源的初始化。并提供在activity异常关闭后的恢复工作的支持。

onStart

  @Override    protected void onStart() {        super.onStart();        Log.d(TAG, "onStart");    }

Read the fucking source code~

     /**     * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when     * the activity had been stopped, but is now again being displayed to the     * user.  It will be followed by {@link #onResume}.     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @see #onCreate     * @see #onStop     * @see #onResume     */

第一段说onStart是在onCreate执行之后执行,或者是在activity停止后又重新显示在界面上时调用onRestart之后执行的,并且紧接着会执行onResume方法。

第二段作用已说明过,此处省略。

onResume

  @Override    protected void onResume() {        super.onResume();        Log.d(TAG, "onResume");    }

Read the fucking source code~

    /**     * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or     * {@link #onPause}, for your activity to start interacting with the user.     * This is a good place to begin animations, open exclusive-access devices     * (such as the camera), etc.     *     * <p>Keep in mind that onResume is not the best indicator that your activity     * is visible to the user; a system window such as the keyguard may be in     * front.  Use {@link #onWindowFocusChanged} to know for certain that your     * activity is visible to the user (for example, to resume a game).     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @see #onRestoreInstanceState     * @see #onRestart     * @see #onPostResume     * @see #onPause     */

第一段说此方法根据当前activity与用户交互过程中会在onRestoreInstanceState或者onRestart或者onPause之后调用。这个阶段适合开启动画或者打开相机等工作。

第二段说要注意此阶段并不是代表当前activity用户可见的,因为可能有一个系统窗口如键盘正显示在当前。可以通过onWindowFocusChanged方法确保当前activity用户可见。

onPause

@Override    protected void onPause() {        super.onPause();        Log.d(TAG, "onPause");    }

Read the fucking source code~

    /**     * Called as part of the activity lifecycle when an activity is going into     * the background, but has not (yet) been killed.  The counterpart to     * {@link #onResume}.     *     * <p>When activity B is launched in front of activity A, this callback will     * be invoked on A.  B will not be created until A's {@link #onPause} returns,     * so be sure to not do anything lengthy here.     *     * <p>This callback is mostly used for saving any persistent state the     * activity is editing, to present a "edit in place" model to the user and     * making sure nothing is lost if there are not enough resources to start     * the new activity without first killing this one.  This is also a good     * place to do things like stop animations and other things that consume a     * noticeable amount of CPU in order to make the switch to the next activity     * as fast as possible, or to close resources that are exclusive access     * such as the camera.     *     * <p>In situations where the system needs more memory it may kill paused     * processes to reclaim resources.  Because of this, you should be sure     * that all of your state is saved by the time you return from     * this function.  In general {@link #onSaveInstanceState} is used to save     * per-instance state in the activity and this method is used to store     * global persistent data (in content providers, files, etc.)     *     * <p>After receiving this call you will usually receive a following call     * to {@link #onStop} (after the next activity has been resumed and     * displayed), however in some cases there will be a direct call back to     * {@link #onResume} without going through the stopped state.     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @see #onResume     * @see #onSaveInstanceState     * @see #onStop     */

第一段说当activity将要进入后台时调用此方法,但此时并未被销毁,相反的阶段是onResume。

第二段说当一个activityB被启动后位于activityA栈顶时,A中的onPause方法将会被调用,而B直到A的onPause方法return时才会执行创建。所以确保在onPause中不要做耗时操作哦~(开始记笔记啦,考点

第三段说在onPause方法中大多用来保存与当前activity界面配置相关的持续状态。确保在没足够资源启动新activity而已销毁当前activity时,当前activity的数据不丢失。此阶段也适合停止动画或者关闭那些显著消耗CPU的处理如相机,以便快速启动新的activity。

第四段说在系统需要更多的内存的情况下,系统会杀死暂停的进程以回收资源,因此你需要确保在此阶段保存好所有状态。一般来说,onSaveInstanceState方法是用来存储当前activity的状态的数据,而onPause是用来持久化全局的状态,如文件,contentproviders等。

第五段说在此方法回调后,接下来通常会执行activityA的onStop方法(是在activityB执行onResume并且显示在界面上后执行)。有时候也会直接回到activityA的onResume状态而不执行onStop。

onStop

 @Override    protected void onStop() {        super.onStop();        Log.d(TAG, "onStop");    }

Read the fucking source code~

    /**     * Called when you are no longer visible to the user.  You will next     * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,     * depending on later user activity.     *     * <p>Note that this method may never be called, in low memory situations     * where the system does not have enough memory to keep your activity's     * process running after its {@link #onPause} method is called.     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @see #onRestart     * @see #onResume     * @see #onSaveInstanceState     * @see #onDestroy     */

第一段说该方法是在用户不可见的时候被调用,接下来可能会执行onRestart,或者onDestroy,抑或啥也没有~

第二段说注意此方法也许永远不会执行的,当虚拟机内存不够维持你的当前activity运行时就会在onPause被调用后就会被销毁了。so,onPause是activity被系统因内存不够销毁前能做的最后一步挽救阶段了。

onDestroy

 @Override    protected void onDestroy() {        super.onDestroy();        Log.d(TAG, "onDestroy");    }

Read the fucking source code~

    /**     * Perform any final cleanup before an activity is destroyed.  This can     * happen either because the activity is finishing (someone called     * {@link #finish} on it, or because the system is temporarily destroying     * this instance of the activity to save space.  You can distinguish     * between these two scenarios with the {@link #isFinishing} method.     *     * <p><em>Note: do not count on this method being called as a place for     * saving data! For example, if an activity is editing data in a content     * provider, those edits should be committed in either {@link #onPause} or     * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to     * free resources like threads that are associated with an activity, so     * that a destroyed activity does not leave such things around while the     * rest of its application is still running.  There are situations where     * the system will simply kill the activity's hosting process without     * calling this method (or any others) in it, so it should not be used to     * do things that are intended to remain around after the process goes     * away.     *     * <p><em>Derived classes must call through to the super class's     * implementation of this method.  If they do not, an exception will be     * thrown.</em></p>     *     * @see #onPause     * @see #onStop     * @see #finish     * @see #isFinishing     */

第一段说此阶段是在一个activity被销毁前做最终的清理工作。一个activity被销毁可以是主动被关闭,也可以是因为系统临时销毁以节省空间。是否销毁可以通过调用isFinishing判断。

第二段说别指望此靠阶段的执行来保存数据。例如一个activity在contentprovider编辑数据时是要在onPause或onSaveInstanceState进行保存数据,而不是onDestroy阶段。这个阶段大多是用来释放与activity相关的资源如线程等,这是为了避免一个已销毁的activity的相关任务还在执行。有些情况是系统销毁此activity时不一定会调用onDestroy方法。所以不应该做那些在主进程被销毁了还准备持有引用的工作,避免内存泄漏。(不懂就直译啦)

个人分述:针对此情况的规范做法是在 onPause() 方法里面判断 isFinishing() ,正常调用 finish() 后 activity 的回调过程是 onPause、onStop、onDestroy ,倘若出现上面的情况,只到 onPause!但是 isFinishing() 标志还是为 true !你可以释放资源了。

以上是对activity内各个生命周期阶段的方法源码注释进行翻译,简单了解了各个阶段到底做了啥。接下来会实例验证各个阶段的作用,并且会进一步分析各个阶段方法的实现过程。

0 0
原创粉丝点击