This paper mainly analyzes Lifecycle in Android Architecture Components of Jetpack. First, it will explain what Lifecycle is, and then verify the features of Lifecycle through a practical example. Then ask the question why Lifecycle is so powerful and powerful! Finally, by reading the source code for Lifecycle, answer the question step by step!

1. Introduction of Lifecycle

What is theLifecycle

Lifecycle provides classes and interfaces that can be used to build Lifecycle aware components that automatically adjust their behavior based on the current Lifecycle state of an Activity or Fragment.

In short, it is very convenient to know the life cycle of an Activity or Fragment and handle it in the corresponding callback event

This Lifecycle library can effectively avoid memory leaks and solve common Android Lifecycle problems!

2.Lifecycle basic usage

Suppose we have a requirement: we want to provide an interface that can sense the lifecycle of an Activity and implement callbacks! How is Lifecycle implemented?

2.1. Define the ILifecycleObserver interface

First we define an interface to implement the LifecycleObserver, and then define the method annotated with OnLifecycleEvent.

interface ILifecycleObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event)

}
Copy the code

Of course, you can implement the DefaultLifecycleObserver interface instead of implementing LifecycleObserver. Google officials recommend using the DefaultLifecycleObserver interface

You can rely on it in build.gradle and then you can use it

def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
Copy the code
class BaseLifecycle : DefaultLifecycleObserver {
		// Process lifecycle callbacks
}
Copy the code

2.2. Define ActivityLifecycleObserver class

Define ActivityLifecycleObserver class to implement we defined ILifecycleObserver interface

class ActivityLifecycleObserver : ILifecycleObserver {

    private var mTag = javaClass.simpleName
    override fun onCreate(owner: LifecycleOwner) {
        "onCreate ".logWithTag(mTag)
    }

    override fun onStart(owner: LifecycleOwner) {
        "onStart ".logWithTag(mTag)
    }

    override fun onResume(owner: LifecycleOwner) {
        "onResume ".logWithTag(mTag)
    }

    override fun onPause(owner: LifecycleOwner) {
        "onPause ".logWithTag(mTag)
    }

    override fun onStop(owner: LifecycleOwner) {
        "onStop ".logWithTag(mTag)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        "onDestroy ".logWithTag(mTag)
    }

    override fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
        "onLifecycleChanged  owner = $owner     event = $event".logWithTag(mTag)
    }

}
Copy the code

In this class, we print a Log in the corresponding lifecycle method, just for testing! This class is the one we’re going to use. It’s an observer that can watch the lifecycle of an Activity or Fragment

2.3. Define BaseActivity

In our BaseActivity through getLifecycle () to obtain a Lifecycle, and then put our ActivityLifecycleObserver added

open class BaseActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(ActivityLifecycleObserver())/ / 1}}Copy the code

Lifecycle is the observed. LifecycleObserver is added by adding LifecycleObserver to the Activity and notifies the observer when the Activity is executing the Lifecycle

The ActivityLifecycleObserver can sense the Activity lifecycle, is so magical

2.4. Define the LifecycleActivity class

Let LifecycleActivity** inherit **BaseActivity, then run the code and look at the log

class LifecycleActivity : BaseActivity(a)Copy the code

LifecycleActivity to start as our default Activity, start the LifecycleActivity and close the page to see the lifecycle log!

2.5. Result Logs

E/ActivityLifecycleObserver: onCreate
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_CREATE
E/ActivityLifecycleObserver: onStart
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_START
E/ActivityLifecycleObserver: onResume
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_RESUME
E/ActivityLifecycleObserver: onPause
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_PAUSE
E/ActivityLifecycleObserver: onStop
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_STOP
E/ActivityLifecycleObserver: onDestroy
E/ActivityLifecycleObserver: onLifecycleChanged  owner = com.jhb.awesomejetpack.lifecycle.LifecycleActivity@56d55b5     event = ON_DESTROY
Copy the code

Whenever LifecycleActivity correspond to the life cycle of change happened, ActivityLifecycleObserver executes corresponding events annotation methods, The onLifecycleChanged annotation is ** @onlifecyCleEvent (lifecy.event.on_any)** so it will be called every time

To sum up the above phenomenon:

We declared an ILifecycleObserver interface and added the @onlifecycleEvent (lifecyc.event.xxx) annotation to the method, In the onCreate method of BaseActivity through lifecycle. AddObserver (ActivityLifecycleObserver ()) this line of code, Then in ActivityLifecycleObserver corresponding method of specific Activity in the life cycle of the callback, good magic! Why is that?

