美文网首页
Jetpack之LifeCycle(一)

Jetpack之LifeCycle(一)

作者: 风骚无俩 | 来源:发表于2019-06-10 08:50 被阅读0次

随着android版本的不断演进和LifeCycle等组件的融合,具有生命周期感应的组件应用越来越广泛,LifeCycle作为基础,了解一下源码有助于我们更好的发挥这些组件的便利,同时以往各种support库已经迁移到AndroidX库名下,这里我们使用Android P版本配合AndroidX库来梳理一下流程。

项目创建

我们创建一个新项目,如果build.gradle文件中使用的还是support库,使用如下方式迁移到AndroidX


image.png

在你的gradle.properties文件中会多两行配置

android.useAndroidX=true
android.enableJetifier=true

build.gradle文件中的依赖将都以androidx开头

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0-beta01'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0-beta01'
}

onCreate

使用自动生成的MainActivity作为启动页面。当我们启动MainActivity时,AMS通过Binder来通知的我们的应用,而ActivityThread类是应用进程的入口,也是运行主线程的地方,它就会收到下面这个方法。

 /**
     * Extended implementation of activity launch. Used when server requests a launch or relaunch.
        Activity启动的实现,在AMS要求启动或重启Activity时使用
     */
ActivityThread.java
 public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
       ...
      
        final Activity a = performLaunchActivity(r, customIntent);
       ...
        return a;
    }

真正的实现在performLaunchActivity

ActivityThread.java
/**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
       ...
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            //实列化Activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ...
        } catch (Exception e) {
           ...
        }
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation); 
            if (activity != null) {
               ...
              //activity 进行初始化
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
                ...
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    //开始调用我们的OnCreate回调
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
               ...
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
          ..
        }
        return activity;
    }
Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

最终调用到Actvity的performCreate

Actvity.java
 final void performCreate(Bundle icicle) {
      //调用下面的两个参数的方法
        performCreate(icicle, null);
    }

 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
       ...
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
          //这里就调用到Actvity子类,我们MainActivity的onCreate方法
            onCreate(icicle);
        }
      ...
      //先忽略
        mFragments.dispatchActivityCreated();
    }

如果在MainActivity的onCreate方法打断点,就有如下图的调用链


image.png

我们继续看其父类有哪些操作

AppCompatActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) {
       ...
        super.onCreate(savedInstanceState);
    }

FragmentActivity.java
 protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.mFragments.attachHost((Fragment)null);
        super.onCreate(savedInstanceState);
       ...
        //先忽略
        this.mFragments.dispatchCreate();
    }
ComponentActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) {
      //继续调用父类
        super.onCreate(savedInstanceState);
        //看完父类的onCreate方法再看
        ReportFragment.injectIfNeededIn(this);
    }
Activity.java
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

 protected void onCreate(@Nullable Bundle savedInstanceState) {
       ...
      //向Fragment分发create事件
        mFragments.dispatchCreate();
      //目前没有哪个类向Application注册了监听,除非我们添加了lifecycle:extensions依赖,这个方法可以忽略
        getApplication().dispatchActivityCreated(this, savedInstanceState);
       ...
    }

注意: Activity里面的FragmentController和FragmentActivity里面的是不一样的

android.app.FragmentController.java
/**
     * Moves all Fragments managed by the controller's FragmentManager
     * into the create state.把FragmentManager管理的所有Fragment都移到create状态
     * <p>Call when Fragments should be created.
     */
    public void dispatchCreate() {
      //这个方法由FragmentManagerImpl实现
        mHost.mFragmentManager.dispatchCreate();
    }
android.app.FragmentManagerImpl.java
 public void dispatchCreate() {
        mStateSaved = false;
      //Fragment.CREATED=1
        dispatchMoveToState(Fragment.CREATED);
    }

private void dispatchMoveToState(int state) {
        if (mAllowOldReentrantBehavior) {
          //android o之前版本
            moveToState(state, false);
        } else {
            try {
                mExecutingActions = true;
                moveToState(state, false);
            } finally {
                mExecutingActions = false;
            }
        }
        execPendingActions();
    }

void moveToState(int newState, boolean always) {
        ...
        //FragmentManagerImpl记录了当前Activity的状态为Fragment.CREATED
        mCurState = newState;
      //此时没有fragment,mActive为null
        if (mActive != null) {
          ...
      }
    }

流程如下图


image.png

到此Activity的onCreate方法算是执行完毕,接着看ComponentActivity的

ComponentActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //ReportFragment是内部使用用来分发初始化事件的,无UI,继承自android framework的 fragment
        ReportFragment.injectIfNeededIn(this);
    }
