AndroidX ComponentActivity implements the LifecycleOwner interface. Subclasses of ComponentActivity override the LifecycleOwner interface method. Lifecycle is the lifecycleRegistry object created in ComponentActivity;
2. Register LifecycleObserver with the lifecycleRegistry object addObserver. When the lifecycle changes, LifecycleObserver onStateChanged is called back, where Lifecycle.Event listens for changes in the current Activity’s Lifecycle
Principle:
Lifecycle will be registered and the observer State will be initialized initial or destroy. The observer and State will be encapsulated into a class as the map value and observer as the key.
2. AddObserver also has a state alignment, later
3. When the host activity or fragment life cycle changes, it will distribute the current life cycle event and convert it to the corresponding mState.
3.1 Compare the state of the earliest observer in the current map. If the value of mState is smaller than the value of state, the current map is traversed by a link in OnResume->onPause->onStop->onDestroy. Update the map state down to the current lifecycle state and call the Observer onStateChange method;
3.2 Compare the state of the last observer in the current map. If the value of mState is greater than the value of state, the current map is traversed by a link in onCreate->onStart->onResume. Update the map’s state up to the current lifecycle state and call the Observer onStateChange method;
3.3 State alignment, for example: when we go to addObserver in the onStop method of the lifecycle, the state added to the map is the inital state. In fact, the current lifecycle is onStop. This corresponds to the Created state. In this case, you need to update the status smaller than Created in the map to the Created state. Because it is a upEvent, the callback event will have onCreate
1. Create a state and save it to map. 2. When the life cycle changes, update the value of state and call back onStateChanged to monitor the life cycle