3. Ask questions

  • How does Lifecycle perceive the Lifecycle?
  • How does Lifecycle deal with the Lifecycle?
  • How does the LifecycleObserver method callback?
  • Why is the LifecycleObserver aware of an Activity’s lifecycle

The following step by step specific analysis, read the source code, from the source code to find the answer

4. Preparation for Lifecycle’s analysis of principles

Before we can analyze the Lifecycle source code, there are a few important classes that must be sensitized to, so that we can read the source code below!

4.1. LifecycleOwner

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle(a);
}
Copy the code

Lifecycle owner, returns a Lifecycle object. If you are using AndroidX (also part of Jetpack), the LifecycleOwner interface is implemented by default in the Activity and Fragment classes

I post the code:

The following is the simplified code

public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner.XXX {

	private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    public Lifecycle getLifecycle(a) {
        returnmLifecycleRegistry; }}Copy the code
public class Fragment implements LifecycleOwner.XXX {

	private final LifecycleRegistry mLifecycleRegistry;

    public Fragment(a) {
        initLifecycle();
    }

    private void initLifecycle(a) {
        mLifecycleRegistry = new LifecycleRegistry(this);
        //....
    }

    public Lifecycle getLifecycle(a) {
        returnmLifecycleRegistry; }}Copy the code

You can see that we implement it by default in our activities and fragments

You can see that the ComponentActivity and Fragment classes implement the LifecycleOwner interface by default, and in the getLifecycle() method returns a LifecycleRegistry object. At this point Lifecycle is held in the Activity and Fragment classes, respectively

What is the Lifecycle class

4.2. Lifecycle

public abstract class Lifecycle {

    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    @NonNull
    public abstract State getCurrentState(a);

    public enum Event {}public enum State {}}Copy the code

The Lifecycle class defines methods to add and remove observers and two enumeration classes, which I’ll talk more about later

The LifecycleRegistry class is a concrete implementation of the abstract class Lifecycle and can handle multiple observers. If you customize LifecycleOwner you can use it directly.

Having said that, let’s look at the LifecycleObserver

4.3. LifecycleObserver

public interface LifecycleObserver {}Copy the code

Lifecycle is a simple interface that simply identifies this as an observer to Lifecycle. There are no internal methods and it all depends on the OnLifecycleEvent annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
    Lifecycle.Event value(a);
}
Copy the code

The value of the annotation is a Lifecycle.Event which is one of the two enumerations we didn’t look at in section 4.2. Let’s look at the two enumerations in Lifecycle.

4.4. Lifecycle. The Event and Lifecycle. The State

public abstract class 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;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0; }}}Copy the code

Event: Specify an enumeration constant that corresponds to the lifecycle of an Activity or Fragment and can respond to its lifecycle. One of the constants is ON_ANY, which can match any Event. The Event is used in conjunction with LifecycleObserver.

* class TestObserver implements LifecycleObserver {*@OnLifecycleEvent(ON_STOP)
*   void onStopped(a) *} {}Copy the code

State: The current State of the current Lifecycle itself which is used in conjunction with events

The relationship between Event and State

The following figure

4.5 summarize

  • LifecycleOwner: Lifecycle interface can be obtained. When the Lifecycle of an Activity or Fragment changes, the LifecycleRegistry class processes the corresponding Lifecycle events and notifies the LifecycleObserver
  • Lifecycle: is the observed, used to store information about the Lifecycle state of a component, such as an Activity or Fragment, and to allow other objects to observe this state.
  • LifecycleObserver: The observer can be registered by the LifecycleRegistry class through the addObserver(LifecycleObserver O) method. After being registered, the LifecycleObserver can observe the lifecycle events corresponding to the LifecycleOwner
  • Lifecycle.Event: Lifecycle events that are dispatched. These events map to callback events in the Activity and Fragment.
  • Lifecycle.State: Indicates the current State of the Lifecycle component.

Understand the above basic content, on the specific source code analysis, by looking at the source code, you can know the whole process.

5.Lifecycle source parsing

5.1. Analysis entry BaseActivity

A single line of code in the base BaseActivity class implements the lifecycle callback

open class BaseActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(ActivityLifecycleObserver())/ / 1}}Copy the code

Let’s look at the getLifecycle () method, and then watching the addObserver (ActivityLifecycleObserver ()), the content of the note this time is divided into two steps, first we see getLifecycle ()

