Introduction to the

Lifecycle is a class that stores information about the Lifecycle state of a component, such as an Activity or Fragment, and allows other objects to observe that state.

The official definition of Lifecycle is very simple and its role is clear: Store the Lifecycle state of a component that has a Lifecycle and act as an observed, allowing other components to maintain observations of the Lifecycle state.

Proper use of the Lifecycle component will give our code significant benefits:

  • You don’t need to put a lot of code in the component lifecycle method to handle the monitoring of the component lifecycle, and then decouple the code while making it more organized and streamlined and easy to maintain.
  • Lifecycle components do not directly hold strong references to Lifecycle components (activities, fragments, etc.), avoiding potential memory leaks.

This is perfectly illustrated in ViewMode and LiveData, with Lifecycle they have Lifecycle awareness.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            Log.e("lifecycle","${event.name}")
        }
    })
}
Copy the code

Implementing the above code in the Activity allows you to monitor the Activity lifecycle, But the premise is the Activity of the parent class or indirect superclass must be ComponentActivity/AppCompatActivity or other realized LifecycleOwner class.

Lifecycle component role

Lifecycle components are three important components: LifecycleOwner, LifecycleRegistry/Lifecycle and LifecycleObserver. They play the roles of producer, manager and consumer respectively. The entire component controls and schedules the lifecycle around three roles. LifecycleOwner is responsible for issuing LifecycleRegistry, LifecycleRegistry is responsible for storing and scheduling LifecycleObserver monitors and consumes LifecycleRegistry bindings.

  • LifecycleOwner: a single method interface that means that the class implementing the interface has Lifecycle;
  • LifecycleRegistry: A subclass of Lifecycle, which holds both a weak reference to LifecycleOwner and a strong reference to LifecycleObserver, acts as a bridge and acts as an observer in its own right. LifecycleOwner stores its lifecycle state in LifecycleRegistry. LifecycleRegistry is notified whenever the LifecycleOwner’s lifecycle changes (of course, each lifecycle component holds an instance of LifecycleRegistry), LifecycleObserver implements lifecycle observation through the observer mode and LifecycleRegistry binding.
  • LifecycleObserver: An observer of the lifecycle, itself an empty interface that does all the work of a concrete implementation class and only acts as a type marker.

Their relationship is roughly as follows:

LifecycleOwner

LifecycleOwner’s definition is simple:

public interface LifecycleOwner {
    Lifecycle getLifecycle();
}
Copy the code

It is a single method interface that marks the implementation class that holds Lifecycle objects. The getLifecycle method returns a Lifecycle, which is essentially an instance of Lifecycle’s implementation class LifecycleRegistry. AppCompatActivity, ComponentActivity and androidx. Fragments. The app. The fragments are implements this interface. Taking ComponentActivity as an example, LifeCycle is implemented as follows:

public class ComponentActivity extends Activity implements LifecycleOwner {
        private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
        public Lifecycle getLifecycle() {
                return mLifecycleRegistry;
        }
}
Copy the code

The purpose is simple and straightforward, to provide an instance of Lifecycle, which is LifecycleRegistry, to the outside world.

LifecycleRegistry/Lifecycle

LifecycleRegistry is a subclass of LifeCycle. It acts as a bridge across the component, storing and distributing the state of the lifecycle. It is through this that the entire component achieves decoupling and data transfer.

Lifecycle is an abstract class that defines two abstract methods, addObserver and removeObserver, to add and remove objects that listen for the Lifecycle. Both methods are implemented by LifecycleRegistry.

There are also two enumerated classes that represent the life cycle:

  • Events: Events that occur when the Lifecycle changes, emitted by Lifecycle (Activity), corresponding to callback events in activities and fragments.
  • State: indicates the current status of the component
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;
}
Copy the code

Notice these two, they look very similar and very related. Event indicates the State that occurs when a component’s life cycle changes, and State indicates a State in the current component’s life cycle. In the Event enumeration class there are the following methods:

