Lifecycle源码解析

Lifecycle-Aware是Google官方的生命周期感知组件。同时,在Google推出的Android Jetpack组件中,也将Lifecycle-Aware放在了Architecture类别之中。我们可以利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 lifecycle。同时,LiveData和ViewModel的lifecycle也依赖于Lifecycle框架,所以我们有必要去了解一下Lifecycle。

image

一、Lifecycle组件初始化

/app/build/intermediates/manifests/full/debug/AndroidManifest.xml,是我们应用在构建完成之后完整生成的AndroidManifest.xml文件。其中,我们可以找到Lifecycle-Aware组件在AndroidManifest的定义。

    

ProcessLifecycleOwnerInitializer是ContentProvider的子类,利用其onCreate()生命周期方法,处理Lifecycle组件初始化。因此,这是一种隐式初始化的方式。

    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }

二、Lifecycle生命周期事件感知

继续关注ProcessLifecycleOwnerInitializer的onCreate()方法,其调用了LifecycleDispatcher的init()方法进行相应初始化。

    static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
        private final FragmentCallback mFragmentCallback;

        DispatcherActivityCallback() {
            mFragmentCallback = new FragmentCallback();
        }

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            if (activity instanceof FragmentActivity) {
                ((FragmentActivity) activity).getSupportFragmentManager()
                        .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
            }
            ReportFragment.injectIfNeededIn(activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
            if (activity instanceof FragmentActivity) {
                markState((FragmentActivity) activity, CREATED);
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            if (activity instanceof FragmentActivity) {
                markState((FragmentActivity) activity, CREATED);
            }
        }
    }

init()方法其实就是在Application中注册了一个ActivityLifecycleCallbacks监听(即DispatcherActivityCallback),用来监听每个Activity的生命周期变化。
我们再看下DispatcherActivityCallback的onActivityCreated()回调方法,如果Activity是FragmentActivity,则注册一个FragmentLifecycleCallbacks(即FragmentCallback)用来监听Activity中Fragment的生命周期。

    static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {

        @Override
        public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
            dispatchIfLifecycleOwner(f, ON_CREATE);

            if (!(f instanceof LifecycleRegistryOwner)) {
                return;
            }

            if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
                f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
                        REPORT_FRAGMENT_TAG).commit();
            }
        }

        @Override
        public void onFragmentStarted(FragmentManager fm, Fragment f) {
            dispatchIfLifecycleOwner(f, ON_START);
        }

        @Override
        public void onFragmentResumed(FragmentManager fm, Fragment f) {
            dispatchIfLifecycleOwner(f, ON_RESUME);
        }
    }

我们看到FragmentCallback的onFragmentCreated()回调方法中,当Fragment如果实现了LifecycleRegistryOwner,就会为其添加一个DestructionReportFragment,用来监听Fragment的生命周期。
之后,会在Activity中添加一个ReportFragment,用来监听Activity生命周期。

    // ReportFragment
    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        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);
            }
        }
    }

如此,利用一个附着在Activity上无UI的Fragment,通过相应的生命周期回调方法,实质上是对Activity生命周期的监听。
至此,我们知道了Lifecycle组件通过ActivityLifecycleCallbacks、FragmentLifecycleCallbacks及 无UI的Fragment来感知Activity/Fragment的生命周期变化并产生相应的事件。

三、Lifecycle生命周期事件分发

在上面的分析中,我们只是重点关注了Lifecycle如何感知生命周期,也就是如何监听Activity/Fragment的生命周期。在相应的回调方法当中,其实都包含了很多生命周期事件分发相关的逻辑。通过相关的源码分析,我们可以发现最终都会调用到Activity/Fragment的getLifecycle()方法获取Lifecycle对象,之后再调用Lifecycle对象的handleLifecycleEvent()方法进行事件分发。26.1.0及更高版本Support支持库中的Activity和Fragment已经实现了LifecycleOwner接口。

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}
public class Fragment implements implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner {
    ... ...
   LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    ... ...
}
public class FragmentActivity extends BaseFragmentActivityApi16 implements
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator {
    ... ...
    // FragmentActivity最终继承自SupportActivity
   @Override
    public Lifecycle getLifecycle() {
        return super.getLifecycle();
    }
    ... ...
}
public class SupportActivity extends Activity implements LifecycleOwner {
    ... ...
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    ... ...
}

有上述源码可以,其实getLifecycle() 方法最终返回的都是LifecycleRegistry对象,事件分发最后也都是调用LifecycleRegistry的handleLifecycleEvent()方法。

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }
    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        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 newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

这些只是分发的逻辑,那么在事件分发之前,肯定要有事件的注册,这就得看一下addObserver()方法。

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }
    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

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

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

至此,我们可以知道,当lifecycle发生变化时,handleLifecycleEvent
会通过 getStateAfter()方法获取当前应处的状态并修改mState值,紧接着遍历所有 ObserverWithState并调用他们的sync方法来同步且通知LifecycleObserver状态发生变化。

总结

Lifecycle生命周期事件感知由LifecycleDispatcher(ActivityLifecycleCallbacks, FragmentLifecycleCallbacks, Fragment)完成,并通过 LifecycleRegistry传递给 LifecycleObserver。

链接:https://www.jianshu.com/p/f3160cf00e49

你可能感兴趣的:(Lifecycle源码解析)