Let’s click on the getLifecycle() method

5.2.Com ponentActivity class

Then we go to ComponentActivity, as follows

public class ComponentActivity extends xxx implements LifecycleOwner.xxx {/ / 1

	private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);/ / 2

	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ReportFragment.injectIfNeededIn(this);/ / 4
        
    }

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

Whether very familiar with, because before we have seen in section 4.1, look at the key here, one line of code in the onCreate method ReportFragment. InjectIfNeededIn (this);

** In the onCreate method, we see that a ReportFragment is initialized

5.3. ReportFragment class

public class ReportFragment extends Fragment {
	
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState); dispatchCreate(mProcessListener); dispatch(Lifecycle.Event.ON_CREATE); },@Override
    public void onStart(a) {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

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

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

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

    @Override
    public void onDestroy(a) {
        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();
      	/ / 1
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }
				/ / 2
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceofLifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); }}}}Copy the code

In the ReportFragment, each Lifecycle is called with the Dispatch (Lifecycle.Event Event) method, passing a different value of the Event. Lifecycle is the Lifecycle method to deal with.

(LifecycleRegistry) Lifecycle).handlelifecyCleEvent (Event) is finally called in the **dispatch(lifecy.event Event)** method; methods

Seeing here, remember our question in verse 3? So this is where you get to the first two questions

1. How will Lifecycle be perceived?

Each Lifecycle in the ReportFragment calls the Dispatch (Lifecycle.Event Event) method, passing different Event values

2. How does Lifecycle deal with it?

By calling (LifecycleRegistry) lifecycle).handlelifecyCleEvent (Event); Method, the LifecycleRegistry class, to handle these lifecycles.

At this point, it’s time to look at the code in LifecycleRegistry’s handleLifecycleEvent method

5.4.LifecycleRegistry handleLifecycleEvent method

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

Copy the code

Lifecycle.State specifies the State of the next Lifecycle based on the value of the current Lifecycle.Event, which is the value of the Lifecycle callback of the Activity or Fragment

//LifecycleRegistry.java
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);
}

Copy the code

The above code combined with this diagram, the effect of eating more

The value of the Lifecycle State of different lifecycle. events relative to the current State of Lifecycle.

So let’s keep going through the code and see what happens when we get to the next state

//LifecycleRegistry.java
private void moveToState(State next) {
    if (mState == next) {
        return;
    }
    mState = next;
    if(mHandlingEvent || mAddingObserverCounter ! =0) {
        mNewEventOccurred = true;
        return;
    }
    mHandlingEvent = true;
    sync();/ / 1
    mHandlingEvent = false;
}

Copy the code

Note 1: The sync() method

Then look at the sync method of LifecycleRegistry

//LifecycleRegistry.java
private void sync(a) {
    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);/ / 1
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if(! mNewEventOccurred && newest ! =null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);/ / 2
        }
    }
    mNewEventOccurred = false;
}

Copy the code

If not, mState’s current state is compared to the newest and eldest states in the mObserverMap to see whether it’s forward or backward; For example, when the mState changes from STARTED to RESUMED, the state is forward, and vice versa. (1) Lifecycle refers to a Lifecycle. (2) Lifecycle refers to a Lifecycle. (3) Lifecycle refers to a Lifecycle.

Note 2: Look at the later code here forwardPass(lifecycleOwner);

Then look at the LifecycleRegistry’s forwardPass method

//LifecycleRegistry.java
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();/ / 1
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));/ / 2popParentState(); }}}Copy the code

Note 1: Get the ObserverWithState instance

Note 2: Call the dispatchEvent method of ObserverWithState

Let’s look at the code for ObserverWithState

6.ObserverWithState

The class name is straightforward, observer and it has State,

//ObserverWithState.java
static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

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

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

So before we look at the dispatchEvent method, let’s look at the construction, how does ObserverWithState get initialized? By the way, Lifecycle. AddObserver (@nonnull LifecycleObserver observer); Method.

Is the lifecycle. AddObserver (ActivityLifecycleObserver ())

open class BaseActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(ActivityLifecycleObserver())
    }
}
Copy the code

It was initialized here.

ObserverWithState internally includes State and LifecycleEventObserver, which is an interface that inherits from the LifecycleObserver interface.

Note 1: MLifecycleObserver this for instance is ReflectiveGenericLifecycleObserver, specific points in to look at will understand, I won’t post code, But must pay attention to in the instantiation ReflectiveGenericLifecycleObserver (object); When the LifecycleObserver, incoming ReflectiveGenericLifecycleObserver structure in the, At this point ReflectiveGenericLifecycleObserver hold LifecycleObserver instance

