How do I listen for the life cycle
The Androidx.lifecycle package provides classes and interfaces that you can use to build life-cycle-aware components. To use Lifecycle requires declaring a dependency:
Implementation "androidx. Lifecycle: lifecycle - runtime - KTX: $lifecycle_version"Copy the code
Listen for the Activity lifecycle
Listening to the Activity lifecycle is very simple:
- Implement the lifecycle observer interface
- Register a lifecycle observer
Create a custom lifecycle observer:
class CustomObserver(val level: String): LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.e("lifecycle", "${level}_onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.e("lifecycle", "${level}_onDestroy")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.e("lifecycle", "${level}_onResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.e("lifecycle", "${level}_onPause")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.e("lifecycle", "${level}_onStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.e("lifecycle", "${level}_onStop")
}
}
Copy the code
Register a lifecycle observer
lifecycle.addObserver(CustomObserver("activity"))
Copy the code
Listen for the Fragment life cycle
Listening for the Fragment life cycle is the same as listening for an Activity.
Listen for the Application lifecycle
Listening to the Application lifecycle first requires support from other packages:
Implementation "androidx. Lifecycle: lifecycle - process: $lifecycle_version"Copy the code
Then do the same:
- Implement the lifecycle observer interface
- Register a lifecycle observer
But the difference is that you register it through ProcessLifecycleOwner.
ProcessLifecycleOwner.get().lifecycle.addObserver(CustomObserver("app"))
Copy the code
The life cycle listens for parsing
There are two important classes in the Lifecycle package that listen for the lifecycle:
ReportFragment
: listeningActivity
Life cycle ofLifecycleRegistry
: Registers to listen to and distribute life cycle events
Listen to the Activity lifecycle principle
The principle of listening for an Activity’s declaration cycle is simple: we know that when fragments are added to an Activity their life cycle is bound. The lifecycle functions are called in the following order:
-Fragment: onCreate
-Fragment: onCreateView
-Fragment: onViewCreated
-Activity: onCreate
-Fragment: onActivityCreated
-Activity: onStart
-Fragment: onStart
-Activity: onResume
-Fragment: onResume
-Fragment: onPause
-Activity: onPause
-Fragment: onStop
-Activity: onStop
-Fragment: onDestroyView
-Fragment: onDestroy
-Fragment: onDetach
-Activity: onDestroy
Copy the code
By listening for the Fragment life cycle added to the Activity, you are listening for the Activity life cycle.
One such ReportFragment has been added to ComponentActivity.
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
Copy the code
Go to the ReportFragment class and remove some code:
public class ReportFragment extends Fragment { private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle" + ".LifecycleDispatcher.report_fragment_tag"; public static void injectIfNeededIn(Activity activity) { if (Build.VERSION.SDK_INT >= 29) { activity.registerActivityLifecycleCallbacks( new LifecycleCallbacks()); } 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(); } } @SuppressWarnings("deprecation") 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); } } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); dispatch(Lifecycle.Event.ON_CREATE); } @Override public void onStart() { super.onStart(); dispatch(Lifecycle.Event.ON_START); } @Override public void onResume() { super.onResume(); 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); } private void dispatch(@NonNull Lifecycle.Event event) { if (Build.VERSION.SDK_INT < 29) { dispatch(getActivity(), event); } } static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityPostCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { dispatch(activity, Lifecycle.Event.ON_CREATE); } @Override public void onActivityPostStarted(@NonNull Activity activity) { dispatch(activity, Lifecycle.Event.ON_START); } @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 onActivityPreStopped(@NonNull Activity activity) { dispatch(activity, Lifecycle.Event.ON_STOP); } @Override public void onActivityPreDestroyed(@NonNull Activity activity) { dispatch(activity, Lifecycle.Event.ON_DESTROY); }}}Copy the code
ReportFragment life cycle changes call LifecycleRegistry. HandleLifecycleEvent () method to inform LifecycleRegistry change state, LifecycleRegistry internal call moveToState () change state, and call each LifecycleObserver. OnStateChange () method to change notification life cycle. As you can see, SupportActivity adds a ReportFragment with no page. In the ReportFragment lifecycle function, Call the LifecycleRegistry. HandleLifecycleEvent () method to distribute life cycle events.
This serves the purpose of listening for the Activity lifecycle.
Principle of monitoring the Fragment life cycle
See androidx. Fragments. App. Fragments of code,
void performStart() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
void performResume() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
Copy the code
. These functions are called directly in the LifecycleRegistry handleLifecycleEvent notification state changes, to see who is calling these methods can see is FramentManager moveToState () function
void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive)
Copy the code
The moveToState() function calls and fragments each lifecycle node.
Listen for the Applicationn lifecycle principle
In the lifecycle – process package defines a ProcessLifecycleOwnerInitializer ContentProvider, it is in the AndroidManifest. Registered in the XML.
<provider
android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="com.jide.jetpack.lifecycle-process"
android:exported="false"
android:multiprocess="true" />
Copy the code
The file address is as follows:
app/build/intermediates/bundle_manifest/debug/processDebugManifest/bundle-manifest/AndroidManifest.xml
Copy the code
In the ProcessLifecycleOwnerInitializer LifecycleDispatcher, ProcessLifecycleOwner initialization.
The ProcessLifecycleOwner annotation is described as follows:
ProcessLifecycleOwner listens for the entire application declaration cycle and calls the lifecycle as follows:
Lifecycle.Event.ON_CREATE
Is called only once.Lifecycle.Event.ON_DESTROY
Will not be called.Lifecycle. Event. ON_START, Lifecycle. Event. ON_RESUME
In the firstActivity
Called when added.Lifecycle. Event. ON_PAUSE, Lifecycle. Event. ON_STOP
In the last oneActivity
Called when removed.
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ProcessLifecycleOwnerInitializer extends ContentProvider { @Override public boolean onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; }}Copy the code
The code in ProcessLifecycleOwner is simpler and won’t be posted.