Activity被回收后再次进入的生命周期

        Activity的基本生命周期是onCreate-onStart-onResume-onPause-onStop-onDestory。  举例Activity A->B->C->D->E, E处于栈顶即正在显示, A、B、C、D实例在后台。

       但是当系统内存不足时, dalvik会回收资源, 这时在后台的A、B、C、D就可能被ActvityManagerService回收掉。 问题来了, 当点击back键finish掉E时, D会执行哪些生命周期、如何恢复E的数据呢?    假如Activity D是某个详情页, 需要id去后台拿数据并显示到UI, 那么这个id在被回收后怎么传递呢?


        MVP请参考我的另一篇博客,这里只写一部分调用。

示例代码:

public class D extend Activity implement ICallBack {

               private int mId;

                private DPresenter mPresenter;


               @override

               public void onCreate(Bundle savedInstanceState) {

                      super.onCreate(savedInstanceState);

                     

                      mId = getIntent().getIntExtra("Id", 0);     //id是从intent传进来的

                      //从savedInstanceState取数据, 新Activity为空,如果被系统回收过再次打开则不空

                       if (savedInstanceState != null) {

                             mId = savedInstanceState.getInt("Id", 0);    //因为在onSaveInstanceState函数里保存过

                       }

                     

                        //调用Presenter接口从后台拉数据

                       mPresenter.getDetailById(mId);

                }


               //presenter回调的ICallBack接口, 刷新Activity的控件               

               public void showDetail(Object obj) {

                }

                .....

              @override

              protected void onSaveInstanceState(Bundle outState) {

                      super.onSaveInstanceState(outState);


                       //在这里缓存你要保存的值,  不包含ui里的textview、edittext等等, 因为android会自动保存并在再次打开activity时仍然显示原来的值

                      outState.putInt("Id", mId);   

              }


      第一、     Activity被系统回收时都会执行onSaveInstanceState(Bundle outState)函数, 所以我们要重写该函数并缓存到bundle里。

       

     第二、 再次打开Activity D会执行的生命周期为 onCreate->onStart->onRestoreInstanceState->onPostCreate-onResume. 我们看google对onRestoreInstanceState函数的注释, 一般情况下在onCreate做逻辑就可以了, 就像上面的示例代码一样。


This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here insavedInstanceState. Most implementations will simply use onCreate(android.os.Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(android.os.Bundle).


详见源码介绍: http://www.grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Activity.java#Activity.onRestoreInstanceState%28android.os.Bundle%2Candroid.os.PersistableBundle%29


   

你可能感兴趣的:(Android)