public State getTargetState() {
    switch (this) {
        case ON_CREATE:
        case ON_STOP:
        return State.CREATED;
        case ON_START:
        case ON_PAUSE:
        return State.STARTED;
        case ON_RESUME:
        return State.RESUMED;
        case ON_DESTROY:
        return State.DESTROYED;
        case ON_ANY:
        break;
    }
    throw new IllegalArgumentException(this + " has no target state");
}
Copy the code

Their relationship can be summarized as follows:

Lifecycle itself as an abstract class is more about defining functions and its behavior is basically implemented through LifecycleRegistry:

public class LifecycleRegistry extends Lifecycle {


    //存储绑定的生命周期观察者
    //使用LifecycleObserver作为key值,使用ObserverWithState内部类作为value
    //ObserverWithState持有LifecycleObserver和State,前者是观察者的引用
    //State表示该观察者所持有的状态
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
    //组件当前的生命周期状态
    private State mState;
    
    //通过弱引用的方式持有LifecycleOwner(Activity/Fragment)
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    //正在进行绑定的观察者数量
    //用来标价正在通过addObserver进行绑定的观察者的数量
    private int mAddingObserverCounter = 0;

    //是否正在处理生命周期事件
    //mHandlingEvent为true时表示正在向外分生命周期状态
    private boolean mHandlingEvent = false;
    //标记有新事件发生
    private boolean mNewEventOccurred = false;

    //构造方法
    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        this(provider, true);
    }

    private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
        mEnforceMainThread = enforceMainThread;
    }

    //根据当前的生命周期事件,设置当前的状态并通知观察者
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    }

    //开始处理状态
    private void moveToState(State next) {
        //如果当前状态和接收到的状态一致,那么直接返回不做任何处理
        if (mState == next) {
            return;
        }
        //修改当前的生命周期状态
        mState = next;
        //如果正在分发状态或者有观察者正在添加,则标记有新事件发生
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            return;
        }
        //标记正在处理事件
        mHandlingEvent = true;
        //开始同步生命周期状态
        sync();
        //还原标记
        mHandlingEvent = false;
    }

    private void sync() {
        //获取LifecycleOwner并确保不为空
        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;        
            //第一种是当前的状态值小于之前的状态,则执行回退状态的操作(如CREATED->RESUMED)
            //由于backwardPass是采用倒序迭代器对链表中的观察者一次进行迭代
            //所以这种情况下通过链表第一个元素进行状态比对
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }

            //第二种是当前的状态值大于之前的状态,则执行前进状态的操作(如>RESUMED->CREATED)
            //由于forwardPass是采用正序迭代器对链表中的观察者一次进行迭代
            //所以这种情况下通过链表最后一个元素进行状态比对
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    //判断是否同步完成
    //通过判断mObserverMap的最eldest和newest的状态是否和当前状态一致
    //来判断是否是否将状态同步到了所有观察者
    //mObserverMap是一个FastSafeIterableMap类型的,它继承自SafeIterableMap
    //实现了类似LinkedHashMap的功能
    //其中eldest获取的是第一个被添加的元素,也就是第一个观察者
    //newest为最近一个别添加进来的元素也就是最后一个观察者
    //由于生命状态同步是通过FastSafeIterableMap中的迭代器一次实现的
    //所以当链表的头尾数据相同且都和当前状态保持一直,则可以认为它们同步完成了
    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

    private void forwardPass(LifecycleOwner lifecycleOwner) {
        //获取迭代器,此处是一个正序迭代器
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        //开始迭代,遍历通知所有的观察者        
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            //通过一个while一级一级的改变状态
            //如果观察者所处的状态和组件的最新状态跨等级,则一步一步的升级而不会跨状态提升
            //于此同时状态每次升级,观察者都会拿到一次回调
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event up from " + observer.mState);
                }
                //此处的observer是一个ObserverWithState类型,它是LifecycleRegistry的静态内部类
                //它持有生命周期观察者的引用和它所处的状态
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
       //backwardPass除了采用倒序降级,其他地方与forwardPass逻辑基本一致。
        ...                
    }

    //增加新的LifecycleObserver观察者对象
    public void addObserver(@NonNull LifecycleObserver observer) {
        enforceMainThreadIfNeeded("addObserver");
        //如果当前组件不处于DESTROYED状态,那么标记LifecycleObserver的初始状态为INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //创建ObserverWithState,为LifecycleObserver赋予状态
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //添加到容器mObserverMap中
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        //如果previous不为null,表示重复添加,直接结束
        if (previous != null) {
            return;
        }

        //判断LifecycleOwner是否已经被销毁
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            return;
        }

        //判断是否是重入状态
        //例如在LifecycleObserver拿到回调之后又立即添加了监听
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        //计算状态
        State targetState = calculateTargetState(observer);
        //标记正在添加的LifecycleObserver的数量
        mAddingObserverCounter++;

        //通过一个while循环来将LifecycleObserver的状态设置为最新
        //设置的过程和forwardPass一致,逐级改变并且可能会多次触发回调
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            final Event event = Event.upFrom(statefulObserver.mState);
            if (event == null) {
                throw new IllegalStateException("no event up from " + statefulObserver.mState);
            }
            //分发事件,此处和forwardPass里的一致
            statefulObserver.dispatchEvent(lifecycleOwner, event);
            popParentState();
            targetState = calculateTargetState(observer);
        }

        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }

    @Override
    public void removeObserver(@NonNull LifecycleObserver observer) {
        //移除观察者LifecycleObserver
        mObserverMap.remove(observer);
    }


    //获取当前的生命周期状态
    public State getCurrentState() {
        return mState;
    }

    //封装LifecycleObserver和State
    //为LifecycleObserver增加状态
    //用来和组件的生命周期状态比对
    //以判定生命周期是否发生改变以及后续要执行的操作
    static class ObserverWithState {
        //观察者LifecycleObserver所处的状态
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
        	//处理LifecycleObserver,下文LifecycleObserver小节会讲到
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            //分发状态并修改LifecycleObserver最新的生命周期状态
            State newState = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
}