ReportFragment.java
 public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        //使用android framework的fragment是为了兼容性好,主要作为是报告生命周期,没啥功能
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
          //这句话的主要作用是记录一个添加Fragment的动作,但不会立马执行
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // 立马执行刚才的添加动作
            manager.executePendingTransactions();
        }
    }

FragmentManager执行executePendingTransactions的过程相当复杂,最后的目的就是调用moveToState来同步Fragment的状态,我们挑出对应代码简化分析

android.app.FragmentManagerImpl.java
    //f 就是ReportFragment,默认初始化状态,newState就是我们前面保存的Fragment.CREATED
 void moveToState(Fragment f, int newState, int transit, int transitionStyle,boolean keepActive) {
     switch (f.mState) 
            case Fragment.INITIALIZING:
                  if (newState > Fragment.INITIALIZING) {                      
                       ...
                        //调用了onAttach回调
                        f.onAttach(mHost.getContext());
                       ...
                        if (f.mParentFragment == null) {
                            //通知宿主Fragment已attach
                            mHost.onAttachFragment(f);
                        } else {
                            f.mParentFragment.onAttachFragment(f);
                        }
                        dispatchOnFragmentAttached(f, mHost.getContext(), false);

                        if (!f.mIsCreated) {
                            dispatchOnFragmentPreCreated(f, f.mSavedFragmentState, false);
                            //会调用相关fragment的onCreate方法
                            f.performCreate(f.mSavedFragmentState);
                            dispatchOnFragmentCreated(f, f.mSavedFragmentState, false);
                        } else {
                           ...
                        }
                        f.mRetaining = false;
                    }
             case Fragment.CREATED:
                  //因为ReportFragment无UI,所以onCreateView方法不会调用
                    ensureInflatedFragmentView(f);
    ...
}

到此,ReportFragment加入了FragmentManager并且onAttach、onCreate回调被调用,状态同步到Fragment.CREATED。ComponentActivity的onCreate方法执行结束


image.png

再看FragmentActivity的onCreate方法

FragmentActivity.java
final FragmentController mFragments = FragmentController.createController(new FragmentActivity.HostCallbacks());

protected void onCreate(@Nullable Bundle savedInstanceState) {
       this.mFragments.attachHost((Fragment)null);
       //结束
       super.onCreate(savedInstanceState);
      ...
       //和activity里面的很相似,不过这是androidx包下的,此时没有androidx包下的fragment要同步
       this.mFragments.dispatchCreate();
   }
androidx.fragment.app.FragmentController.java
    public void dispatchCreate() {
      //这个方法由FragmentManagerImpl实现
        mHost.mFragmentManager.dispatchCreate();
    }
androidx.fragment.app.FragmentManagerImpl
 public void dispatchCreate() {
       this.mStateSaved = false;
       this.mStopped = false;
       this.dispatchStateChange(Fragment.CREATED);
   }
private void dispatchStateChange(int nextState) {
       try {
           this.mExecutingActions = true;
           this.moveToState(nextState, false);
       } finally {
           this.mExecutingActions = false;
       }
       this.execPendingActions();
   }

void moveToState(int newState, boolean always) {
       if (this.mHost == null && newState != 0) {
           throw new IllegalStateException("No activity");
       } else if (always || newState != this.mCurState) {
           this.mCurState = newState;
         //mActive 为null
           if (this.mActive != null) {
               ...
           }
       }
   }

FragmentActivity的onCreate结束后,AppCompatActivity的没啥相关的也结束,就到MainActivity的onCreate方法,完成setContentView后也结束,这样onCreate方法就全部结束了


Activivty_onCreate.png

回到performCreate继续往下执行dispatchActivityCreated

Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
       ...
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
          //结束
            onCreate(icicle);
        }
      ...
      //同步到ActivityCreated状态
        mFragments.dispatchActivityCreated();
    }

流程同上,只是这次要同步的状态是Fragment.ACTIVITY_CREATED

android.app.FragmentManagerImpl.java
//从Fragment.CREATED到Fragment.ACTIVITY_CREATED
  void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) {
      switch (f.mState)
        case Fragment.CREATED:
                    ensureInflatedFragmentView(f);
                    if (newState > Fragment.CREATED) {
                        if (DEBUG) Log.v(TAG, "moveto ACTIVITY_CREATED: " + f);
                        ...
                            f.mContainer = container;
                            f.mView = f.performCreateView(f.performGetLayoutInflater(
                                    f.mSavedFragmentState), container, f.mSavedFragmentState);
                           ...
                        }
                        //会调用ReportFragment的onActivityCreated方法
                        f.performActivityCreated(f.mSavedFragmentState);
                        dispatchOnFragmentActivityCreated(f, f.mSavedFragmentState, false);
                        if (f.mView != null) {
                            f.restoreViewState(f.mSavedFragmentState);
                        }
                        f.mSavedFragmentState = null;
                    }

}

