In the last article, we discussed the simple use of Lifecycle. In this article, we will take a look at the source code for Lifecycle.
Basic environment construction
First, set up your environment quickly as described in the previous article.
Add Lifecycle lightweight dependency library:
implementation "Android. Arch. Lifecycle: the runtime: 1.1.1"Copy the code
Add support Library 28.0.0 to support library 28.0.0:
implementation 'com. Android. Support: appcompat - v7:28.0.0'Copy the code
Add an annotation for processor-specific dependencies, which will be useful later:
annotationProcessor "Android. Arch. Lifecycle: the compiler: 1.1.1"Copy the code
Next create the MyObserver class that implements the LifecycleObserver interface:
Let’s make our Activity inherit from AppCompatActivity and bind MyObserver via getLifecycle().addobServer (new MyObserver()) in the onCreate() method:
The core code, getLifecycle().addobServer (new MyObserver()), will allow us to create MyObserver classes with lifecycle awareness. We know that there are only two main objects here. LifecycleRegistry object (inherited from the abstract class Lifecycle) returned from the getLifecycle() method, and MyObserver, a class we created that needs to listen for the Lifecycle. So we have to ask: How does LifecycleRegistry perceive life cycles? How does it distribute life cycle events to the LifecycleObserver?
Let’s address the first question, how LifecycleRegistry is aware of the lifecycle.
How does LifecycleRegistry perceive the lifecycle
First, we can trace the getLifecycle() code with Command/Ctrl + left mouse button and see that its implementation is in an AppCompatActivity ancestor class SupportActivity, This class implements the LifecycleOwner interface.
The onSaveInstanceState() method sets the State of mLifecycleRegistry to Lifecycle.state.created, as we discussed in the previous article. But we still don’t see anything about the life cycle from here. At this point, we find this line of code in the onCreate() method:
ReportFragment.injectIfNeededIn(this);Copy the code
What does ReportFragment do? Click inside to see:
As you can see, the ReportFragment injectIfNeededIn(Activity Activity) method adds an unset Fragment to the Activity:
Lifecycle awareness is then distributed by calling the Dispatch (Lifecycle.Event Event) method in the rewritten Lifecycle Event, where Lifecycle awareness comes from. It’s a common trick to implement a particular function from an empty Activity or Fragment, such as the permission request library RxPermission, And Airbnb’s open source DeepLinkDispatch for URL hopping (the former uses empty fragments, the latter uses empty activities).
ReportFragment#dispatch(Lifecycle.Event event)
LifecycleRegistry’s handleLifecycleEvent(Event) method is called. This brings us to the second question, how events are distributed to the LifecycleObserver.
How are events distributed to LifecycleObserver
Enter the
LifecycleRegistry#handleLifecycleEvent(Lifecycle.Event event)
Method, which is called again
moveToState(State next)
Methods:
In the sync() method, depending on the state, backwardPass(…) is eventually called. Or forwardPass (…). :
With forwardPass (…). For example:
As you can see above, an observer object of type ObserverWithState is finally obtained via mObserverMap and its dispatchEvent is called for event distribution:
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));Copy the code
What the hell is object server with State? We follow along and discover that ObserverWithState is a static inner class of LifecycleRegistry.
As the name suggests, this class encapsulates both an Observer and a State object (specifically, State and GenericLifecycleObserver, which is an interface, Inherits from LifecycleObserver), and in its dispatchEvent method ends up calling onStateChanged(…) to mLifecycleObserver. Methods.
Following this, we know that Lifecycle will eventually call back to the onStateChanged() method of GenericLifecycleObserver after listening for Lifecycle changes. Where, we wondered, was our MyObserver definition? I don’t see any calls to our defined callback methods. What does it have to do with the GenericLifecycleObserver?
We see that the ObserverWithState constructor passes in an observer object of type LifecycleObserver. Where is this parameter passed in? I kept tracking, and I found it
LifecycleRegistry#addObserver(LifecycleObserver observer)
Methods.
And this is the way that we do it
MainActivity#onCreate(...)
Method called from:
getLifecycle().addObserver(new MyObserver());Copy the code
At this point, we are finally associated with MyObserver. To view
LifecycleRegistry#addObserver(LifecycleObserver observer)
Method source code:
There are only two lines of core code, one of which is:
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);Copy the code
This line of code creates the ObserverWithState object from the passed Observer object. Another line reads:
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);Copy the code
This line of code puts the LifecycleObserver object into a FastSafeIterableMap for iteration.
Let’s go into the constructor for ObserverWithState:
In the constructor, Lifecycling. GetCallback (Observer) builds a GenericLifecycleObserver of type mLifecycleObserver from the observer passed in. Then the secret must be in this method. Keep going.
The essence of this method is that, based on a LifecycleObserver object passed in, Construct a GenericLifecycleObserver Object (there are four subclasses: FullLifecycleObserverAdapter, SingleGeneratedAdapterObserver, CompositeGeneratedAdaptersObserver, ReflectiveGene RicLifecycleObserver), and the resulting object contains all the information about the LifecycleObserver we created, including the various callback methods.
The dependency of an annotation handler is added at the beginning of this article:
annotationProcessor "Android. Arch. Lifecycle: the compiler: 1.1.1"Copy the code
When we customize the LifecycleObserver with annotations, traditionally annotations have to be parsed through reflection, which has a performance impact. On the one hand, we use caching to avoid getting the constructor through reflection every time. On the other hand, through the annotation processor, at compile time to those by @onlifecycleEvent annotation of the ordinary method, preprocessing, generation to “class name _LifecycleAdapter” named class, will be a variety of callback methods directly logical conversion, avoid reflection, and then improve performance.
With this in mind, the Lifecycling. GetCallback (Observer) method is easier to understand.
- If the parameters of the incoming object is FullLifecycleObserver type, it constructed as FullLifecycleObserverAdapter object, and returns
- If the object passed in is of type GenericLifecycleObserver, return that object directly
- If 1,2 are not met, the constructor Type of the class is resolved (whether the class was retrieved by reflection or generated by the annotation handler). If it is through the annotation processor generated classes to invoke the callback function, it returns a SingleGeneratedAdapterObserver/CompositeGeneratedAdaptersObserver object
- If none of the above conditions are met, each callback function is called by reflection. Returns a ReflectiveGenericLifecycleObserver object
Now we add the above annotation processor dependency to the bulid.gradle in the app directory and compile the project to see the corresponding class generated in the build directory: myobserver_lifecycleAdapter.java
Click here to see the source code for the generated class:
As you can see, we passed in MyObserver
@OnLifecycleEvent
Annotation annotation methods are judged here based on conditions, not annotations.
At this point we can sort out the process, and when we add the annotation handler, Our Lifecycling. GetCallback (observer) method will build our MyObserver object into a SingleGeneratedAdapterObserver object returns (because there’s only one constructor), After mLifecycleObserver. OnStateChanged (the owner, the event); Call is actually SingleGeneratedAdapterObserver onStateChanged (the owner, the event) method:
As you can see here, it calls callMethods(…) of the enclosing class. The method, the callMethonds of MyObserver_LifecycleAdapter we mentioned above (…) Methods.
At this point Lifecycle is finished parsing the source code.
Get annotation information through reflection
This incidentally mentions the process of calling each callback method via annotations. Main related classes is ReflectiveGenericLifecycleObserver. Java
Here we focus on the code that gets the CallbackInfo:
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
Because of the reflection of the price is relatively large, so through ClassesInfoCache again. Java the singleton class, for ReflectiveGenericLifecycleObserver class to invoke the various methods of related information in the cache.
Check its getInfo(…) Inside a method, how method information is retrieved.
The createInfo() method is called:
Here, you can see the code that handles the annotations.
At this point, we have finished parsing the source code inherited from AppCompactActivity, but inherited from normal Activity, what is the principle?
Due to the space, will be put in the next article. Welcome to pay attention to my public number to obtain.