Note 2: the key code mLifecycleObserver. OnStateChanged (the owner, the event), is actually called ReflectiveGenericLifecycleObserver onStateChanged method

Look at the next ReflectiveGenericLifecycleObserver onStateChanged method

7.ReflectiveGenericLifecycleObserver

//ReflectiveGenericLifecycleObserver.java
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

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

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);/ / 2}}Copy the code

MWrapped is actually an instance of LifecycleObserver

Note 1: Let’s look at the mInfo initialization process, which is the most critical code

Notice that at this point we are going to have to take a double look at the code in comment 1, and the code in comment 2 is the code to be called back

8. The getInfo method of ClassesInfoCache

//ClassesInfoCache.java
CallbackInfo getInfo(Class
        klass) {
    CallbackInfo existing = mCallbackMap.get(klass);
    if(existing ! =null) {
        return existing;
    }
    existing = createInfo(klass, null);/ / 1
    return existing;
}

Copy the code

This Klass is a bytecode file object for LifecycleObserver (lifecycleobserver.class) bytecode? It’s reflective. Yeah, keep watching and we’ll see.

Continue with the code

private CallbackInfo createInfo(Class<? > klass,@Nullable Method[] declaredMethods) {.../ / 1Method[] methods = declaredMethods ! =null ? declaredMethods : getDeclaredMethods(klass);
    boolean hasLifecycleMethods = false;
    for (Method method : methods) {
      / / 2
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation == null) {
            continue;
        }
        hasLifecycleMethods = true; Class<? >[] params = method.getParameterTypes();int callType = CALL_TYPE_NO_ARG;
        if (params.length > 0) {
            callType = CALL_TYPE_PROVIDER;
            if(! params[0].isAssignableFrom(LifecycleOwner.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. Must be one and instanceof LifecycleOwner"); }}/ / 3
        Lifecycle.Event event = annotation.value();
			/ / 4
        if (params.length > 1) {
            callType = CALL_TYPE_PROVIDER_WITH_EVENT;
            if(! params[1].isAssignableFrom(Lifecycle.Event.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. second arg must be an event");
            }
            if(event ! = Lifecycle.Event.ON_ANY) {throw new IllegalArgumentException(
                        "Second arg is supported only for ON_ANY value"); }}if (params.length > 2) {
            throw new IllegalArgumentException("cannot have more than 2 params");
        }
      / / 5
        MethodReference methodReference = new MethodReference(callType, method);
        verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
    }
    CallbackInfo info = new CallbackInfo(handlerToEvent);
    mCallbackMap.put(klass, info);
    mHasLifecycleMethods.put(klass, hasLifecycleMethods);
    return info;
}
Copy the code

The above code is quite long, but it is all useful. It is the process of getting the value of the annotation by the reflection fetching method. Let’s look at each of them

Note 1: Get the method declared in lifecycleobserver.class, which is the same as the method declared in the ILifecycleObserver interface in our example

Note 2: Walk through the method, getting the OnLifecycleEvent annotation declared on the method

Note 3: Get the value on the OnLifecycleEvent annotation

Note 4: Assign callType = CALL_TYPE_PROVIDER_WITH_EVENT

Note 5: Store the callType and current method in a MethodReference for subsequent retrieval

Take a look at the code in MethodReference

//MethodReference.java
static class MethodReference {
    final int mCallType;
    final Method mMethod;

    MethodReference(int callType, Method method) {
        mCallType = callType;
        mMethod = method;
        mMethod.setAccessible(true); }}Copy the code

Ok, that’s the end of the mInfo assignment problem

Look at the code for comment 1 in section 7. Now look at the code for comment 2 in Section 7

This is mInfo’s invokeCallbacks method

Continue to look at the invokeCallbacks method for ClassesInfoCache

Clicking on it goes to the invokeCallbacks method of ClassesInfoCache

//ClassesInfoCache.java
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
    invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
    invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
            target);//ON_ANY is also called
}

private static void invokeMethodsForEvent(List
       
         handlers, LifecycleOwner source, Lifecycle.Event event, Object mWrapped)
        {
    if(handlers ! =null) {
        for (int i = handlers.size() - 1; i >= 0; i--) {
            handlers.get(i).invokeCallback(source, event, mWrapped);/ / 1}}}Copy the code

Note 1: Continue to look at the invokeCallback method of MethodReference

//MethodReference.java
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
    //noinspection TryWithIdenticalCatches
    try {
        switch (mCallType) {
            case CALL_TYPE_NO_ARG:
                mMethod.invoke(target);
                break;
            case CALL_TYPE_PROVIDER:
                mMethod.invoke(target, source);
                break;
            case CALL_TYPE_PROVIDER_WITH_EVENT:/ / 1
                mMethod.invoke(target, source, event);
                break; }}catch (InvocationTargetException e) {
        throw new RuntimeException("Failed to call observer method", e.getCause());
    } catch (IllegalAccessException e) {
        throw newRuntimeException(e); }}Copy the code

