Lifecycle is a Component from Google that can sense the Lifecycle of components such as activities/fragments. With Lifecycle, we can avoid writing too much logic in Activity/Fragment Lifecycle functions and make our business logic more decoupled. Lifecycle is described below and how it works. LiveData: ViewModel

One: Add dependencies

dependencies {
    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0."

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

    // Saved state module for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    // Annotation processor
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    // optional - helpers for implementing LifecycleOwner in a Service
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

    // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$arch_version"
}
Copy the code

Add dependencies as needed

2: use

2.1: ProcessLifecycleOwner (listens for the entire application lifecycle)

We can use ProcessLifecycleOwner to listen to whether the application is in the foreground or background. The code is as follows:

class MApp :Application() {override fun onCreate(a) {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
    }
}

class AppLifecycleObserver :LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgound(a){
        Log.e("ccm"."====AppLifecycleObserver=====onAppBackgound==")}@OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForeground(a){
        Log.e("ccm"."====AppLifecycleObserver=====onAppForeground==")}}Copy the code
  • In the applicatioin onCreate method using ProcessLifecycleOwner. The get (). The lifecycle. The addObserver (AppLifecycleObserver ()) add to monitor
  • AppLifecycleObserver implements LifecycleObserver. The onAppBackgound() method annotated by @onlifecycleEvent (Lifecycle.event.on_stop) is called when the application goes into the background. OnLifecycleEvent(Lifecycle.event.on_start)onAppForeground() method, called when the application comes into foreground.

The above implementation of the application into the foreground and background monitoring.

2.2: Listening for the Activity/Fragment lifecycle

We used to release resources in the Activity onDestroy. If there is a lot of business logic, the corresponding code in onDestroy is too much to maintain. With Lifecycle, we can use Lifecycle to decouple the logical code and make the activities and fragments cleaner. Here is a simple example of listening to the Activity declaration cycle:

class LearnLifeCycleActivity :AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_learnlifecycle)
        lifecycle.addObserver(LearnLifecycleObserver())
    }
}

class LearnLifecycleObserver :LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(a){
        Log.e("ccm"."===LearnLifecycleObserver==onCreate====")}@OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(a){
        Log.e("ccm"."===LearnLifecycleObserver==onStart====")}@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(a){
        Log.e("ccm"."===LearnLifecycleObserver==onResume====")}@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause(a){
        Log.e("ccm"."===LearnLifecycleObserver==onPause====")}@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop(a){
        Log.e("ccm"."===LearnLifecycleObserver==onStop====")}@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(a){
        Log.e("ccm"."===LearnLifecycleObserver==onDestroy====")}}Copy the code
  • Lifecycle. AddObserver (LearnLifecycleObserver()) uses this code in the Activity to add observations
  • The LearnLifecycleObserver class implements LifecycleObserver, and with the @onlifecycleEvent annotation, You can listen for the Activity’s onCreate(),onStart(),onResume(),onPause(),onStop(), and onDestroy() methods.

It’s very simple to use. Here’s another example. For example, we often use the Handler code, and to let the Handler in onDestroy. RemoveCallbacksAndMessages. This piece can now be decoupled by Lifecycle. As follows:

class LifecycleHandler(val lifecycleOwner:LifecycleOwner) :Handler(),LifecycleObserver{
    init {
        addObserver()
    }
    private fun addObserver(a){
        lifecycleOwner.lifecycle.addObserver(this)}@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onDestroy(a){
        removeCallbacksAndMessages(null)
        lifecycleOwner.lifecycle.removeObserver(this)}}Copy the code
  • The LifecycleHandler class inherits from Handler and implements the LifecycleObserver
  • At initialization time lifecycleOwner. Lifecycle. AddObserver add observation (this)
  • OnLifecycleEvent(Lifecycle.event.ON_DESTROY) after receiving onDestroy, Go removeCallbacksAndMessages (null) with lifecycleOwner. Lifecycle. RemoveObserver delete observation (this)

Here is a simple example. Lifecycle is simple to use. How Lifecycle can listen to the Lifecycle of a component such as an Activity/Fragment?

Three: source code analysis

In the example above, look at the code for LearnLifeCycleActivity:

class LearnLifeCycleActivity :AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_learnlifecycle)
        lifecycle.addObserver(LearnLifecycleObserver())
    }
}
Copy the code

Click on lifecycle to see what lifecycle is. Jump to ComponentActivity

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); .public Lifecycle getLifecycle() {
  return mLifecycleRegistry;
}
Copy the code

