This is the third day of my participation in the First Challenge 2022.

0x1 Lifecycle introduction

This section continues with Jetpack, with a second component Lifecycle that helps developers manage the Lifecycle of activities, fragments, and components such as LiveData, ViewModel, etc.

These are some of the most common problems encountered in daily development:

  • Specific actions need to be performed in Activity and Fragment lifecycle callbacks to cause errors or memory leaks, such as forgetting to cancel an infinite loop property animation in onDestory, forgetting to unregister an Eventbus in onDestory, etc. Don’t try to be careful, in a collaborative setting, especially a collaborative setting;
  • A common solution: write a base class that overrides the lifecycle callback methods and dumps the action code into each method to avoid perceived oversight. Yes, but as a result, the base class is bloated and hard to maintain, and some subclasses are forced to inherit a bunch of unnecessary operations;
  • There may be unexpected life cycle situations, such as an asynchronous callback in onCreate(), but because the callback takes time, by the time the callback is already in onStop(), the operation in the callback may not be meaningful, so you need to get the current life cycle state.
  • A conventional solution is to define an additional sentinel value, modify it in the lifecycle callback method, and the asynchronous callback will perform operations based on this value.

Lifecycle is there to help developers solve these problems:

Isolate component lifecycle status information for unified management and allow other objects to observe.


0x2 Lifecycle is used

Tips: Part taken from official document: Handling the Lifecycle with Lifecycle Aware Components

① Dependency introduction

/ / not Androidx implementation"Android. Arch. Lifecycle: extensions: 1.1.1"

// Androidx
implementation 'androidx. Appcompat: appcompat: 1.4.1'
Copy the code

Simply rely on an AppCompat and open the External Libraries on the left to see the Libraries associated with Lifecycle:

Type gradlew :app:dependencies. Lifecycle depends on lifecycle

It can be used without additional dependency configuration, but it can be used separately if the library version is required, or if extension classes are used in special cases, such as:

// annotationProcessor"Androidx. Lifecycle: lifecycle - compiler: 2.3.1." "Java 8 supports DefaultLifecycleObserver implementation"Androidx. Lifecycle: lifecycle - common - java8:2.3.1." "// LifecycleOwner implementation for Service"Androidx. Lifecycle: lifecycle - service: 2.3.1." "ProcessLifecycleOwner provides a lifecycle implementation for the entire app process"Androidx. Lifecycle: lifecycle - process: 2.3.1." "

// ReactiveStreams support for LiveData
implementation "Androidx. Lifecycle: lifecycle - reactivestreams: 2.3.1." "
Copy the code

The repository version number and its dependent libraries can be found by entering the package name in MVNRepository:

Tips: If Lifecycle is solely intended to be used, Lifecycle – Runtime should be introduced, but this will be used with LiveData and ViewModel.


② Basic use

  • Custom observer → Observer implements DefaultLifecycleObserver interface and rewrites corresponding methods to monitor component life cycle;
  • Component add observer → getLifecycle() getLifecycle instance, call addObserve()

Tips: LifecycleObserver implements LifecycleObserver with OnLifecycleEvent annotations to add lifecycle methods, but this has been deprecated. The documentation notes suggest using DefaultLifecycleObserver or LifecycleEventObserver.

The following is an example of the code used:

The running results are as follows:

Instead of having to rewrite a bunch of lifecycle callback methods in an Activity, just adding an observer changes from inheritance to composition, and the code simplification effect is not trivial.

You may not know how wonderful this is, But As Yung explains, think about it:

There are now ten libraries that perform operations in their life cycle. As originally written, you would have to rewrite the Activity life cycle callback to fill in the code calls that correspond to the library. Congratulations, this class has suddenly become long and smelly.

Make it more difficult?

Libraries have different lifecycle callbacks, for example: LIBRARY A only focuses onCreate() and onDestory(), library B only focuses onDestory(), library C only focuses onStop, etc. When it comes to removing, adding, or modifying a library, you have to be careful, because a careless change can cost you precious time on low-level bugs like this.

What about Lifecycle? It does that for us: separation of concerns

Each library defines an observer in which to override life cycle callbacks as needed, such as Activity mindless addObserve(). Isolate long, smelly code into a separate class. Change the words directly change the corresponding class, do not worry about affecting other libraries, add, delete and change libraries without pressure, wonderful ah!


③ Event & State

The official documentation shows this:

For those of you who are a little confused, change the upper case of Event to lower case, for example ON_CREATE → onCreate(), which is the lifecycle callback, and State is the lifecycle State that you’re in, and sometimes we need to get the current State of the lifecycle component, and that’s how we do it, The two are used together.

Reading:

  • Lifecycle.state. CREATED → after onCreate(), onStop();
  • Lifecycle.State.STARTED → Call onStart(), onPause();
  • Lifecycle.state.RESUMED → after onResume();
  • Lifecycle. State. He DESTROYED – callback onDestroy ();

Tips: judge life cycle State example: if (lifecycleOwner. Lifecycle. The currentState. IsAtLeast (lifecycle. State. STARTED)


④ Customize LifecycleOwner

LifecycleOwner is implemented by default in Fragments and Activities of AppCompat 26.1.0 and later, and is generally not required to be customized. If you want to implement a life-cycle-aware component yourself, you can start. Let’s start with the next three core classes:

  • LifecycleOwner → with Lifecycle;
  • LifecycleObserver → Listen for lifecycle events;
  • LifecycleRegistry → forwarding lifecycle events, custom LifecycleOwner will be used;

Lifecycle is an optional library called Lifecycle -process

It provides a ProcessLifecycleOwner for the entire App process and, with a few simple lines of code, listens to the App switch between front and back.

Dependency introduction:

Implementation "androidx. Lifecycle: lifecycle - process: 2.4.0." "Copy the code

The test code is as follows, showing the Application class:

Then there is the Activity called:

Run to see the effect:

Easy to use, no problem, easy to listen to the application before and after switching, and then pull down this library is how to achieve:

Can be very simple, just four files, first class initialization ProcessLifecycleInitializer:

Use the ContentProvider to retrieve the App Context and initialize it. Use the other component StartUp, which will be described later

Follow LifecycleDispatcher → init()

RegisterActivityLifecycleCallbacks () is to provide a method of Application, can monitor all the Activity within the App lifecycle. OnActivityCreated () was only rewritten to Hook the host lifecycle via ReportFragment.

ProcessLifecycleOwner → init() → attach()

OnStart () and onResume() are in the correct order.

MDelayedPauseRunnable:

Delay 700ms, then go to verify whether it is in the background, then LifecycleRegistry forwards the lifecycle event, and the end. Simple point is that encapsulates the Application ActivityLifecycleCallbacks, and provides a global LifecycleOwner.


0 x3, summary

Lifecycle → Lifecycle → Lifecycle → Jetpack (Http://jetpack) Lifecycle → Lifecycle → Jetpack (http://jetpack

Tips: For changes to the Lifecycle library see Lifecycle, as well as other libraries


References:

  • Use ProcessLifecycle to elegantly listen to app transitions

  • Jetpack AAC will Lifecycle Lifecycle!