LifeCycle源码解读

对于LifeCycle的简单使用可以看上一篇文章:LiveData+ViewModel+Repository搭建MVVM

这篇文章主要是为了阅读源码,尽量深入阅读,能力还是一般,见谅:

LifeCycle的作用

解决onCreate等生命周期方法,由于各种原因,后期越来越臃肿的问题。

关键类阐述

LifecycleRegistryOwner/LifecycleOwner

在Activity等组件生命周期发生变化的时候,发出相应的Event给LifecycleRegistry。

LifecycleRegistry

控制state的转换、接受分发Event事件。

LifecycleObserver

通过注解绑定Event和自定义的函数,实现对生命周期的监听并处理。

Event

@SuppressWarnings("WeakerAccess")
public enum Event {
    /**
     * Constant for onCreate event of the {@link LifecycleOwner}.
     */
    ON_CREATE,
    /**
     * Constant for onStart event of the {@link LifecycleOwner}.
     */
    ON_START,
    /**
     * Constant for onResume event of the {@link LifecycleOwner}.
     */
    ON_RESUME,
    /**
     * Constant for onPause event of the {@link LifecycleOwner}.
     */
    ON_PAUSE,
    /**
     * Constant for onStop event of the {@link LifecycleOwner}.
     */
    ON_STOP,
    /**
     * Constant for onDestroy event of the {@link LifecycleOwner}.
     */
    ON_DESTROY,
    /**
     * An {@link Event Event} constant that can be used to match all events.
     */
    ON_ANY
}

源码分析

依赖库版本:implementation "android.arch.lifecycle:extensions:1.1.1"

项目地址:https://github.com/fengqingxiuyi/LiveDataDemo

入口

getLifecycle().addObserver(new ActivityLifecycleObserver(getApplicationContext()));

进入addObserver

@Override
public void addObserver(@NonNull LifecycleObserver observer) { //这里的LifecycleObserver就是我们自定义的ActivityLifecycleObserver
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //把带着状态的observer封装成ObserverWithState
    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--;
}

进入ObserverWithState

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //通过不同的observer返回不同的mLifecycleObserver
        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;
    }
}

进入getCallback

@NonNull
static GenericLifecycleObserver getCallback(Object object) {
    if (object instanceof FullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = createGeneratedAdapter(constructors.get(i), object);
        }
        return new CompositeGeneratedAdaptersObserver(adapters);
    }
    return new ReflectiveGenericLifecycleObserver(object); //走到了这里
}

进入ReflectiveGenericLifecycleObserver

class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped); //这里:通过反射实现事件分发
    }
}

那么是在哪里调用onStateChanged的呢?下面我们继续分析:

LifecycleDispatcher

When initialized, it hooks into the Activity callback of the Application and observes Activities. It is responsible to hook in child-fragments to activities and fragments to report their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle providers related to an activity as soon it is not safe to run a fragment transaction in this activity.

第一次冷启动App的时候会通过ActivityThread创建,并且之后会在Activity创建的时候,添加ReportFragment去实现生命周期事件的分发,下面看下源码:

@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
    //省略...

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

    //省略...
}

进入ReportFragment

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    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.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();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE); //这里分发事件,我们自定义的观察者定义的注解其实就是Lifecycle.Event.ON_CREATE这一类
    }

    @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); //这里将事件分发交接给了LifecycleRegistryOwner
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); //这里将事件分发交接给了LifecycleRegistry
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

进入handleLifecycleEvent

/**
 * Sets the current state and notifies the observers.
 * <p>
 * Note that if the {@code currentState} is the same state as the last call to this method,
 * calling this method has no effect.
 *
 * @param event The event that was received
 */
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event); //获取下一个state
    moveToState(next);
}

这里借用官方的一张图(LifeCycle-States):

LifeCycle-States

大概意思就是可以通过不同的Event知道不同的State。例如:当你的Event是ON_RESUME的时候就代表他当前的State是STARTED,所以Next State就是RESUMED,接着分析getStateAfter:

//对照着表其实很简单,events是ON_CREATE和ON_STOP的下一个状态指向都是CREATED,所以返回CREATED,其他的类似。
static State getStateAfter(Event event) {
    switch (event) {
        case ON_CREATE:
        case ON_STOP:
            return CREATED;
        case ON_START:
        case ON_PAUSE:
            return STARTED;
        case ON_RESUME:
            return RESUMED;
        case ON_DESTROY:
            return DESTROYED;
        case ON_ANY:
            break;
    }
    throw new IllegalArgumentException("Unexpected event value " + event);
}

所以getStateAfter获取的是下一个State,也就是下一个生命周期。

进入moveToState

private void moveToState(State next) {
    //判断当前State是不是等于我们上面获取的
    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;
}

// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
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;
    }
    //当前的State和最早的State或最新的State进行比较,mObserverMap这个集合存放的是ObserverWithState,而ObserverWithState有我们的状态。 
    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); //继承Activity走这里
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner); //继承FramgentActivity走这里,因为Activity的子类SupportActivity实现了LifecycleOwner,而且SupportActivity是FragmentActivity的父类
        }
    }
    mNewEventOccurred = false;
}

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    //第一个while循坏遍历我们存储观察者的集合
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        //第二个是要处理各个状态经过的event
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            //upEvent返回所要经历的Event,例如:当前是STARTED, 那么他的经过的Event就是ON_RESUME
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); //在这里分发事件
            popParentState();
        }
    }
}

private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    //第一个while循坏遍历我们存储观察者的集合
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
        ObserverWithState observer = entry.getValue();
        //第二个是要处理各个状态经过的event
        while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            //downEvent返回下一个Event
            Event event = downEvent(observer.mState);
            pushParentState(getStateAfter(event));
            //upEvent返回所要经历的Event,例如:当前是STARTED, 那么他的经过的Event就是ON_RESUME
            observer.dispatchEvent(lifecycleOwner, event); //在这里分发事件
            popParentState();
        }
    }
}

进入dispatchEvent

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流程图

参考文章

添加新评论