Lifecycle source analysis
catalogue
- What is the role of Lifecycle
- 02. Simple use of Lifecycle
- Lifecycle usage scenarios
- 04. How to realize life cycle awareness
- 05. How are annotation methods called
- 06. AddObserver call analysis
- 07. Comb and summarize the knowledge points
Use AAC to implement bus event bus
- Use LiveData to implement the EventBus instead of EventBus. Taking full advantage of lifecycle awareness, you can update activities, fragments, or services when their lifecycle is active. Support to send ordinary events, can also send sticky events; You can also send delayed messages, as well as rotational delayed messages and so on.
- Github.com/yangchong21…
What is the role of Lifecycle
- Lifecycle is a library dedicated to dealing with the Lifecycle. It helps to completely decouple the Lifecycle processing of activities and fragments from the business logic processing so that we can focus more on the business. Decouple activities and fragments to make them more readable and maintainable.
02. Simple use of Lifecycle
- Looking directly at the following example, the usage is very simple and the code is as follows
- Lifecycle can be obtained via the getLifecycle() method and an Observer can be added to listen for the Lifecycle of the Activity.
public class FourActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BusLogUtils.d("------AppCompatActivity onCreate() called"); testLifecycle(); } @Override protected void onResume() { super.onResume(); BusLogUtils.d("------AppCompatActivity onResume() called"); } @Override protected void onDestroy() { super.onDestroy(); BusLogUtils.d("------AppCompatActivity onDestroy() called"); } private void testLifecycle() { getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate(){ BusLogUtils.d("------LifecycleObserver onCreate() called"); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResume(){ BusLogUtils.d("------LifecycleObserver onResume() called"); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy(){ BusLogUtils.d("------LifecycleObserver onDestroy() called"); }}); }}Copy the code
- Then print the log record as shown below
- Lifecycle can be monitored for the Lifecycle of an activity.
- When an activity is created, the onCreate method of the activity lifecycle takes precedence over the onCreate method of the LifecycleObserver. Shut down when the opposite!
/ / open the page 09:44:09 2020-03-06. 522. 11647-11647 / com ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - AppCompatActivity onCreate () called the 2020-03-06 09:44:09. 545, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - LifecycleObserver onCreate () called the 2020-03-06 09:44:09. 551, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - AppCompatActivity onResume () called the 2020-03-06 09:44:09. 552, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - LifecycleObserver onResume () called / / close the page 09:44:14. 2020-03-06, 265, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - LifecycleObserver onStop () called the 2020-03-06 09:44:14. 265, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - AppCompatActivity onStop () called the 2020-03-06 09:44:14. 266, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: -- -- -- -- -- - LifecycleObserver onDestroy () called the 2020-03-06 09:44:14. 266, 11647-11647 / com. Ycbjie. Yclivedatabus D/BusLogUtils: ------AppCompatActivity onDestroy() calledCopy the code
Lifecycle usage scenarios
- Lifecycle has a wide range of application scenarios and we can use the Lifecycle mechanism to help us decouple all the business logic associated with the Lifecycle.
- Like pausing and playing video,
- Handler message removed,
- Cancel the network request,
- The Presenter attach&detach View
- Pause and resume animation drawing
- And it can be implemented in a more elegant way, giving us a cleaner and more readable Activity & Fragment.
- Cancel the network request
- Retrofit manages the Http Lifecycle to the extreme with Lifecycle
- Stop and enable video buffering
- Start the video buffering as soon as possible using life-cycle enabled components, but delay playback until the application is fully started. Lifecycle aware components can also be used to terminate buffering when the application is destroyed.
- Start and stop network connections
- Use lifecycle aware components to update (stream) network data in real time while the application is in the foreground and automatically pause when the application is in the background.
- Pause and resume animation drawing
- Use lifecycle aware components to handle suspending animation drawing while the application is running in the background and resuming animation drawing after the application is running in the foreground.
04. How to realize life cycle awareness
- Looking at the simple example above, you can see that a method annotated @onlifecycleEvent (Lifecycle.event.on_create) can perform Lifecycle listening.
- So trace Lifecycle.Event class and see where else this annotation is used, as shown in the screenshot below. Here we have a look at the ReportFragment class.
4.1 Life cycle events and states
- In the example above, annotations are used. What are their states?
- Lifecycle is an abstract class that has two main functions: Event Lifecycle and State.
- Lifecycle.Event represents the state of the Lifecycle, similar to the Activity Lifecycle.
- Lifecycle.State indicates the Lifecycle State of the current component,
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(); @SuppressWarnings("WeakerAccess") public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } @SuppressWarnings("WeakerAccess") public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(@NonNull State state) { returncompareTo(state) >= 0; }}}Copy the code
- Relationship between Event and State (from network)
4.2 ReportFragment Class Analysis
- The source code is shown below, but only some of the lifecycle related source code has been extracted.
- Lifecycle.event.xxx (Lifecycle) is called in the Lifecycle method and the ReportFragment is doing the work.
- Lifecycle uses fragments to listen for life cycles and ultimately dispatches Lifecycle events.
- LifecycleRegistry’s handleLifecycleEvent method is called within the Dispatch method to distribute the Fragment lifecycle when it changes.
Public class ReportFragment extends Fragment {public class ReportFragment extends Fragment { Public static void injectIfNeededIn(Activity Activity) {// ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragmentsfor activities android.app.FragmentManager manager = activity.getFragmentManager(); if(manager. FindFragmentByTag (REPORT_FRAGMENT_TAG) = = null) {/ / add Fragment to the Activity of manager. The beginTransaction (). The add (new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); dispatchCreate(mProcessListener); // Dispatch the state dispatch(Lifecycle.event.on_create); } @Override public voidonStart() { super.onStart(); dispatchStart(mProcessListener); Lifecycle.Event.ON_START (Lifecycle. } @Override public voidonResume() { super.onResume(); dispatchResume(mProcessListener); Lifecycle.Event.ON_RESUME); // Lifecycle. } @Override public voidonPause() { super.onPause(); // Dispatch state (Lifecycle. Event.on_pause); } @Override public voidonStop() {// Distribute status super.onstop (); dispatch(Lifecycle.Event.ON_STOP); } @Override public voidonDestroy() { super.onDestroy(); // Dispatch state 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) {// Get host activity activity activity = getActivity(); If (Activity instanceof LifecycleRegistryOwner) {handleLifecycleEvent method source code ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); If (lifecycle instanceof LifecycleRegistry) {//// 下 载 下 载 handleLifecycleEvent lifecycle).handleLifecycleEvent(event); }}} / /... }Copy the code
- Then take a look at where to this ReportFragment class, specific to track the DispatcherActivityCallback LifecycleDispatcher onActivityCreated methods of inner classes, the source code is shown below
class LifecycleDispatcher { static void init(Context context) { if (sInitialized.getAndSet(true)) { return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); } @SuppressWarnings("WeakerAccess") @VisibleForTesting static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks { private final FragmentCallback mFragmentCallback; DispatcherActivityCallback() { mFragmentCallback = new FragmentCallback(); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (activity instanceof FragmentActivity) { ((FragmentActivity) activity).getSupportFragmentManager() .registerFragmentLifecycleCallbacks(mFragmentCallback, true); } ReportFragment.injectIfNeededIn(activity); }}}Copy the code
- Looking at the source code for handleLifecycleEvent(Event), you can see that the State is obtained based on the event State and then distributed. It will be analyzed later that…
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } Copy the code
4.3 ComponentActivity class analysis
- Fragments depend on the host activity. By searching ReportFragment. InjectIfNeededIn calls, found ComponentActivity calls the method. (Versions below API 28 are SupportActivity)
- A LifecycleRegistry member object is created internally, and the ComponentActivity class implements the LifecycleOwner.
- In the onCreate method calls the ReportFragment. InjectIfNeededIn (this); ReportFragment is injected. The mLifecycleRegistry object is available via getLifecycle!
- Lifecycle is an abstract class and LifecycleRegistry is an implementation subclass that manages the Observer,
@RestrictTo(LIBRARY_GROUP) public class ComponentActivity extends Activity implements LifecycleOwner { private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override @SuppressWarnings("RestrictedApi") protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } @CallSuper @Override protected void onSaveInstanceState(Bundle outState) { mLifecycleRegistry.markState(Lifecycle.State.CREATED); super.onSaveInstanceState(outState); } @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } } public class LifecycleRegistry extends Lifecycle {} public abstract class Lifecycle {} Copy the code
05. How are annotation methods called
- OnLifecycleEvent comments:
- You see a retentionPolicy.runtime modifier that represents a run-time annotation that is recognized by reflection at RUNTIME.
- Run-time annotations are generally used in conjunction with reflection, which is less performance than compile-time annotations, but more flexible and easier to implement.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnLifecycleEvent { Lifecycle.Event value(); } Copy the code
- LifecycleRegistry is the receiver of the lifecycle event. It is its handleLifecycleEvent() that receives the event.
public void handleLifecycleEvent(Lifecycle.Event event) { mState = getStateAfter(event); 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
- This can be seen from the method annotation, which handles the state and notifies the Observer. Take a look at the getStateAfter() method:
- The getStateAfter() method retrieves the corresponding State based on the current Event. If you look closely, it is actually the code implementation of the figure in [2.3.3].
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
- Next, the sync() method:
private void sync() { 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(); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if(! mNewEventOccurred && newest ! = null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(); } } mNewEventOccurred =false; } Copy the code
- The sync method compares the current mState with the previous State to see if it should move forward or backward. This corresponds to the forward and backward of the life cycle, for example, from onResume -> onPause (forwardPass). OnPause -> onResume (backwardPass), take backwardPass() for example. (The forwardPass method handles this similarly.)
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 ()))) {// call downEvent to get the previous Event Event Event = downEvent(observer.mState); pushParentState(getStateAfter(event)); // dispatchEvent observer.dispatchEvent(lifecycleOwner, Event); popParentState(); } } } private static Event downEvent(State state) { switch (state) {case INITIALIZED: throw new IllegalArgumentException(); case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; case DESTROYED: throw new IllegalArgumentException(); } throw new IllegalArgumentException("Unexpected state value " + state); } Copy the code
- The backwardPass() method calls downEvent to retrieve the backward target Event. It might be a bit abstract. For example, in the onResume state, if we press home, we can go from a RESUMED state to a STARTED state, and the Event to send is ON_PAUSE. That’s what backwardPass() does. If all the previous code is an introduction, you finally see a hint of distribution — observer.dispatchEvent(lifecycleOwner, event).
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); / / here mLifecycleObserver onStateChanged (the owner, the event); mState = newState; }}Copy the code
- Can see the last call GenericLifecycleObserver. OnStateChanged () method, with again.
- This class has a lot of code, but it’s not complicated. You can see that the code finally goes to invokeCallback() and calls the method through reflection.
- This method is the OnLifecycleEvent annotation found by the createInfo() method reflecting through our registered Observer and stored in info.meventtoHandlers as Event type.
- Methods annotated in the Observer are retrieved and preserved by reflection, and the corresponding Event method is found and invoked by reflection when the lifecycle changes.
Class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {/ / mWrapped is our Observer private final Object mWrapped; // mWrapped gets the annotated method private final CallbackInfo mInfo; @SuppressWarnings("WeakerAccess") static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>(); ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = getInfo(mWrapped.getClass()); } @Override public void onStateChanged(LifecycleOwner source, Event event) { invokeCallbacks(mInfo, source, event); } private void invokeCallbacks(CallbackInfo info, LifecycleOwner source, Event event) { invokeMethodsForEvent(info.mEventToHandlers.get(event), source, event); invokeMethodsForEvent(info.mEventToHandlers.get(Event.ON_ANY), source, event); } private void invokeMethodsForEvent(List<MethodReference> handlers, LifecycleOwner source, Event event) { if(handlers ! = null) {for (int i = handlers.size() - 1; i >= 0; i--) { MethodReference reference = handlers.get(i); invokeCallback(reference, source, event); Private void invokeCallback(MethodReference reference, LifecycleOwnersource, Event event) { //noinspection TryWithIdenticalCatches try { switch (reference.mCallType) { case CALL_TYPE_NO_ARG: reference.mMethod.invoke(mWrapped); break; case CALL_TYPE_PROVIDER: reference.mMethod.invoke(mWrapped, source); break; case CALL_TYPE_PROVIDER_WITH_EVENT: reference.mMethod.invoke(mWrapped, source, event); break; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method", e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static CallbackInfo getInfo(Class klass) { CallbackInfo existing = sInfoCache.get(klass); if(existing ! = null) {return existing; } existing = createInfo(klass); returnexisting; } private static CallbackInfo createInfo(Class klass) {//... Method[] methods = klass.getDeclaredMethods(); Class[] interfaces = klass.getInterfaces();for (Class intrfc : interfaces) { for(Entry<MethodReference, Event> entry : getInfo(intrfc).mHandlerToEvent.entrySet()) { verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass); }}for (Method method : methods) { OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class); if (annotation == null) { continue; } 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"); } } Event event = annotation.value(); / /... MethodReference methodReference = new MethodReference(callType, method); verifyAndPutHandler(handlerToEvent, methodReference, event, klass); } CallbackInfo info = new CallbackInfo(handlerToEvent); sInfoCache.put(klass, info);return info; } @SuppressWarnings("WeakerAccess") static class CallbackInfo { final Map<Event, List<MethodReference>> mEventToHandlers; final Map<MethodReference, Event> mHandlerToEvent; CallbackInfo(Map<MethodReference, Event> handlerToEvent) { //... } } static class MethodReference { final int mCallType; final Method mMethod; MethodReference(int callType, Method method) { mCallType = callType; mMethod = method; mMethod.setAccessible(true); } } private static final int CALL_TYPE_NO_ARG = 0; private static final int CALL_TYPE_PROVIDER = 1; private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2; } Copy the code
06. AddObserver call analysis
- Lifecycle’s addObserver method is an abstract method. Lifecycle’s addObserver method is an abstract method. Lifecycle’s addObserver method is an abstract method
@Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState ObserverWithState statefulObserver = new ObserverWithState(Observer, initialState); // Add observer and statefulObserver objects to the FastSafeIterableMap data structure ObserverWithState Previous = mObserverMap.putIfAbsent(observer, statefulObserver);if(previous ! = null) {return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if(lifecycleOwner == null) {// It is null and we should be destroyed. Quick backreturn; } 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) { // wedo sync only on the top level. sync(); } mAddingObserverCounter--; } Copy the code
- Then look at the ObserverWithState class, trace the code back to Lifecycling. GetCallback (Observer), and see what’s going on inside
static class ObserverWithState { State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.getCallback(observer); mState = initialState; } void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }}Copy the code
- Next, look at the getCallback method in the Lifecycling class
- Check whether the Observer is GenericLifecycleObserver, if so return itself; If it is FullLifecycleObserver create a FullLifecycleObserverAdapter object directly
- The annotation handler looks for a class that contains “class name __LifecycleAdapter” Contains and OnLifecycleEvent SingleGeneratedAdapterObserver/CompositeGeneratedAdaptersObserver annotations
- If none of the above commits satisfy, the callback method is called through reflection
@NonNull static GenericLifecycleObserver getCallback(Object object) { if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } if (object instanceof GenericLifecycleObserver) { return(GenericLifecycleObserver) object; } final Class<? > klass = object.getClass(); // Gets whether the type contains an annotation handler inttype = getObserverConstructorType(klass); if (type= = GENERATED_CALLBACK) {/ / / / this is a return to SingleGeneratedAdapterObserver or CompositeGeneratedAdaptersObserver contain annotation processor 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); } returnnew CompositeGeneratedAdaptersObserver(adapters); } /// call the method through reflectionreturn new ReflectiveGenericLifecycleObserver(object); } Copy the code
- Then check the SingleGeneratedAdapterObserver class
- The last call through ObserverWithState# dispatchEvent method is SingleGeneratedAdapterObserver onStateChanged method
- Invoke the Adapter in SingleGeneratedAdapterObserver callMethods method
- This is a
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver { private final GeneratedAdapter mGeneratedAdapter; SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) { mGeneratedAdapter = generatedAdapter; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { mGeneratedAdapter.callMethods(source, event, false, null); mGeneratedAdapter.callMethods(source, event, true, null); }}Copy the code
- Then look at the CompositeGeneratedAdaptersObserver class
- The last call through ObserverWithState# dispatchEvent method is CompositeGeneratedAdaptersObserver onStateChanged method
- In CompositeGeneratedAdaptersObserver traversal mGeneratedAdapters, then also call callMethods method
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class CompositeGeneratedAdaptersObserver implements GenericLifecycleObserver { private final GeneratedAdapter[] mGeneratedAdapters; CompositeGeneratedAdaptersObserver(GeneratedAdapter[] generatedAdapters) { mGeneratedAdapters = generatedAdapters; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { MethodCallsLogger logger = new MethodCallsLogger(); for (GeneratedAdapter mGenerated: mGeneratedAdapters) { mGenerated.callMethods(source, event, false, logger); } for (GeneratedAdapter mGenerated: mGeneratedAdapters) { mGenerated.callMethods(source, event, true, logger); }}}Copy the code
- Finally see ReflectiveGenericLifecycleObserver class code
- Reflection calls the callback function, but we’ve heard about the class object, which gets its info from ClassesInfoCache. Use createInfo to scan the methods in the class. Specific analysis can see the source code……
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver { private final Object mWrapped; private final CallbackInfo mInfo; ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass()); } @Override public void onStateChanged(LifecycleOwner source, Event event) { mInfo.invokeCallbacks(source, event, mWrapped); }}Copy the code
- What is actually passed in when addObserver is a wrapped ObserverWithState object and the onStateChanged method is called to distribute the state. Use the processor to improve performance and avoid the performance cost of reflection.
07. Comb and summarize the knowledge points
- Lifecycle library senses the Lifecycle by injecting ReportFragment into the onCreate of SupportActivity;
- Lifecycle Abstract Class, one of the core classes of the Lifecycle library, is an abstraction of the Lifecycle. It defines Lifecycle events and states, through which we can capture the current Lifecycle state, and it sets the tone for the Observer pattern. (Can you see I’m a Party member :-D)
- LifecycleOwner, which describes a component that has a lifecycle, can be defined on its own, but usually we don’t need to just use AppCompatActivity, etc.
- LifecycleRegistry is the Lifecycle implementation class that takes over Lifecycle events and registers and notifies observers.
- ObserverWithState, a wrapper class is the Observer, is that it eventually ReflectiveGenericLifecycleObserve invoking the way we use annotations to modify;
- LifecycleObserver, Lifecycle observer, with which we can enjoy the power that Lifecycle brings;
- ReflectiveGenericLifecycleObserver, it stores the way we annotations in the Observer, and at the time of change in the life cycle of the final call the corresponding method by means of reflection.
Refer to the blog
- Developer.android.com/topic/libra…
- www.jianshu.com/p/7087f1dae…
- Mp.weixin.qq.com/s/P22w7K0vS…
- Mp.weixin.qq.com/s/xxYoyLXII…