Android Jetpack architectural components: a text takes you understand Lifecycle (use articles)

Foreword

This article introduce Lifecycle Android Jetpack architecture components, to help developers Lifecycle Management Activity and Fragment life cycle, due to the Lifecycle is the basis LiveData and ViewModel, so you need to learn it.

1. Why Lifecycle

In application development, process lifecycle Code Activity or Fragment assembly is inevitable, the official document cited an example, simplified here, in a written Activity monitoring, call this method at different life cycle of Activity monitor.

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() {
 super.onStart();
 myListener.start();
 }
 @Override
 protected void onStop() {
 super.onStop();
 myListener.stop();
 }
}
class MyListener {
 public MyListener(Context context) {
 ...
 }
 void start() {
 ...
 }
 void stop() {
 ...
 }
}

As another case where a common MVP, as shown below.

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() {
 super.onResume();
 myPresenter.onResume();
 }
 @Override
 protected void onPause() {
 super.onPause();
 myPresenter.onPause();
 }
}
class MyPresenter{
 void onResume() {
 ...
 }
 void onPause() {
 ...
 }
}

These two examples of writing is very common, it is not difficult to implement, but the actual development, there may be multiple components in the Activity lifecycle callbacks, methods such Activity life cycle may need to put a lot of the code, which makes them difficult to maintain. Another problem is that if we do a time-consuming operation in the component (for example, in onStart method), such an approach can not guarantee complete assembly started before the Activity or Fragment stop. So we need a management lifecycle Activity and Fragment library, this library is the Lifecycle.

2. How to use Lifecycle

Respectively, to introduce rely Lifecycle Lifecycle libraries and basic usage.

2.1 Lifecycle dependent libraries

Official website of the dependent code is given 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"
}

The official website using a AndroidX, because the use of AndroidX, may have some mobility problems, for example here is not used AndroidX, but the use of lifecycleandroid.arch.lifecycle library as follows.

dependencies {
 def lifecycle_version = "1.1.1"
 // 包含ViewModel和LiveData
 implementation "android.arch.lifecycle:extensions:$lifecycle_version"
 // 仅仅包含ViewModel
 implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
 // 仅仅包含LiveData
 implementation "android.arch.lifecycle:livedata:$lifecycle_version"
 // 仅仅包含Lifecycles
 implementation "android.arch.lifecycle:runtime:$lifecycle_version"

 annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
 // 如果用Java8, 用于替代compiler
 implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
 // 可选,ReactiveStreams对LiveData的支持
 implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
 // 可选,LiveData的测试
 testImplementation "android.arch.core:core-testing:$lifecycle_version"
}

In fact, we do not need to put all this code into a full written build.gralde (of course, all would not be written into the wrong), because Gradle by default to support dependent on delivery. We add the following directly depend on to meet the daily work, what if the library is missing, go to add a separate fine.

implementation "android.arch.lifecycle:extensions:1.1.1"

Add this one dependent on the following code libraries.

Android Jetpack architectural components: a text takes you understand Lifecycle (use articles)

2.2 Lifecycle basic usage

Putting aside the Activity and Fragment how to use, to cite a simple example Lifecycle.

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

MyObserver create a new class that implements the interface LifecycleObserver, indicating MyObserver become a Lifecycle observer. Note then added at 1 to LifecycleOwner in MyObserver. LifecycleOwner is an interface, which is only one method of internal getLifecycle (), getLifecycle method for acquiring Lifecycle, so may be added to MyObserver Lifecycle when Lifecycle life cycle changes, MyObserver will be observed, or are perceived to.

If you are using a Java8, you can use DefaultLifecycleObserver instead LifecycleObserver:

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

In addition, do not forget to add in build.gradle "androidx.lifecycle: common-java8: <version>"

Application examples 3.Lifecycle

Application examples to prepare two examples, is to use a Activity in a MVP is improved in the example of the first measure.

3.1 Activity in use

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(){
 Log.d(TAG, "Lifecycle call onResume");
 }
 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
 void onPause(){
 Log.d(TAG, "Lifecycle call onPause");
 }
 }
 @Override
 protected void onResume() {
 super.onResume();
 Log.d(TAG, "onResume");
 }
 @Override
 protected void onPause() {
 super.onPause();
 Log.d(TAG, "onPause");
 }
}

First realize MyObserver, for ON_CREATE and ON_RESUME event monitoring. Because Android Support Library version 26.1.0 and later, Activity and Fragment already achieved LifecycleOwner default interface, so you can use in the comment at 1 getLifecycle method to get Lifecycle object directly, so MyObserver MainActivity can observe the life cycle of the change, LifecycleOwner can be understood as an observer, MainActivity default implementation LifecycleOwner interface that is MainActivity is an observer. Running the program, log printed as follows.

D/MainActivity: onResume
D/MainActivity: Lifecycle call onResume
D/MainActivity: Lifecycle call onPause
D/MainActivity: onPause

Just add MyObserver in the onCreate method MainActivity, then MyObserver can be observed changes MainActivity various life cycle.

3.2 MVP in use

Examples of the rewritable first bar MVP, to achieve MyPresenter, as shown below.

public class MyPresenter implements IPresenter {
 private static final String TAG = "test";
 @Override
 public void onResume() {
 Log.d(TAG, "Lifecycle call onResume");
 }
 @Override
 public void onPause() {
 Log.d(TAG, "Lifecycle call onPause");
 }
}
interface IPresenter extends LifecycleObserver {
 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
 void onResume();
 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
 void onPause();
}

IPresenter interface inherits from LifecycleObserver interface MyPresenter but also realized IPresenter interface so MyPresenter become an observer. Then joining MyPresenter in MainActivity in:

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() {
 super.onResume();
 Log.d(TAG, "onResume");
 }
 @Override
 protected void onPause() {
 super.onPause();
 Log.d(TAG, "onPause");
 }
}

MainActivity become the observed, when its life cycle changes, MyPresenter can be observed, so that no method calls in a plurality of lifecycle MyPresenter MainActivity the method. Print log is as follows:

D/test: onResume
D/test: Lifecycle call onResume
D/test: Lifecycle call onPause
D/test: onPause

4. Custom LifecycleOwner

If you want to implement a custom LifecycleOwner, you can use LifecycleRegistry, it is the Lifecycle implementation class. Android Support Library 26.1.0 and later versions, Activity and Fragment already achieved LifecycleOwner default interface, 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() {
 super.onStart();
 lifecycleRegistry.markState(Lifecycle.State.STARTED);
 }
 @NonNull
 @Override
 public Lifecycle getLifecycle() {
 return lifecycleRegistry;
 }
}

By New LifecycleRegistry, the various states is disposed Lifecycle LifecycleRegistry, and returns the LifecycleRegistry by getLifecycle method.

to sum up

This article on the Lifecycle basic usage, and to help you understand digestion by two small examples, specific use in the project is not difficult, the difficulty is still the only principle Lifecycle

At last

Thank you for patience and ability, La miles long-winded reading my article.

We are willing to stick with you in Android development positions of fellow mutual exchange of learning and common progress!

Here I also share a copy of your collection of finishing Android studying architecture PDF + Video + Interview + document source notes , as well as advanced technical architecture Advanced Brain Mapping, Android interview with thematic development, advanced materials advanced architecture to help you enhance Advanced Learning , but also saves everyone time online in search of information to learn, you can also share with close friends studying together

If you have a need, you can thumbs up

Android Jetpack architectural components: a text takes you understand Lifecycle (use articles)

Guess you like

Origin blog.51cto.com/14573572/2446049