This article was first published on the wechat public account “Houchangcun Mannong”

preface

Lifecycle is a component of the Android Jetpack architecture that helps developers manage the Lifecycle of activities and fragments. Since Lifecycle is the foundation of Both LiveData and ViewModel, you need to learn it first.

1. Why Lifecycle is needed

In application development, code related to the life cycle of an Activity or Fragment component is a must. For example, write a listener in the Activity and call this listener in the Activity’s different life cycle methods.

public class MainActivity extends AppCompatActivity {
    private MyListener myListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myListener = new MyListener(MainActivity.this);
    }

    @Override
    protected void onStart(a) {
        super.onStart();
        myListener.start();
    }

    @Override
    protected void onStop(a) {
        super.onStop(); myListener.stop(); }}class MyListener {
    public MyListener(Context context) {... }void start(a) {... }void stop(a) {... }}Copy the code

Here’s another common MVP situation, as follows.

public class MainActivity extends AppCompatActivity {
    private MyPresenter myPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myPresenter = new MyPresenter();
    }

    @Override
    protected void onResume(a) {
        super.onResume();
        myPresenter.onResume();
    }

    @Override
    protected void onPause(a) {
        super.onPause(); myPresenter.onPause(); }}class MyPresenter{
    void onResume(a) {... }void onPause(a) {... }}Copy the code

Both examples are fairly common to write and not difficult to implement, but in practice, multiple components that call back during the Activity lifecycle may require a lot of code in the Activity lifecycle methods, making them difficult to maintain. Another problem is that if we do time-consuming operations in the component (such as in the onStart method), this writing does not guarantee that the component will start before the Activity or Fragment stops. So we need a library that can manage the life cycles of activities and fragments, and that library is Lifecycle.

How can Lifecycle be used

Lifecycle library and Lifecycle basic usage will be described separately.

2.1 Relies on the Lifecycle library

The dependency code on the official website is as follows:

dependencies {
    def lifecycle_version = "2.0.0"

    // ViewModel and LiveData
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    // alternatively - just ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" // For Kotlin use lifecycle-viewmodel-ktx
    // alternatively - just LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // alternatively - Lifecycles only (no ViewModel or LiveData). Some UI
    // AndroidX libraries use this lightweight import for Lifecycle
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version" // For Kotlin use lifecycle-reactivestreams-ktx

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$lifecycle_version"
}
Copy the code

Website using AndroidX, because use AndroidX, may produce some migration problem, for example, would not use AndroidX here but instead USES lifecycleandroid. Arch. The lifecycle library, as shown below.

dependencies {
    def lifecycle_version = 1.1.1 ""

    // Contains ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    // Only the ViewModel is included
    implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
    // Contain only LiveData
    implementation "android.arch.lifecycle:livedata:$lifecycle_version"
    // Only Lifecycles are included
    implementation "android.arch.lifecycle:runtime:$lifecycle_version"
    
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
    // If Java8 is used instead of compiler
    implementation "android.arch.lifecycle:common-java8:$lifecycle_version"

    // Optional, ReactiveStreams support LiveData
    implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"

    // Optional, LiveData test
    testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
Copy the code

In fact, we don’t need to write all of this code into build.gralde (there’s nothing wrong with writing it all in), because Gradle supports dependency passing by default. We can simply add the following dependencies for daily work, and if a library is missing, we can add it separately.

implementation "Android. Arch. Lifecycle: extensions: 1.1.1"
Copy the code

Adding this line of code relies on the following library.

Lifecycle is essential

Leaving aside how activities and fragments are used, Lifecycle is a simple example.

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener(a) {... }@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener(a) {... } } myLifecycleOwner.getLifecycle().addObserver(new MyObserver());/ / 1
Copy the code

Create a new MyObserver class that implements the LifecycleObserver interface, indicating that MyObserver becomes a Lifecycle observer. Then add MyObserver to LifecycleOwner at comment 1. LifecycleOwner is an interface that has only one method inside it, getLifecycle(), which is used to getLifecycle so that MyObserver can be added to Lifecycle, MyObserver will observe, or perceive, as Lifecycle’s Lifecycle changes.