Copy the code

The detailed logic is explained in code comments, but there are a few points to note:

  1. LifecycleRegistry does not hold LifecycleObserver directly, but instead stores LifecycleObserver in FastSafeIterableMap using ObserverWithState as the Key value. ObserverWithState holds LifecycleObserver and holds a lifecycle state, which represents the state LifecycleObserver currently receives. This state is compared with the lifecycle state of the component to determine whether the state will be upgraded or degraded or remain unchanged.
  2. FastSafeIterableMap inherits from SafeIterableMap and stores data internally through HashMap, but has the characteristics of LinkedHashMap. It traverses data through bidirectional linked lists and provides two iterators in positive and reverse order.
  3. LifecycleObserver is bound to its initial State each time it is added (INITIALIZED by default if the component is not in the DESTROYED State) and is compared with the current State of the component. If the State is different, the State distribution mechanism will be triggered immediately. LifecycleObserver will also receive a callback immediately. LifecycleObserver may trigger a callback as soon as it is registered.
  4. There are two modes of state change, but they are both in order. INITIALIZED; CREATED; CREATED; STARTED; Experienced) can go up through a forwardPass and process only code that goes in the direction of the code, or can go down through a backwardPass and process only code that goes in a DESTROYED direction. The former uses positive order to notify the observer of the callback, while the latter uses reverse order.
  5. State calls are distributed level by level, not across levels. After a state change (or when a listener is added), multiple dispatches and callbacks can be triggered by reissuing events depending on the level difference.

For the fifth point, analyze it in detail using the forwardPass method.

private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) {
                    throw new IllegalStateException("no event up from " + observer.mState);
                }
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
Copy the code

