Series of articles look here

Android Jetpack Architecture Components — What is Jetpack?

Android Jetpack architecture component — Lifecycle usage

Android Jetpack Architecture component — Lifecycle Principles

Android Jetpack Architecture Components – This article takes you through the ViewModel and how it works

Android Jetpack architecture component – LiveData Usage

Android Jetpack Architecture component – LiveData Principles

An overview of the

Lifecycle is a class that holds the Lifecycle state of a component and allows other components to observe changes in the Lifecycle. Not limited to activities or fragments. We only know that the lifecycle is managed by the code running in the operating system or process. And life cycles are at the heart of how Android works, so apps must follow them. Otherwise, it causes OOM or Crash.

Why use Lifecycle to manage the Lifecycle

Here we use an example provided on the official website:

 internal class MyLocationListener(
        private val context: Context,
        private val callback: (Location) -> Unit
) {

    fun start() {
        // connect to system location service
    }

    fun stop() {
        // disconnect from system location service
    }
}

class MyActivity : AppCompatActivity() {
    private lateinit var myLocationListener: MyLocationListener

    override fun onCreate(...) {
        myLocationListener = MyLocationListener(this) { location ->
            // update UI
        }
    }

    public override fun onStart() {
        super.onStart()
        myLocationListener.start()
        // manage other components that need to respond
        // to the activity lifecycle
    }

    public override fun onStop() {
        super.onStop()
        myLocationListener.stop()
        // manage other components that need to respond
        // to the activity lifecycle
    }
}
Copy the code

Logically this code is fine, but in a real-world application scenario we would need to manage many components and calls to the current page in response to the current lifecycle state. This leads us to store a lot of code in onStop and onStart, which makes it difficult to maintain.

Lifecycle is designed to help us solve these problems in a resilient and isolated way.

How to use Lifecycle

Lifecycle depend on

If lifecycle is required, Google’s Maven repository will need to be added to the project. Add the following to build. Gradle:

allprojects {
    repositories {
        google()
    }
}
Copy the code

Add the following dependencies to build. Gradle in your project directory:

Dependencies {def lifecycle_version = "2.2.0" def arch_version = "2.1.0 "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" // LiveData implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" // Lifecycles only (without ViewModel or LiveData) implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" // Saved state module for ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version" // Annotation processor kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // alternately - if using Java8, use the following instead of lifecycle-compiler implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" // optional - helpers for implementing LifecycleOwner in a Service implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version" // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version" // optional - ReactiveStreams support for LiveData implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version" // optional - Test helpers for LiveData testImplementation "androidx.arch.core:core-testing:$arch_version" }Copy the code

Method of use

  • The lifecycle owner uses getLifecycle() or an instance, and then adds an observer via addObserver.
  • The observer implements the LifecycleObserver interface and follows the corresponding lifecycle by using the OnLifecycleEvent annotation.

Use the sample

We’ll still use the official example here:

class MyObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(MyObserver())
Copy the code

First MyObserver implements the LifecycleObserver interface and imposes lifecycle constraints on methods using ON_RESUME and ON_PAUSE annotations. The owner then makes the call directly by adding an observer.

Implement custom LifecycleOwner

Fragments and Activities in 26.1.0 and later already implement the LifecycleOwner interface by default. If you need a custom class and want it to be LifecycleOwner. You can use LifecycleRegistry. Example code is as follows:

class MyActivity : Activity(), LifecycleOwner {

    private lateinit var lifecycleRegistry: LifecycleRegistry

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleRegistry = LifecycleRegistry(this)
        lifecycleRegistry.markState(Lifecycle.State.CREATED)
    }

    public override fun onStart() {
        super.onStart()
        lifecycleRegistry.markState(Lifecycle.State.STARTED)
    }

    override fun getLifecycle(): Lifecycle {
        return lifecycleRegistry
    }
}
Copy the code

The various states of Lifecycle are set through makeState and the instance is returned through getLifecycle.

In actual combat

Lifecycle simply does a listen on the front and back of the application. Let’s look at how we listen to the front and back of the application before lifecycle is used.

/** * @date:2020/12/30 * @author:Silence * @describe: **/ open class BaseActivityLifecycleCallback : Application.ActivityLifecycleCallbacks { private var currentResumedActivity: WeakReference<Activity>? Private var Listener: OnAppStatusListener? = null / / open the Activity quantity statistics private var activityStartCount = 0 fun registerAppStatusListener (listener: OnAppStatusListener) { this.listener = listener } override fun onActivityPaused(activity: Activity) { currentResumedActivity == null } override fun onActivityStarted(activity: Activity) { activityStartCount++ if (activityStartCount == 1) { listener? .onAppFront() } } override fun onActivityDestroyed(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) = Unit override fun onActivityStopped(activity: Activity) { activityStartCount-- if (activityStartCount == 0) { listener? .onAppBackground() } } override fun onActivityCreated(activity: Activity, bundle: Bundle?) = Unit override fun onActivityResumed(activity: Activity) { currentResumedActivity = WeakReference(activity) } fun getCurrentActivity(): Activity? { return currentResumedActivity? .get() } }Copy the code

Does the code feel a little cumbersome? You need to count the activity to determine whether the application is in the foreground or background. So what will happen if we pass Lifecycle? Let’s take a look:

/**
 * @date:2021/02/08
 * @author:Silence
 * @describe:
 **/
class AppLifeObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onForeground() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onBackground() {
    }
}
Copy the code

Then we call the following code directly from application:

ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifeObserver())
Copy the code

Is it much simpler than the previous counting method? And implementation through Lifecycle will be relatively more readable.

conclusion

In this article we have taken a brief look at the use of Lifecycle and a simple example of listening on the app foreground by trying to use lifecycle. Lifecycle can be found to be simple to use. However, lifecycle is not covered. Because you don’t want to know how it works unless you know how to use it. So in the next article we will look at the implementation of Lifecycle.

reference

The official documentation

This article was first published on my personal blog: Android Jetpack Architectural Components — Lifecycle Usage

For more articles, please pay attention to my official number:Code the farmers work