What is? Lifecycle?
Lifecycle Component means android.arch.lifecycle Various classes and interfaces provided under the package , It allows developers to build components that are aware of other components ( Mainly refers to Activity 、Fragment) Life cycle (lifecycle-aware) Class .
Why to introduce Lifecycle?
I said before. ,Lifecycle Allows developers to build components that are aware of other components ( Mainly refers to Activity 、Fragment) Life cycle (lifecycle-aware) Class . Focus on , Let developers build components that are aware of other components ( Mainly refers to Activity 、Fragment) Life cycle (lifecycle-aware) Class . stay android In the process of development , We often need to make some operations aware Activity/Fragment Life cycle of , Thus, the operation is allowed in the active state , In the destruction state, the operation needs to be automatically prohibited , Release resources , Prevent memory leaks . For example, the famous picture loading framework Glide stay Acticiy/Fragment Loading pictures while in the foreground , Stop the loading of the picture in the invisible state , Another example is that we hope RxJava Of Disposable In the Activity/Fragment Destruction is automatic dispose.Lifecycle Appearance , So that developers can easily realize the above functions .
One use Lifecycle Transformed MVP Example
For example, we need to implement such a function now : Listen to someone Activity Life cycle change , Print the log when the life cycle changes .
- The general approach is to construct callbacks
First define the basis IPresent Interface :
public interface IPresent {
void onCreate();
void onStart();
void onResume();
void onPause();
void onStop();
void onDestory();
}
Then in the custom Present In the inheritance IPresent Interface :
public class MyPresent implements IPresent {
private String TAG = "tag";
@Override
public void onCreate() {
LogUtil.i(TAG, "onCreate");
}
@Override
public void onStart() {
LogUtil.i(TAG, "onStart");
}
@Override
public void onResume() {
LogUtil.i(TAG, "onResume");
}
@Override
public void onPause() {
LogUtil.i(TAG, "onPause");
}
@Override
public void onStop() {
LogUtil.i(TAG, "onStop");
}
@Override
public void onDestory() {
LogUtil.i(TAG, "onDestory");
}
Last in Activity Call the callback method in turn to distribute the event :
public class MyActivity extends AppCompatActivity {
protected MyPresent myPresent;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
myPresent = new MyPresent();
myPresent.onCreate();
}
@Override
protected void onStart() {
super.onStart();
myPresent.onStart();
}
@Override
protected void onResume() {
super.onResume();
myPresent.onResume();
}
@Override
protected void onPause() {
super.onPause();
myPresent.onPause();
}
@Override
protected void onStop() {
super.onStop();
myPresent.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
myPresent.onDestory();
}
}
Through such a simple example , We can see that , Although the implementation process is very simple , But the code implementation is cumbersome , inflexible , And the code is too intrusive . This example just shows Present monitor Activity Life cycle , If there are classes 1, class 2, class 3...... Want to monitor Activity Life cycle of , Then it's in Activity Add a callback to the class 1, class 2, class 3..... The callback . This led to a thought , Whether we can achieve Activity What about the function of actively notifying the demand side when the life cycle changes ? Tolerable , The answer is Lifecycle.
- Lifecycle Realization Present
To achieve MyPresent, At the same time, add... To each method implementation @OnLifecycleEvent(Lifecycle.Event.XXXX) annotation ,OnLifecycleEvent Corresponding Activity Life cycle approach to :
public class MyPresent implements IPresent, LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
@Override
public void onCreate() {
LogUtil.i(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
@Override
public void onStart() {
LogUtil.i(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
@Override
public void onResume() {
LogUtil.i(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
@Override
public void onPause() {
LogUtil.i(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
@Override
public void onStop() {
LogUtil.i(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
@Override
public void onDestory() {
LogUtil.i(TAG, "onDestory");
}
}
Then in the need to monitor Activity Register in :
public class MyActivity extends AppCompatActivity {
protected MyPresent myPresent;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
getLifecycle().addObserver(new MyPresent()); // Add listening object
}
}
Run the following :
com.cimu.lifecycle I/MyPresent : onCreate()
com.cimu.lifecycle I/MyPresent : onStart()
com.cimu.lifecycle I/MyPresent : onResume()
com.cimu.lifecycle I/MyPresent : onPause()
com.cimu.lifecycle I/MyPresent : onStop()
com.cimu.lifecycle I/MyPresent : onDestroy()
Is it simple , We hope MyPresent Perceptual monitoring Activity Life cycle of , Only need Activity Call a sentence in getLifecycle().addObserver(new MyPresent()) That's all right. .Lifecycle How to realize the function of perceiving the life cycle and then notifying the observer ?
Lifecycle Source code analysis
First of all, we need to know three key things :
- LifecycleOwner: Life cycle event distributor , stay Activity/Fragment When their life cycle changes, they send out corresponding Event to LifecycleRegistry.
- LifecycleObserver: Life cycle observer , Annotate the handler function with what you want to listen for Event binding , When the corresponding Event occurs ,LifecycleRegistry The corresponding function will be notified to process .
- LifecycleRegistry: Control Center . It's responsible for controlling state Transformation 、 Accept distribution event event .
LifeCycle Source code analysis , We divide the analysis into two steps :
- register / Log off listening process
- * Life cycle Distribution process *
register / Logout monitoring process source code analysis
From the above MVP Example , We already know , Registration only needs to call getLifecycle().addObserver(observer) that will do , that addObserver It can be used as the entrance of source code analysis .
By tracking , We found that getLifecycle The return is SupportActivity Medium mLifecycleRegistry, The type is LifecycleRegistry:
public class SupportActivity extends Activity implements LifecycleOwner {
......
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
= new FastSafeIterableMap<>();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
......
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
......
}
that addObserver It's actually called LifecycleRegistry Of addObserver Method , Let's take a look at this method :
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// The listener who will send it in observer Encapsulate into a ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// Will be packaged ObserverWithState Put it in a collection
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// We dispatch An event was given to the observer , When calling back the observer code , The observer may
// Modify our status
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
About the registration process , Above, we focus on encapsulation observer Of ObserverWithState:
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//getCallback() Through different types of observer Back to different GenericLifecycleObserver Implementation class
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
// Life cycle event Distribution of , It will eventually call this method , This method calls GenericLifecycleObserver Of
// Of onStateChanged Method
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
public interface GenericLifecycleObserver extends LifecycleObserver {
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}
ObserverWithState The constructor of called Lifecycling.getCallback() Will the incoming observer To analyze , Generated a pair of interface classes GenericLifecycleObserver The specific implementation of returns , And override... In the concrete implementation class onStateChanged Method , stay onStateChanged Realize the distribution of life cycle . When Activity/Fragment When the life cycle of , Can traverse LifecycleRegistry Medium mObserverMap aggregate , Take out the ObserverWithState node , Call it the onStateChanged Method , And in the ObserverWithState Of onStateChanged The method that implements the specific life cycle distribution is called GenericLifecycleObserver.onStateChanged Method .
Based on the analysis of Lifecycling.getCallback() Before method , So let's see Lifecycle Three basic ways to use :
- The first way to use it . Use @onLifecycleEvent annotation . The annotation processor will parse the annotation and generate it dynamically GeneratedAdapter Code , This GeneratedAdapter I'll put the corresponding Lifecycle.Event Encapsulated as a method call . Finally through GenericLifecycleObserver Of onStateChanged Method call generated GeneratedAdapter Of callMechods Method for event distribution ( Let's take the following example to understand ).
public class MyLifeCycleObserver implements LifeCycleObserver {
@onLifecycleEvent(LifeCycle.Event.ON_CREATE)
public onCreate(LifeCycleOwner owner) {
//doSomething
}
@onLifecycleEvent(LifeCycle.Event.ON_DESTROY)
public onDestroy(LifeCycleOwner owner) {
//doSomething
}
}
public class MainActivity extends AppCompatActivity {
@override
public void onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getLifecycle().addObserver(new MyLifeCycleObserver());
}
}
In the above example MyLifeCycleObserver Will be at compile time , Generate GeneratedAdapter The code is as follows :
public class MyLifeCycleObserver_LifecycleAdapter implements GeneratedAdapter {
final MyLifeCycleObserver mReceiver;
MyLifeCycleObserver_LifecycleAdapter(MyLifeCycleObserver receiver) {
//mReceiver That's what our developers introduced MyLifeCycleObserver
this.mReceiver = receiver;
}
//callMechod The method will be GenericLifecycleObserver Of onStateChanged Method call , To distribute the lifecycle
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
return;
}
// If the lifecycle event is ON_CREATE, So called MyLifeCycleObserver Of onCreate Method
if (event == Lifecycle.Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreate", 2)) {
mReceiver.onCreate(owner);
}
return;
}
// If the lifecycle event is ON_DESTROY, So called MyLifeCycleObserver Of onDestroy Method
if (event == Lifecycle.Event.ON_DESTROY) {
if (!hasLogger || logger.approveCall("onDestroy", 2)) {
mReceiver.onDestroy(owner);
}
return;
}
}
}
- The second way to use it . Direct inheritance GenericLifecycleObserver, And implement onStateChange Method
public class MyLifeCycleObserver extends GenericLifeCycleObserver {
@override
void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if(event == LifeCycleEvent.Event.ON_CREATE) {
//dosomething
} else if(event == LifeCycleEvent.Event.ON_DESTROY) {
//doSomething
}
}
}
public class MainActivity extends AppCompatActivity {
@override
public void onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getLifecycle().addObserver(new MyLifeCycleObserver());
}
}
- The third way to use it . Inherit DefaultLifecycleObserver Interface (DefaultLifecycleObserver And inherit from FullLifecycleObserver Interface ), And implement FullLifecycleObserver Interface onCreate、onStart、onResume、onPause、onStop、onDestroy And other methods corresponding to their respective life cycles
class MyLifycycleObserver implements DefaultLifecycleObserver {
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
//doSomething
}
......
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
//doSomething
}
}
public class MainActivity extends AppCompatActivity {
@override
public void onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getLifecycle().addObserver(new MyLifeCycleObserver());
}
}
We learned how to use Lifecycle Three basic methods of , Now let's take a brief look Lifecycling.getCallback() The way is to generate GenericLifecycleObserver The concrete implementation class returns :
// First , Let's get familiar with resolveObserverCallbackType This method , This method is Lifecycling.getCallback()
// In the called ,getCallback Will decide what type of... To return according to its return value GenericLifecycleObserver Implementation class
private static int resolveObserverCallbackType(Class<?> klass) {
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// When using the first way of annotation , Will generate code automatically , Generated adapter Inherited GeneratedAdapter,
// So the return value is GENERATED_CALLBACK
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
//hasLifecycleMethods The way is to judge klass Is it included in onLifecycleEvent.class annotation
// If you include , return REFLECTIVE_CALLBACK
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
// Recursively call resolveObserverCallbackType Method , Traverse klass Parent class of
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
// Traversal and recursion kclass The interface of
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
//getCallBack Parameters of object It is our getLifeCycle().addObserver(observer) Listener passed in when observer
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
// The third way to use it , because DefaultLifecycleObserver Inherit and FullLifecycleObserver
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
// The second way to use it , When we use direct inheritance GenericLifecycleObserver In this way , Go straight back to
return (GenericLifecycleObserver) object;
}
final Class<?> klass = object.getClass();
// The first way to use it , When using annotations ,getObserverConstructorType The return value of GENERATED_CALLBACK
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
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);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
// When oberver When none of the above types are met , Will be instantiated directly ReflectiveGenericLifecycleObserver
// Return as an alternative ( In general , You won't come here , It may be a security model to deal with the confusion mechanism )
// stay ReflectiveGenericLifecycleObserver Will find oberver Medium onLifecyleEvent annotation , And annotate these
// The method of generating MethodReference To add to List<MethodReference> in , Call methods distributed as lifecycles
return new ReflectiveGenericLifecycleObserver(object);
}
Okay ,Lifecycling.getCallback() If you really want a detailed analysis , There will be a lot of space , ad locum , We roughly analyzed . If you want to know more about it , It's best to combine the source code with yourself .
Summarize the registration process :
- Acitivty Call in LifecycleRegistry Of addObserver, Pass in a LifecycleObserver
- Incoming LifecycleObserver It's packaged into a ObserverWithState Put it in a collection , When the life cycle changes , Will traverse this ObserverWithState aggregate , And call ObserverWithState Of dispatchEvent distributed
- stay ObserverWithState In the construction method , Called Lifecycling.getCallback(observer) Generated specific GenericLifecycleObserver Object returns . stay ObserverWithState Of dispatchEvent() Method is called GenericLifecycleObserver Object's onStateChanged Method for event distribution
As for the cancellation process, it is very simple , Direct will observer From the assembly remove, The code is as follows :
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
// we consciously decided not to send destruction events here in opposition to addObserver.
// Our reasons for that:
// 1. These events haven't yet happened at all. In contrast to events in addObservers, that
// actually occurred but earlier.
// 2. There are cases when removeObserver happens as a consequence of some kind of fatal
// event. If removeObserver method sends destruction events, then a clean up routine becomes
// more cumbersome. More specific example of that is: your LifecycleObserver listens for
// a web connection, in the usual routine in OnStop method you report to a server that a
// session has just ended and you close the connection. Now let's assume now that you
// lost an internet and as a result you removed this observer. If you get destruction
// events in removeObserver, you should have a special case in your onStop method that
// checks if your web connection died and you shouldn't try to report anything to a server.
mObserverMap.remove(observer);
}
Life cycle distribution process
We register observer When , It's actually called SupportActivity Medium mLifecycleRegistry Object method , So let's analyze SupportActivity Of onCreate Method :
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
stay onCreate Called in ReportFragment Of injectIfNeedIn Method . This method is actually to Activity Added a Fragment. We know ,Fragment Is attached to Activity Upper ,Fragment The life cycle of follows Activity Life cycle of . Since the ReportFragment Be able to sense Activity Life cycle of , So is it responsible for distributing life cycle events to LifecycleObserver What about ?
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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 fragments for activities
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@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(Lifecycle.Event event) {
Activity activity = getActivity();
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);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
ReportFragment The code is easy to understand , We can find in the code Lifecycle.Event.xxx event , And in its lifecycle callback method Lifecycle.Event.xxx The incident was passed on to dispatch Method , Obviously, it is used to distribute the life cycle . stay ReportFragment Of dispatch In the method , Called LifecycleRegistry Of handleLifecycleEvent Method :
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
Before analyzing this method , Let's first understand Lifecycle Events and states of :
public abstract class Lifecycle {
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
}
}
Lifecycle.Event Corresponding activity Each declaration cycle ,Lifecycle.State It is Lifecycle The state of . stay LifecycleRegistry The transformation relationship between States is defined in :
public class LifecycleRegistry extends Lifecycle {
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);
}
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);
}
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
}
These three methods , It can be summarized as the following figure :
downEvent In the diagram, it shows from a state to the state below him ,upEvent It's up .
I understand Lifecycle After the state of , Let's continue to look at LifecycleRegistry. We know above , When Activity After the life cycle of ,ReportFragment Will sense , This calls dispatch Method , Finally call to LifecycleRegistry Of handleLifecycleEvent Method :
public class LifecycleRegistry extends Lifecycle {
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
// When we're in LifecycleRegistry Callback LifecycleObserver When a state change is triggered ,
// mHandlingEvent by true;
// add to observer When , It is also possible to execute callback methods , At this time, if a state change is triggered ,
// be mAddingObserverCounter != 0
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// No need to execute sync.
// The implementation here is :sync() -> LifecycleObserver -> moveToState()
// After returning directly here , I'll go back to sync(), Then continue to synchronize the status to observer
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
// sync() Will transform changes in state into life cycle events , Then forward it to LifecycleObserver
sync();
mHandlingEvent = false;
}
}
LifecycleRegistry What was supposed to be done is actually very simple , But because he needs to execute the customer's code , This introduces a lot of additional complexity . as a result of , The customer code is not under our control , They can do anything they can . For example, here , A state change is triggered in the callback . A similar situation is , The client code is not called when the lock is held , This will also make the implementation more complex .
Now let's see sync():
public class LifecycleRegistry extends Lifecycle {
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*
* This Invariant It's very important , He will affect sync() The logic of
* Invariant: at any moment of time for observer1 & observer2:
* if addition_order(observer1) < addition_order(observer2), then
* state(observer1) >= state(observer2),
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
while (!isSynced()) {
// mNewEventOccurred In order to in observer When the trigger state changes, let backwardPass/forwardPass()
// For early return . We were just about to transfer them , I'm going to set it to false that will do .
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
// mObserverMap The states of the elements in the are arranged non incrementally , in other words , Team leader state Maximum
// If mState Less than the largest one in the queue , Indicates that there are elements that need to update the status
// In order to maintain mObserverMap Of Invariant, Here we need to update the status of the element from the end of the team
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// If mNewEventOccurred, Description called above backwardPass() when , The customer triggered a status change
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
// Determine whether synchronization is required , If all observer The status of has been synchronized , return true, Otherwise return to false
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
//eldestObserverState Was first added observer,newestObserverState Is the latest addition observer
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
// Because we guarantee the head of the team state >= Of the following elements state, So just judge the head and tail
// If the newest and oldest Observer When the state of is inconsistent or the current state is inconsistent with the latest state , Then state synchronization is required
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
}
sync() The main function of is to put mObserverMap The states of all elements in the are synchronized to mState. Let's continue to look at the rest backwardPass/forwardPass:
public class LifecycleRegistry extends Lifecycle {
// This comment should be the most difficult to understand in the whole class , At least for me
// we have to keep it for cases:
// void onStart() {
// // removeObserver(this), explain this It's a LifecycleObserver
// // So this is about , We perform the following two operations in the callback
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// Suppose now we want to start from CREATED go to STARTED state ( in other words ,mState Now it is STARTED).
// In this case , Only the new observer Set to CREATED state , its onStart Will be called
// In order to get this CREATED, It's only here that mParentStates. stay forwardPass In the implementation of
// pushParentState(observer.mState) when ,observer.mState That's what we need CREATED.
// backwardPass The situation is similar .
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
private ArrayList<State> mParentStates = new ArrayList<>();
// first while Cycle through our set of stored observers ,
// The second is to deal with the process of each state event
private void forwardPass(LifecycleOwner lifecycleOwner) {
// Start iterating from the head of the team
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
// Maybe when calling back the customer code , The customer removed himself
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//upEvent Return to the experience event
// for example : Now it's STARTED , So what happened to him events Namely ON_RESUME
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
// Start iteration at the end of the team
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();
}
}
}
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
private void pushParentState(State state) {
mParentStates.add(state);
}
}
Tips : Looking at this forwardPass as well as backwardPass These two methods , Refer to the state transition diagram above
- Assume that all in the current set
ObserverWithState
All elements are inCREATED
state . Then a message was receivedON_START
event , As can be seen from the figure , The next step should be to switch toSTARTED
state . becauseSTARTED
Greater thanCREATED
, So it will executeforwardPass
Method .forwardPass
Call insideupEvent(observer.mState)
, Return fromCREATED
Up toSTARTED
Events to send , That is to sayON_START
, thereforeON_START
The event is sent to the observer . - Assuming the current
LifecycleRegistry
OfmState
be inRESUMED
state . And then calladdObserver
Method to add a newLifecycleObserver
, The observer Will be encapsulated asObserverWithState
Save into collection , This newObserverWithState
be inINITIALIZED
state , becauseRESUMED
Greater thanINITIALIZED
, So will performforwardPass
Method .ObserverWithState
Of The status will follow**INITIALIZED -> CREATED -> STARTED -> RESUMED**
Such sequential changes .
summary
Some personal questions :
- Doubtful point 1: Why not SupportActivity In the life cycle function of Lifecycle Distribute lifecycle Events , But to add one Fragment Well ?
Because not all pages inherit AppCompatActivity, For compatibility with non AppCompatActivity, So encapsulate a with the same life cycle Fragment Here it is Lifecycle Distribute lifecycle Events . obviously Fragment Less invasive .
- Doubtful point 2: Why ReportFragment Distribute the lifecycle without using it directly ActivityLifecycleCallbacks Callback to handle Lifecycle Life cycle change ?
because ActivityLifecycleCallbacks Callback ratio of Fragment and Activity It's still early , In fact, the corresponding life cycle method is not actually implemented
Lifecycle Let's stop here , Finally, a flow chart is attached , Help understand and remember :