If Java8 is used, then DefaultLifecycleObserver can be used instead of LifecycleObserver:

class MyObserver implements DefaultLifecycleObserver {
     @Override
     public void onCreate(LifecycleOwner owner) {... }}Copy the code

. In addition, don’t forget to build gradle add “androidx. Lifecycle: common – java8: < version >”

Lifecycle application examples

Prepare two examples, one for use in activities and one for improvement on the MVP example in section 1.

3.1 Used in Activity

package com.example.lifecycledemo1;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLifecycle().addObserver(new MyObserver());/ / 1
    }

    public class MyObserver implements LifecycleObserver{

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        void onResume(a){
            Log.d(TAG, "Lifecycle call onResume");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        void onPause(a){
            Log.d(TAG, "Lifecycle call onPause"); }}@Override
    protected void onResume(a) {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause(a) {
        super.onPause();
        Log.d(TAG, "onPause"); }}Copy the code

Implement MyObserver to listen for ON_CREATE and ON_RESUME events. Since the LifecycleOwner interface is implemented by default for activities and fragments in Android Support Library 26.1.0 and later, Lifecycle can be obtained directly by using the getLifecycle method in comment 1. MyObserver will be able to observe the Lifecycle of the MainActivity. LifecycleOwner can be understood as being observed. The MainActivity implements the LifecycleOwner interface by default, which means that the MainActivity is observed. Run the program and print the log shown below.

D/MainActivity: onResume
D/MainActivity: Lifecycle call onResume
D/MainActivity: Lifecycle call onPause
D/MainActivity: onPause
Copy the code

By adding MyObserver to the onCreate method of the MainActivity, MyObserver can observe changes in the life cycle of the MainActivity.

3.2 Used in MVP

To rewrite the MVP example in section 1, implement MyPresenter first, as shown below.

public class MyPresenter implements IPresenter {
    private static final String TAG = "test";

    @Override
    public void onResume(a) {
        Log.d(TAG, "Lifecycle call onResume");
    }

    @Override
    public void onPause(a) {
        Log.d(TAG, "Lifecycle call onPause"); }}interface IPresenter extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(a);

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(a);
}
Copy the code

The IPresenter interface inherits from the LifecycleObserver interface, and MyPresenter implements the IPresenter interface so that MyPresenter becomes an observer. Add MyPresenter to MainActivity:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "test";
    private IPresenter mPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPresenter = new MyPresenter();
        getLifecycle().addObserver(mPresenter);
    }

    @Override
    protected void onResume(a) {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause(a) {
        super.onPause();
        Log.d(TAG, "onPause"); }}Copy the code

MainActivity becomes observed, and MyPresenter can observe when its life cycle changes, eliminating the need to call MyPresenter’s methods in multiple MainActivity life cycle methods. The following logs are displayed:

D/test: onResume
D/test: Lifecycle call onResume
D/test: Lifecycle call onPause
D/test: onPause
Copy the code

4. Customize LifecycleOwner

If you want to implement a custom LifecycleOwner, you can use LifecycleRegistry, which is an implementation class for Lifecycle. Android Support Library 26.1.0 and later, activities and Fragments already implement the LifecycleOwner interface by default, so we can write:

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleRegistry;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MyActivity extends AppCompatActivity {
    private LifecycleRegistry lifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

    @Override
    public void onStart(a) {
        super.onStart();
        lifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle(a) {
        returnlifecycleRegistry; }}Copy the code

Lifecycle is set up for LifecycleRegistry by creating a new LifecycleRegistry and returning that LifecycleRegistry via the getLifecycle method.

conclusion

This article will introduce the basic use of Lifecycle and will provide two small examples to help you understand how Lifecycle can be used in a project. The only difficulty will be the principle behind Lifecycle. In the next article we will look at the principle behind Lifecycle.

For more content, please pay attention to my original knowledge system: liuwangshu.cn/system/


Here not only share big front end, Android, Java and other technologies, but also programmer growth class articles.