Notice the second while loop, which continually compares the state of ObserverWithState (the current state of LifecycleObserver) with the current lifecycle state of the component. If the states do not match, the Event that triggered the next-level state is retrieved via event.upfrom and reissued. Note the next level, not the current state of the component (lifecycleregistry.mstate). Look specifically at the upFrom method:

public static Event upFrom(@NonNull State state) { switch (state) { case INITIALIZED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; default: return null; }}Copy the code

Note that we passed in observer.mstate, which is the current state of the observer LifecycleObserver. ForwardPass then calls observer.dispatchEvent(lifecycleOwner, event); :

static class ObserverWithState { void dispatchEvent(LifecycleOwner owner, Event event) { State newState = event.getTargetState(); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }}Copy the code

As you can see, each loop only changes the state one level, and then continues through the loop until the state is synchronized. That is, while the component is in the RESUMED state, the LifecycleObserver is INITIALIZED. Three callbacks are triggered, and the event. name is ON_CREATE->ON_START->ON_RESUME.

Similarly, in backwardPass, Event. DownFrom is used to obtain events:

public static Event downFrom(@NonNull State state) { switch (state) { case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; default: return null; }}Copy the code

And when the observer is bound, the state is immediately compared and synchronized. So it is possible to trigger a callback when you add a listener, but it also follows the rule of changing state step by step. So write the following code in onCreate:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                Log.e("lifecycleOwnerState","${source.lifecycle.currentState}")
                Log.e("lifecycleEvent","${event.name}")
            }
        })
    }
Copy the code

The output is as follows:

E/lifecycleOwnerState: CREATED
E/lifecycleEvent: ON_CREATE
E/lifecycleOwnerState: STARTED
E/lifecycleEvent: ON_START
E/lifecycleOwnerState: RESUMED
E/lifecycleEvent: ON_RESUME
Copy the code

Because the initial state is INITIALIZED, the RESUMED are upgraded to three times. And the LifecycleOwner, which is an Activity, is already in its RESUMED state, so it gets its latest state every time. Three state changes occur in the Observer holding class ObserverWithState, which marks the Observer state as the member variable mState of ObserverWithState.

LifecycleObserver

The LifecycleObserver class is an interface that acts more as a type or identity token. It is itself an empty interface:

public interface LifecycleObserver {
}
Copy the code

All tasks are basically done by its concrete implementation classes. It has the following direct implementations. Each immediate implementation has a different other implementation.

LifecycleEventObserver is the simplest implementation: only the onStateChanged method is provided to get the event and the current state.

public interface LifecycleEventObserver extends LifecycleObserver {
  onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
Copy the code

There are FullLifecycleObserver:

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}
Copy the code

FullLifecycleObserver is a bit more complex, and instead of passing onStateChanged callback all at once, it splits events and triggers different methods for different events.

And differentiate between event logic into an implementation of LifecycleEventObserver FullLifecycleObserverAdapter:

class FullLifecycleObserverAdapter implements LifecycleEventObserver { private final FullLifecycleObserver mFullLifecycleObserver; private final LifecycleEventObserver mLifecycleEventObserver; FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver, LifecycleEventObserver lifecycleEventObserver) { mFullLifecycleObserver = fullLifecycleObserver; mLifecycleEventObserver = lifecycleEventObserver; } @Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { switch (event) { case ON_CREATE: mFullLifecycleObserver.onCreate(source); break; case ON_START: mFullLifecycleObserver.onStart(source); break; case ON_RESUME: mFullLifecycleObserver.onResume(source); break; case ON_PAUSE: mFullLifecycleObserver.onPause(source); break; case ON_STOP: mFullLifecycleObserver.onStop(source); break; case ON_DESTROY: mFullLifecycleObserver.onDestroy(source); break; case ON_ANY: throw new IllegalArgumentException("ON_ANY must not been send by anybody"); } if (mLifecycleEventObserver ! = null) { mLifecycleEventObserver.onStateChanged(source, event); }}}Copy the code

