Lifecycle源码阅读

1、Lifecycle时序图

Lifecycle时序图.png

2、首先看看添加观察者(addObserver)

class TestActivity : AppCompatActivity() {

    val testLifecycleObserver = TestLifecycleObserver()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        lifecycle.addObserver(testLifecycleObserver)
    }
}

1、lifecycle的创建

在AppCompatActivity父类ComponentActivity中创建了LifecycleRegistry

  private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

   public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

2、addaddObserver

把观察者和初始状态包装成了ObserverWithState,在ObserverWithState的构造方法中获取了LifecycleEventObserver mLifecycleObserver,用来分发状态

 LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

在Lifecycling.lifecycleEventObserver(observer)中判断观察者的类型,如果不是FullLifecycleObserver和LifecycleEventObserver主要是通过反射回调状态更新的方法

2、状态改变的回调

ComponentActivity的oncreate方法中调用了 ReportFragment.injectIfNeededIn(this);

  public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            LifecycleCallbacks.registerIn(activity);
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

在sdk大于29是使用了LifecycleCallbacks的生命周期回调方法来分发状态的改变,小于29时把这个空的fragment添加到了activity中利用fragment的生命周期方法回调。都会调用到dispatch()的方法。

    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

最终调用了LifecycleRegistry的sync()

    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

Lifecycle有两个重要的枚举

  public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,    
        ON_STOP,
        ON_DESTROY,
        ON_ANY;
}

public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
    }
lifecycle-states.jpg

上图描述的时sync中的两个调用方法 backwardPass(lifecycleOwner)、forwardPass(lifecycleOwner)当当前的States状态大于mObserverMap中最近添加观察者的方法状态mObserverMap中所有的观察者状态前移保持当前states的状态一致反之后移。并且调用ObserverWithState的dispatchEvent()方法。

  void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

其中mLifecycleObserver就是在添加观察者过程中创建的LifecycleEventObserver实现列。根据不同继承调用反射方法或者直接分发。

其中一些细节并不详细

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容