Lifecycle is LifecycleRegistry and calling lifecycle. AddObserver is actually calling the addObserver method of LifecycleRegistry. At this point, let’s pause and see what LifecycleRegistry is

public class LifecycleRegistry extends Lifecycle {... }Copy the code

LifecycleRegistry extends Lifecycle. LifecycleRegistry is the only implementation class for Lifecycle. Take a look at the code for Lifecycle

public abstract class Lifecycle {
	public abstract void addObserver(@NonNull LifecycleObserver observer);
	public abstract void removeObserver(@NonNull LifecycleObserver observer);
	public abstract State getCurrentState();
	
    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
  • Lifecycle has three main abstraction methods: addObserver, removeObserver, and getCurrentState
  • Two enumerated classes, Event, State.

Lifecycle has a look at a diagram on Lifecycle to show the relationship between Events and State.

State is the node and Event is the line connecting each node. The value of Event is completely understood according to the Activity’s life cycle and corresponds to one by one. State seems to be missing PAUSED and STOPED, but PAUSED is actually STARTED and STOPED is CREATED. In general, an Event is a life-cycle Event. State is the current life-cycle State \ of an Activity/Fragment

Now that Lifecycle is understood and LifecycleRegistry is the only implementation of Lifecycle, let’s go back to the legacy LifecycleRegistry addObserver method.

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

   if(previous ! =null) {
       return;
   }
   LifecycleOwner lifecycleOwner = mLifecycleOwner.get(a);if (lifecycleOwner == null) {
       // it is null we should be destroyed. Fallback quickly
       return; }... }Copy the code
  • State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; // Initialize the State
  • ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); Replace State with observer. Pass in ObserverWithState as an argument and build an instance of ObserverWithState.
    static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; }... }Copy the code

    ObserverWithState is an object that holds State and Observer. Then see Lifecycling. LifecycleEventObserver (observer); methods

    static LifecycleEventObserver lifecycleEventObserver(Object object) {...return new ReflectiveGenericLifecycleObserver(object);
     }
    Copy the code

    Incoming observer was actually ReflectiveGenericLifecycleObserver pack a layer, and then look at ReflectiveGenericLifecycleObserver

    class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
     private final Object mWrapped;
     private final CallbackInfo mInfo;
    
     ReflectiveGenericLifecycleObserver(Object wrapped) {
         mWrapped = wrapped;
         mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
     }
    
     @Override
     public void onStateChanged(@NonNull LifecycleOwner source, @NonNullEvent event) { mInfo.invokeCallbacks(source, event, mWrapped); }}Copy the code

    Look at what is CallbackInfo, ClassesInfoCache sInstance. GetInfo (mWrapped. GetClass ());

    CallbackInfo getInfo(Class<? > klass) { CallbackInfo existing = mCallbackMap.get(klass);
         if(existing ! =null) {
             return existing;
         }
         existing = createInfo(klass, null);
         return existing;
     }
     privateCallbackInfo createInfo(Class<? > klass,@NullableMethod[] declaredMethods) { ... Method[] methods = declaredMethods ! =null ? declaredMethods : getDeclaredMethods(klass);
         boolean hasLifecycleMethods = false;
         for (Method method : methods) {
             OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
             if (annotation= =null) {
                 continue; }... Lifecycle.Event event =annotation.value(); . 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

    We can see method.getannotation (onlifecycleEvent.class); annotation.value(); The annotations are parsed, the values are retrieved, and the stored collection is finally wrapped in the CallbackInfo class.

  • mObserverMap.putIfAbsent(observer, statefulObserver); MObserverMaps is a HashMap collection that stores the observer and statefulObserver key-value pairs into the collection.

So to summarize what addObserver does.

  • The first step is to build the ObserverWithState class, and ObserverWithState contains State and the passed Observer object, And the incoming of the Observer was actually ReflectiveGenericLifecycleObserver packing a layer, and also contains CallbackInfo ReflectiveGenericLifecycleObserver. The CallbackInfo class essentially parses and stores the information corresponding to the @onlifecycleEvent annotation of the passed Observer class
  • Store the ObserverWithState and the passed Observer class into the FastSafeIterableMap collection

Now that we’ve analyzed what the addObserver method does, we can go back and look at the getLifecycle() method, and our getLifecycle() method is in ComponentActivity, And our LearnLifeCycleActivity all inherits ComponentActivity

public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner.ViewModelStoreOwner.SavedStateRegistryOwner.OnBackPressedDispatcherOwner {.protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if(mContentLayoutId ! =0) { setContentView(mContentLayoutId); }}}Copy the code

ComponentActivity LifecycleOwner is achieved, and in the onCreate method of ComponentActivity a ReportFragment. InjectIfNeededIn (this);

public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        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(); }}Copy the code