Is also a LifecycleEventObserver FullLifecycleObserverAdapter itself. You can use it to bind as an observer to listen for life cycle events. Instead, it overrides the onStateChanged method to implement refinements and differentiations of events via switch, and it holds FullLifecycleObserver and LifecycleEventObserver, which can distribute events on demand.

You may be wondering how LifecycleRegistry differentiates the specific types of observers, since it only provides an addObserver(LifecycleObserver) method. The answer lies in the inner class ObserverWithState of LifecycleRegistry. LifecycleRegistry does not store LifecycleObserver directly, but rather through ObserverWithState. It is constructed as follows:

static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; }}Copy the code

MState is used to mark the state of the LifecycleObserver as explained above. Focus on Lifecycling. LifecycleEventObserver (observer) this code. LifecycleEventObserver is a static method of Lifecycling:

Static LifecycleEventObserver LifecycleEventObserver (Object Object) {// Determine the Observer type Boolean isLifecycleEventObserver =  object instanceof LifecycleEventObserver; boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver; / / if the Observer realizes LifecycleEventObserver and FullLifecycleObserver / / at the same time through FullLifecycleObserverAdapter packaging it, And for FullLifecycleObserverAdapter / / two variables fullLifecycleObserver and lifecycleEventObserver assignment. To call back all related methods. if (isLifecycleEventObserver && isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, (LifecycleEventObserver) object); } / / if only FullLifecycleObserver, for packaging, but for FullLifecycleObserverAdapter lifecycleEventObserver / / assignment is empty. Don't for the callback if (isFullLifecycleObserver) {return new FullLifecycleObserverAdapter ((FullLifecycleObserver) object, null); } //LifecycleEventObserver: if (isLifecycleEventObserver) {return (LifecycleEventObserver) object; } // Implement 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); }Copy the code

You can see that Lifecycling determines the type each time a listener is added to ensure that LifecycleRegistry correctly triggers callback events for different observers.

In addition, lifecycleEvening Server also has a common implementation: LifecycleBoundObserver. It is the inner class of LiveData that gives LiveData lifecycle awareness.

Event producer

With the introduction of the various roles that LifeCycle plays, we have seen how LifeCycle event distribution and state flows are handled. LifecycleRegistry accepts events by exposing the handleLifecycleEvent method for subsequent processing. The logic on the consumer side is clear. The next step is to find the source of the event: how the events that LifeCycle processes are generated.

Common life cycle event producers are activities and fragments. As mentioned earlier, ComponentActivity implements the LifecycleOwner interface, which is a producer that provides events. But instead of using the handleLifecycleEvent method directly in its own lifecycle method, it does so through the ReportFragment. Its onCreate method has the following code:

 protected void onCreate(@Nullable Bundle savedInstanceState) {
    mSavedStateRegistryController.performRestore(savedInstanceState);
    mContextAwareHelper.dispatchOnContextAvailable(this);
    super.onCreate(savedInstanceState);
    mActivityResultRegistry.onRestoreInstanceState(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}
Copy the code

Look at the ReportFragment. InjectIfNeededIn done:

public static void injectIfNeededIn(Activity activity) { if (Build.VERSION.SDK_INT >= 29) { LifecycleCallbacks.registerIn(activity); } android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); }}Copy the code

InjectIfNeededIn is handled in two cases:

If the system version is >= 29, a LifecycleCallbacks is bound to the Activity and lifecycle listening is done directly. LifecycleCallbacks. RegisterIn part of the code is as follows:

static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { static void registerIn(Activity activity) { activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) { } @Override public void onActivityPostCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { dispatch(activity, Lifecycle.Event.ON_CREATE); }... }Copy the code

It implements the Application ActivityLifecycleCallbacks interface, and has carried on the registration to the Activity.

The dispatch method is implemented as follows:

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); }}}Copy the code

This is where the handleLifecycleEvent method of LifecycleRegistry is called for event handling and distribution.

Within an Activity, however, every time a lifecycle method is triggered. Will traverse ActivityLifecycleCallbacks back then. For example, onPause, the code is as follows:

