Android Jetpack architecture component - Lifecycle in pit Guide

This article starts with WeChat public's "Android development tour". Welcome to pay more attention to get more dry goods.

Background introduction

In the previous article, we mainly introduced the origin of Jetpack and the component library contained in each of the four components. In this article, we will learn about lifecycle components in architecture components in the future. Lifecycle components help us manage the life cycle of activities and fragments. That is to say, when the life cycle of activities or fragments sends changes, we can be notified. We usually call various methods in the lifecycle method, or initialize some components or invoke some callbacks in a life cycle, which leads to relatively bloated, highly coupled and unmaintainable life cycle related methods.

Let me take a look at the callback example given in the official document:

class MyLocationListener {
    public MyLocationListener(Context context, Callback callback) {
        // ...
    }

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

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

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    @Override
    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, (location) -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        myLocationListener.start();
        // manage other components that need to respond
        // to the activity lifecycle
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
        // manage other components that need to respond
        // to the activity lifecycle
    }
}

These codes look good even we usually do, but I call the management UI and other components too much in response to the current state of the life cycle, which will write a lot of code in the life cycle methods, such as onStart() and onStop(), which will make the code difficult to maintain.

For all these reasons, Lifecycle is officially launched.

Introduction to Lifecycle

Lifecycle management lifecycle is also observer mode, which mainly involves the following categories: lifecycle observer, lifecycle owner, lifecycle, State, Event.

  • Lifecycle Observer: lifecycle observer. We need a custom class to implement LifecycleObserver, which can observe the life cycle method through annotation.
  • Lifecycle owner: lifecycle owner. Let the Activity or fragment implement the interface. When the lifecycle changes, the event will be received by the lifecycle observer.
  • Lifecycle: lifecycle abstract class. Hold add and remove listening methods. Define State and Event enumerations.
  • Lifecycle registry: the implementation class of lifecycle.
  • State: the state of the current lifecycle. Lifecycle corresponds the life cycle function of an Activity to state
  • Event: the event corresponding to the change of the current life cycle. The State change triggers the event event, which is received and processed by the registered observer lifecycle observer.

Event enumeration:

 public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }

State enumeration:

public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }

Correspondence between State and Event:

Lifecycle usage

If the project has been migrated to Android x, there is no need for additional packages, because Android x already contains Jetpack related components. If there is no migration, configure the following in build.gradle:

dependencies {
​    def lifecycle_version = "1.1.1"
​
    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    // alternatively - just ViewModel // For Kotlin use viewmodel-ktx
    implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" 
    // alternatively - just LiveData
    implementation "android.arch.lifecycle:livedata:$lifecycle_version"
    // alternatively - Lifecycles only (no ViewModel or LiveData).
    // Support library depends on this lightweight import
    implementation "android.arch.lifecycle:runtime:$lifecycle_version"
    // For Kotlin use kapt instead of annotationProcessor
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" 
    // alternately - if using Java8, use the following instead of compiler
    implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
    // optional - ReactiveStreams support for LiveData
    implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
    // optional - Test helpers for LiveData
    testImplementation "android.arch.core:core-testing:$lifecycle_version"

After the configuration is completed, we define a class to implement LifecycleObserver:

class MyObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connectListener() {
        Log.e("MyObserver","==ON_RESUME==")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun disconnectListener() {
        Log.e("MyObserver","==ON_PAUSE==")

    }
}

The accept Event is completed by annotating the onlife Event, and the parameter is the Event enumeration in the above.

Next, we add the observer to the Activity:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        lifecycle.addObserver(MyObserver())

    }
}

This is the simplest use. At this time, we can actually monitor the life cycle changes of activities.

com.jetpack.jetpackdemo E/MyObserver: ==ON_RESUME==
com.jetpack.jetpackdemo E/MyObserver: ==ON_PAUSE==

Is there a question about using it like this? We registered the Event event in the Observer, but we did not specify the State in the life cycle method of the Activity. How does this relate? In Android Support Library 26.1.0 and later, Activity and Fragment have implemented the lifecycle owner interface by default, so we don't need to reset it.

Custom Lifecycle

When some of our classes don't implement AppCompatActivity, we also want to use Lifecycle, so we need to customize it, that is, we need to implement it ourselves
Lifecycle owner interface. The MyObserver class remains unchanged, and the MainActivity class changes as follows:

class MainActivity : Activity(), LifecycleOwner {

    private lateinit var lifecycleRegistry: LifecycleRegistry

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifecycleRegistry = LifecycleRegistry(this)
        lifecycle.addObserver(MyObserver())

    }

    override fun onResume() {
        super.onResume()
        lifecycleRegistry.currentState = Lifecycle.State.RESUMED
    }

    override fun onPause() {
        super.onPause()
        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
    }

    override fun getLifecycle(): Lifecycle {
        return lifecycleRegistry
    }
}

This means that all the settings must be done by ourselves. The printing result is the same, as follows:

com.jetpack.jetpackdemo E/MyObserver: ==ON_RESUME==
com.jetpack.jetpackdemo E/MyObserver: ==ON_PAUSE==

summary

This article mainly introduces the API related to Lifecycle and its simple use. In a real project, you still need to use ViewModel and LiveData together. Get the required data through the ViewModel, and reflect the data changes into the view by observing the LiveData object. In the following articles, we will continue to introduce the use of ViewModel and LiveData.

Recommended reading

Don't know what Android Jetpack is yet? You are out.

Scan below the two-dimensional code to pay attention to the public number and get more dry goods.

Keywords: Android Fragment Gradle

Added by st89 on Wed, 20 Nov 2019 11:21:31 +0200