Mmethod. invoke(Target); The target in this case is LifecycleObserver as explained earlier

What are the values of mCallType and mMethod? This is the value that mInfo was initialized with earlier. Look at the source code again

static class MethodReference {
    final int mCallType;
    final Method mMethod;

    MethodReference(int callType, Method method) {
        mCallType = callType;
        mMethod = method;
        mMethod.setAccessible(true);
    }

    void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
        //noinspection TryWithIdenticalCatches
        try {
            switch (mCallType) {
                case CALL_TYPE_NO_ARG:
                    mMethod.invoke(target);
                    break;
                case CALL_TYPE_PROVIDER:
                    mMethod.invoke(target, source);
                    break;
                case CALL_TYPE_PROVIDER_WITH_EVENT:
                    mMethod.invoke(target, source, event);
                    break; }}catch (InvocationTargetException e) {
            throw new RuntimeException("Failed to call observer method", e.getCause());
        } catch (IllegalAccessException e) {
            throw newRuntimeException(e); }}}Copy the code

MCallType = CALL_TYPE_PROVIDER_WITH_EVENT, mMethod is the current method at the time of traversal

Since it was previously stored via a Map, the invokeCallback is traversed, eventually reflecting the call to the method and annotations.

Of course, other mCallType values are also called by reflection

9. To summarize

Let’s go back to the original question

1. How will Lifecycle be perceived?

Each Lifecycle in the ReportFragment calls the Dispatch (Lifecycle.Event Event) method, passing different Event values

2. How does Lifecycle deal with it?

By calling (LifecycleRegistry) lifecycle).handlelifecyCleEvent (Event); Method, the LifecycleRegistry class, to handle these lifecycles.

3. How does the LifecycleObserver method call back?

LifecycleRegistry’s handleLifecycleEvent method, The corresponding method is then invoked through layers of calls and finally through the @onlifecycleEvent (lifecy.event.xxx) annotation value reflected on the LifecycleObserver method

4. Why can LifecycleObserver be aware of Activity lifecycle

LifecycleRegistry calls the handleLifecycleEvent method passing the Event type, then through the layers, and finally through reflection to get the value of the annotation, Go to the @onlifecycleEvent (lifecy.event.xxx) annotation on the LifecycleObserver method and note that this value corresponds to the Lifecycle of the Activity/Fragment. So you can sense the lifecycle of an Activity or Fragment.

10. Source address

ActivityLifecycleObserver.kt

11. The original address

Analysis of the basic use and rationale of Android Jetpack component Lifecycle

12. Refer to articles

Lifecycle is handled using lifecycle aware components

A detailed analysis of the official Android architecture component Lifecycle

series

  • Analysis of the basic use and rationale of Android Jetpack component Lifecycle
  • Android Jetpack component LiveData basic use and principle analysis
  • Android Jetpack component ViewModel basic use and principle analysis

I recommend my open source project WanAndroid client

WanAndroidJetpack architecture diagram

  • A pure Android learning project, WanAndroid client.
  • Project useMVVMArchitecture,KotlinVoice writing.
  • Extensive use of Android Jetpack includes, but is not limited toLifecycle,LiveData,ViewModel,Databinding,Room,ConstraintLayoutAnd more in the future.
  • usingRetrofitKotlin-Coroutine coroutinesNetwork interaction.
  • Loading picturesGlideMainstream load picture frame.
  • Data storage is mainly usedRoomAnd tencentMMKV.

Kotlin + MVVM + Jetpack + Retrofit + Glide is a good project to learn MMVM architecture.

This project itself is also a special learning Android related knowledge of the APP, welcome to download the experience!

Source code address (with download link)

WanAndroidJetpack

Overview of the APP

Order if you likeStarsIf you have questions, please refer to the following questions: