role

Lifecycle is an operation that a lifecycle aware component can perform in response to changes in the lifecycle state of another component, such as an Activity or Fragment. Putting part of an Activity’s business logic into Lifecycle makes the code look more organized and concise.

The basic use

MainActivity.kt

class MainActivity : AppCompatActivity() { private val TAG:String = "MainLifecycle" private val life:MainLifecycle = MainLifecycle() override  fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"onCreate") lifecycle.addObserver(life) } override fun onStart() { super.onStart() Log.d(TAG,"onStart") } override fun onResume() { super.onResume() Log.d(TAG,"onResume") } override fun onPause() { super.onPause() Log.d(TAG,"onPause") } override fun onStop() { super.onStop() Log.d(TAG,"onStop") } override fun onDestroy() { super.onDestroy() Log.d(TAG,"onDestroy") } }Copy the code

MainLifecycle.kt

class MainLifecycle : LifecycleObserver{
    private val TAG:String = "MainLifecycle"

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun create(){
        Log.i(TAG,"create")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private fun start(){
        Log.i(TAG,"start")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun resume(){
        Log.i(TAG,"resume")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private fun pause(){
        Log.i(TAG,"pause")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private fun stop(){
        Log.i(TAG,"stop")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun destroy(){
        Log.i(TAG,"destroy")
    }
}
Copy the code

The Log output

The 2021-07-20 10:29:52. 046, 15488-15488 / com. Example. Jetpacklearn D/MainLifecycle: OnCreate 10:29:52. 2021-07-20, 049, 15488-15488 / com. Example. Jetpacklearn I/MainLifecycle: Create the 2021-07-20 10:29:52. 062, 15488-15488 / com. Example. Jetpacklearn D/MainLifecycle: OnStart 10:29:52. 2021-07-20, 063, 15488-15488 / com. Example. Jetpacklearn I/MainLifecycle: Start the 2021-07-20 10:29:52. 064, 15488-15488 / com. Example. Jetpacklearn D/MainLifecycle: OnResume 10:29:52. 2021-07-20, 067, 15488-15488 / com. Example. Jetpacklearn I/MainLifecycle: Resume 10:29:55. 2021-07-20, 947, 15488-15488 / com. Example. Jetpacklearn I/MainLifecycle: Pause the 2021-07-20 10:29:55. 948, 15488-15488 / com. Example. Jetpacklearn D/MainLifecycle: OnPause 10:29:56. 2021-07-20, 366, 15488-15488 / com. Example. Jetpacklearn I/MainLifecycle: Stop the 2021-07-20 10:29:56. 370, 15488-15488 / com. Example. Jetpacklearn D/MainLifecycle: onStopCopy the code

Note that Resume precedes Activity and Lifecycle precedes Resume.

Inherit the custom Class from LifecycleObserver, annotating the methods associated with the lifecycle

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
Copy the code

Called in an Activity

getLifecycle.addObserver(lifecycle)
Copy the code

Just associate it with it

The principle of analytic

The getLifecycle.addobServer (Lifecycle) method enters the Activity inherited from ComponentActivity

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}
Copy the code

LifecycleRegistry This class is responsible for passing the time between LifecycleOwner and LifecycleObserver

In its OnCreate method

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

ReportFragment.injectIfNeededIn(this)

public static void injectIfNeededIn(Activity activity) { if (Build.VERSION.SDK_INT >= 29) { activity.registerActivityLifecycleCallbacks( new LifecycleCallbacks()); } 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

API will sign up for LifecycleCallbacks in 29. Click on this method to see

public void registerActivityLifecycleCallbacks(
        @NonNull Application.ActivityLifecycleCallbacks callback) {
    synchronized (mActivityLifecycleCallbacks) {
        mActivityLifecycleCallbacks.add(callback);
    }
}
Copy the code

See mActivityLifecycleCallbacks this variable will be found

private void dispatchActivityPreCreated(@Nullable Bundle savedInstanceState) { getApplication().dispatchActivityPreCreated(this, savedInstanceState); Object[] callbacks = collectActivityLifecycleCallbacks(); if (callbacks ! = null) { for (int i = 0; i < callbacks.length; i++) { ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreCreated(this, savedInstanceState); }}}Copy the code
private void dispatchActivityPreStarted() { getApplication().dispatchActivityPreStarted(this); Object[] callbacks = collectActivityLifecycleCallbacks(); if (callbacks ! = null) { for (int i = 0; i < callbacks.length; i++) { ((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this); }}}Copy the code

There are many life-cycle like methods that loop through the stored callback to notify lifecycle changes. CollectActivityLifecycleCallbacks this method just mActivityLifecycleCallbacks variable from the List into Array call convenient cycle.

Go back to the ReportFragment

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(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);
}
Copy the code

Both pass the life cycle through the dispatch() method.

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

After casting the Activity to LifecycleRegistryOwner, call getLifecycle() to get the LifecycleRegistry to call its handler Event.

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}
Copy the code
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; }Copy the code
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; }Copy the code

BackwardPass (lifecycleOwner) and forwardPass(lifecycleOwner) are called respectively after the status is determined.

private void backwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
            mObserverMap.descendingIterator();
    while (descendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> 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();
        }
    }
}
Copy the code
private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> 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();
        }
    }
}
Copy the code

So let’s take a look at ObserverWithState, and I forgot to mention the addObserver method, so let’s take a look at that

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

The ObserverWithState object is created, LifecycleObserver and ObserverWithState are saved into the mObserverMap, and the dispatchEvent method of ObserverWithState is finally called after judgment. So let’s look at ObserverWithState

static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }}Copy the code

Its constructor will LifecycleObserver packaged into LifecycleEventObserver, through LifecycleEventObserver. OnStateChanged to send the change of the life cycle. BackwardPass (lifecycleOwner), forwardPass(lifecycleOwner) above. The dispatchEvent method is also called to finish sending the event.