private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacks = new ArrayList<Application.ActivityLifecycleCallbacks>(); protected void onPause() { ... dispatchActivityPaused(); . } / / distribute event private void dispatchActivityPaused () {Object [] callbacks = collectActivityLifecycleCallbacks (); if (callbacks ! = null) { for (int i = callbacks.length - 1; i >= 0; I -) {/ / traverse the registered object, and in turn trigger ((Application. ActivityLifecycleCallbacks) callbacks [I]). OnActivityPaused (this); } } getApplication().dispatchActivityPaused(this); } / / return all registered callback Object private Object [] collectActivityLifecycleCallbacks () {Object [] callbacks = null; synchronized (mActivityLifecycleCallbacks) { if (mActivityLifecycleCallbacks.size() > 0) { callbacks = mActivityLifecycleCallbacks.toArray(); } } return callbacks; } / / add the callBack public void registerActivityLifecycleCallbacks (@ NonNull Application. ActivityLifecycleCallbacks callBack)  { synchronized (mActivityLifecycleCallbacks) { mActivityLifecycleCallbacks.add(callback); }}Copy the code

It’s a very simple callback.

For a system version number less than or equal to 29. Adds a UI-free ReportFragment implementation listener to the Activity and extracts some ReportFragment lifecycle methods:

@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(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 29) {
            // Only dispatch events from ReportFragment on API levels prior
            // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
            // added in ReportFragment.injectIfNeededIn
        dispatch(getActivity(), event);
    }
}
Copy the code

LifecycleRegistry’s handleLifecycleEvent method is eventually called through the Dispatch method for event handling and distribution.

So only to distinguish the version number, is registerActivityLifecycleCallbacks in Api 29 to be added.

In androidx. Fragments. App. Fragments is much simple and crude, has RESUME, for example:

LifecycleRegistry mLifecycleRegistry; public Fragment() { initLifecycle(); } private void initLifecycle() { mLifecycleRegistry = new LifecycleRegistry(this); . } public Lifecycle getLifecycle() { return mLifecycleRegistry; } void performResume() { ... onResume(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); . }Copy the code

Is the simple and crude in relevant life cycle method is executed directly by LifecycleRegistry. HandleLifecycleEvent sending events.

Relevant extension

How do LiveData and ViewModels become life-cycle aware and self-destruct at the end of an Activity’s life cycle?

ViewModel perception is very simple, in the construction method of ComponentActivity has the following code:

public ComponentActivity() { Lifecycle lifecycle = getLifecycle(); getLifecycle().addObserver(new LifecycleEventObserver() { @Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { if (event == Lifecycle.Event.ON_DESTROY) { // Clear out the available context mContextAwareHelper.clearAvailableContext(); // And clear the ViewModelStore if (! isChangingConfigurations()) { getViewModelStore().clear(); }}}}); }Copy the code

As you can see, LifeCycle implementation will formally listen for the ON_DESTROY event and then the ViewModelStore.clear method will destroy the ViewModel.

LiveData is a bit more complicated, with a LifecycleBoundObserver that listens on the lifecycle. Rewrites the onStateChanged method:

public void onStateChanged(@NonNull LifecycleOwner source,
    @NonNull Lifecycle.Event event) {
    Lifecycle.State currentState = mOwner.getLifecycle().getCurrentState();
    if (currentState == DESTROYED) {
        removeObserver(mObserver);
        return;
    }
    Lifecycle.State prevState = null;
    while (prevState != currentState) {
        prevState = currentState;
        activeStateChanged(shouldBeActive());
        currentState = mOwner.getLifecycle().getCurrentState();
    }
}
Copy the code

LiveData will not only be unbound in DESTROYED. It also makes a judgment call that triggers a LiveData callback.

Here is only a brief mention of LiveData and ViewModel lifecycle processing, more details can be combined with LiveData source analysis and ViewModel source analysis.

Lifecycle also provides the ProcessLifecycleOwner implementation that listens to the Application, that is, the Lifecycle of the Application.

This can be done with the following code:

class MainApplication : Application() { override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: ON_CREATE-> log. e(" Event ","App process created ") Lifecycle.Event.ON_START-> Lifecycle. ON_RESUME-> log. e("event","App ") Lifecycle.Event.ON_PAUSE-> ON_STOP-> log. e("event","App into background ") Lifecycle.Event. Log.e("event"," system will not distribute, will never trigger ")}}})}}Copy the code