We can see that API29 registers a LifecycleCallbacks and adds a new ReportFragment() to any API

// this class isn't inlined only because we need to add a proguard rule for it. (b/142778206)
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @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);
        }
        
        @Override
        public void onActivityStarted(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostStarted(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_START);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostResumed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_RESUME);
        }

        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPreStopped(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity,
                @NonNull Bundle bundle) {
        }

        @Override
        public void onActivityPreDestroyed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_DESTROY);
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }
Copy the code

We found that LifecycleCallbacks listens for the lifecycle of the Activity and calls the Dispatch method for each lifecycle, but the events passed in are events that correspond to the declared cycle (e.g. Dispatch (activity, Lifecycle.Event.ON_DESTROY)), and look at the ReportFragment Fragment

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

@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.injectIfNeededIndispatch(getActivity(), event); }}Copy the code

We found that dispatch was also called during the ReportFragment Lifecycle and the corresponding Lifecycle events were passed in (e.g. Dispatch (Lifecycle.event.on_destroy);). Now let’s look at 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

We see that the code will determine if the activity is of LifecycleOwner type and lifecycle is LifecycleRegistry, and then LifecycleRegistry’s handleLifecycleEvent method will be called. And the event is passed in as an argument. According to the source code we reviewed above, ComponentActivity implements LifecycleOwner and Lifecycle is LifecycleRegistry. So take a look at the handleLifecycleEvent method in LifecycleRegistry

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

State next = getStateAfter(event); Convert Event to State. There’s a graph before Event and State

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

moveToState(next); Basically, the sync method is called

 privatevoid moveToState(State next) { ... sync(); . }Copy the code

Sync method is as follows:

private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get(a);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.
            // Lifecycle backward logic
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // Lifecycle progression logic
            if(! mNewEventOccurred && newest ! =null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
}
Copy the code

Depending on the State, there are two kinds of logic: forward is the path from left to right in the life cycle State and event graph, and back is the path from right to left in the life cycle State and event graph. Look at the backwardPass logic:

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

The key code is observer.dispatchEvent(lifecycleOwner, event); DispatchEvent method with ObserverWithState

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

Call to mLifecycleObserver. OnStateChanged (the owner, the event); The implementation class is which we analyzed mLifecycleObserver ReflectiveGenericLifecycleObserver, so to see ReflectiveGenericLifecycleObserver onStateChanged method

.private finalCallbackInfo mInfo; . ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass()); }@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
}
Copy the code

InvokeCallbacks (source, event, mWrapped); Take a look at CallbackInfo’s invokeCallbacks method

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

private static void invokeMethodsForEvent(List<MethodReference> 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); }}}Copy the code

Call the invokeCallback method of MethodReference

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) {
                thrownew RuntimeException(e); }}Copy the code

Here mMethod is going to be called by reflection. So what is this mMethod? We looked at the createInfo method on CallbackInfo earlier

privateCallbackInfo createInfo(Class<? > klass,@NullableMethod[] declaredMethods) { Class<? > superclass = klass.getSuperclass(); Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();if(superclass ! =null) {
            CallbackInfo superInfo = getInfo(superclass);
            if(superInfo ! =null) { handlerToEvent.putAll(superInfo.mHandlerToEvent); } } Class<? >[] interfaces = klass.getInterfaces();for(Class<? > intrfc : interfaces) {for(Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo( intrfc).mHandlerToEvent.entrySet()) { verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass); } } Method[] methods = declaredMethods ! =null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            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");
                }
            }
            Lifecycle.Event event = annotation.value();

            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");
            }
            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

Method is the OnLifecycleEvent method annotated in the observer. Summary: The component Activity/Fragment calls the Dispatch method in the corresponding lifecycle function to distribute events, and calls the handleLifecycleEvent in LifecycleRegistry to handle events. LifecycleRegistry determines whether the logic is forward or backward based on incoming lifecycle events. Then after ObserverWithState – > ReflectiveGenericLifecycleObserver – > CallbackInfo – > MethodReference, Finally, reflection actually calls the annotated method into the custom LifecycleObserver. That’s the whole process