到此才发挥了ReportFragment的真正作用,向LifecycleRegistry汇报Activity的生命周期

ReportFragment.java
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //mProcessListener为null,忽略
        dispatchCreate(mProcessListener);
        //调用下面方法分发事件
        dispatch(Lifecycle.Event.ON_CREATE);
    }

private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
        //ComponentActivity实现了LifecycleOwner接口,所以走这里
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                //目前没有注册监听,先忽略
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

至此,在ActivityThread里调用的performLaunchActivity就结束了,整个Activity就启动了.流程如下


Activivty_onCreate_dispatch.png

为了使过程简单,我们没有添加自定义的Fragment和其他任何代码,尽管如此,仅仅分析了一个OnCreate的调用的已涉及计了大量的逻辑,好消息是剩下的回调大同小异。

onStart

过程类似,不再分析代码,大家可以使用断点调式一步一步查看详细执行结果,流程如下:


Activivty_onStart.png

onResume

Activivty__onResume.png

在上述过程中,ReportFragment对事件的分发都发生在回调之后,即系统先调完onCreate再通知ReportFragment去分发,同理onStart和onResume。这样我们监听到对应事件可以确保系统已完成初始化。

onPause

流程图如下:


Activivty_onPause.png

需要注意一个细节,onPause事件的分发比我们Activity onPause回调的调用要早

Activity.java
final void performPause() {
        //此事件分发在调用onPause方法之前
        mFragments.dispatchPause();
        mCalled = false;
        onPause();
       ...
    }

onStop

过程和onPause类似,流程图如下


Activivty_onStop.png

在onStop过程中会确认onPause是否调用

ActivityThread.java
 private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
            boolean saveState, boolean finalStateRequest, String reason) {
        if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
        if (r != null) {
            if (!keepShown && r.stopped) {
               ...
            // One must first be paused before stopped...确认先pause
            performPauseActivityIfNeeded(r, reason);
            if (info != null) {
               ..
            if (!keepShown) {
                callActivityOnStop(r, saveState, reason);
            }
        }
    }

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
        if (r.paused) {
            // You are already paused silly...如果已经停了就返回
            return;
        }
        try {
            r.activity.mCalled = false;
            mInstrumentation.callActivityOnPause(r.activity);
           ...
        r.setState(ON_PAUSE);
    }

onDestroy

和onStop一样,先确认前面的生命周期走完

ActivityThread.java
ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance, String reason) {
       ...
            //如有需要 先暂停
            performPauseActivityIfNeeded(r, "destroy");
            //如果没stop 先stop
            if (!r.stopped) {
                callActivityOnStop(r, false /* saveState */, "destroy");
            }
            ...
            try {
                r.activity.mCalled = false;
                mInstrumentation.callActivityOnDestroy(r.activity);
               ...
        }
        mActivities.remove(token);
        StrictMode.decrementExpectedActivityCount(activityClass);
        return r;
    }
Activity.java
final void performDestroy() {
        mDestroyed = true;
        mWindow.destroy();
      //先分发
        mFragments.dispatchDestroy();
        onDestroy();
       ...
    }

再看一下moveToState,此时newState =INITIALIZING=0

                case Fragment.STOPPED:
                case Fragment.ACTIVITY_CREATED:
                    if (newState < Fragment.ACTIVITY_CREATED) {                
                      ...
                        //调用到ReportFragment的onDestroyView
                        f.performDestroyView();
                        ...
                        f.mContainer = null;
                        f.mView = null;
                        f.mInLayout = false;
                    }
                    // fall through
                case Fragment.CREATED:
                    if (newState < Fragment.CREATED) {
                        if (f.getAnimatingAway() != null) {
                           ...
                            newState = Fragment.CREATED;
                        } else {
                            if (!f.mRetaining) {
                              //调用ReportFragment的onDestroy
                                f.performDestroy();                                
                            } else {
                                f.mState = Fragment.INITIALIZING;
                            }
                       //调用ReportFragment的onDetach
                            f.performDetach();
                            ...
                        }
                    }
Activivty_onDestroy.png
和前面onCreate、onPause、onResume相反,在onPause、onStop、onDestroy事件中,系统先通知Reportment分发事件,再调用相应的回调,这样在监听生命周期时可以保证我们释放资源时,系统资源仍然可用。虽然扯了一大坨,以上的流程还只是整个流程的中间一部分,如果想了解在这之前发生了什么,不妨看看下一篇

相关文章

网友评论

      本文标题:Jetpack之LifeCycle(一)

      本文链接:https://www.haomeiwen.com/subject/rptyzqtx.html