The key code for ProcessLifecycleOwner is as follows:

public class ProcessLifecycleOwner implements LifecycleOwner { private Handler mHandler; private final LifecycleRegistry mRegistry = new LifecycleRegistry(this); private Runnable mDelayedPauseRunnable = new Runnable() { @Override public void run() { dispatchPauseIfNeeded(); dispatchStopIfNeeded(); }}; ActivityInitializationListener mInitializationListener = new ActivityInitializationListener() { @Override public void onCreate() { } @Override public void onStart() { activityStarted(); } @Override public void onResume() { activityResumed(); }}; private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner(); public static LifecycleOwner get() { return sInstance; } static void init(Context context) { sInstance.attach(context); } void activityStarted() { mStartedCounter++; if (mStartedCounter == 1 && mStopSent) { mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); mStopSent = false; } } void activityResumed() { ... } void activityPaused() { ... mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS); } void activityStopped() { dispatchStopIfNeeded(); } void dispatchStopIfNeeded() { if (mStartedCounter == 0 && mPauseSent) { mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); mStopSent = true; } } private ProcessLifecycleOwner() { } void attach(Context context) { mHandler = new Handler(); mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); Application app = (Application) context.getApplicationContext(); app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() { @Override public void onActivityPreCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { . activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() { @Override public void onActivityPostStarted(@NonNull Activity activity) { activityStarted(); } @Override public void onActivityPostResumed(@NonNull Activity activity) { activityResumed(); }}); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (Build.VERSION.SDK_INT < 29) { ReportFragment.get(activity).setProcessListener(mInitializationListener); } } @Override public void onActivityPaused(Activity activity) { activityPaused(); } @Override public void onActivityStopped(Activity activity) { activityStopped(); }}); } @NonNull @Override public Lifecycle getLifecycle() { return mRegistry; }}Copy the code

The following points can be summarized:

  • ProcessLifecycleOwner through Application. RegisterActivityLifecycleCallbacks callback to listen on life cycle.
  • ProcessLifecycleOwner listens for the Application life cycle and does not trigger ON_DESTROY;
  • ProcessLifecycleOwner use may use handler. postDelayed which will delay TIMEOUT_MS, 700 ms.

Next comes the initialization analysis of ProcessLifecycleOwner.

public class ProcessLifecycleOwnerInitializer extends ContentProvider { @Override public boolean onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; }... }Copy the code

ProcessLifecycleOwner through ProcessLifecycleOwnerInitializer is initialized, it is a ContentProvider.

LifeCycle will automatically register it in the AndroidManifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="androidx.lifecycle.process" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="28" />
    <application>
        <provider
            android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
            android:authorities="${applicationId}.lifecycle-process"
            android:exported="false"
            android:multiprocess="true" />
    </application>
</manifest>
Copy the code

In this way LifeCycle enables non-intrusive listening to the Application.

conclusion

  • Activities and fragments implement LifecycleOwner to hold instances of LifecycleRegistry, and use LifecycleRegistry to distribute and handle lifecycle events.
  • LifecycleRegistry holds a weak reference to LifecycleOwner to get relevant state while avoiding possible memory leaks;
  • LifecycleRegistry distributes events step by step and does not jump. If there is a level difference, all intermediate events will be reissued;
  • ComponentActivity will adopt ReportFragment undertakes respectively according to different system version number and Application. The registerActivityLifecycleCallbacks callback distribute events in one of two ways. Fragments are distributed directly.