Android開發Jetpack組件Lifecycle使用篇

1.為什麼需要Lifecycle

在應用開發中,處理Activity或者Fragment組件的生命周期相關代碼是必不可免的; 官方文檔中舉瞭一個例子,這裡簡化一下,在Activity中寫一個監聽,在Activity的不同生命周期方法中調用這個監聽

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() {
    ...
    }
}

再舉個MVP中常見的情況,如下所示。

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() {
    ...
    }
}

這兩個例子的寫法已經很普遍瞭,實現起來也不難; 但實際開發中,可能會有多個組件在Activity的生命周期中進行回調; 這樣Activity的生命周期的方法中可能就需要放大量的代碼,這就使得它們難以維護

還有一個問題是,如果我們在組件中做瞭耗時操作(比如在onStart方法),這種寫法就無法保證組件在Activity或者Fragment停止之前完成啟動

因此我們需要一個能管理Activity和Fragment的生命周期的庫,這個庫就是Lifecycle

2.如何使用Lifecycle

分別來介紹下依賴Lifecycle庫和Lifecycle基本用法

2.1 依賴Lifecycle庫

官網給出的依賴代碼如下所示:

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"
}

官網用的是AndroidX,因為使用AndroidX,可能會產生一些遷移的問題,這裡的舉例就不使用AndroidX,而是使用lifecycleandroid.arch.lifecycle庫,如下所示。

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"
}

實際上我們不需要全部把這些代碼全寫進build.gralde進去(當然全寫進去也不會有什麼錯),因為Gradle默認是支持依賴傳遞的, 我們直接添加如下依賴就可以滿足日常的工作,如果缺少哪個庫,再去單獨添加就好瞭。

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

添加這一句代碼就依賴瞭如下的庫。

2.2 Lifecycle基本用法

先不談Activity和Fragment中如何使用,先舉一個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類,它實現瞭LifecycleObserver接口,說明MyObserver成為瞭一個Lifecycle的觀察者。 然後在註釋1處將MyObserver添加到LifecycleOwner中。LifecycleOwner是一個接口,其內部隻有一個方法getLifecycle(),getLifecycle方法用於獲取Lifecycle,這樣就可以將MyObserver添加到Lifecycle中,當Lifecycle的生命周期發生變化時,MyObserver就會觀察到,或者說是感知到。

如果使用是Java8 ,那麼可以使用DefaultLifecycleObserver來替代LifecycleObserver:

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

除此之外,不要忘瞭在build.gradle添加 "androidx.lifecycle:common-java8:<version>"

3.Lifecycle應用舉例

應用舉例準備兩個示例,一個是在Activity中使用,一個是在第一小節的MVP例子上進行改進。

3.1 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(){
            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");
    }
}

先實現MyObserver,對ON_CREATE和ON_RESUME事件進行監聽。因為在Android Support Library 26.1.0 及其之後的版本,Activity和Fragment已經默認實現瞭LifecycleOwner接口,所以在註釋1處可以直接使用getLifecycle方法獲取Lifecycle對象,這樣MyObserver就可以觀察MainActivity的生命周期變化瞭

LifecycleOwner可以理解為被觀察者,MainActivity默認實現瞭LifecycleOwner接口,也就是說MainActivity是被觀察者

運行程序,打印的log如下所示

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

隻要在MainActivity的onCreate方法中添加MyObserver,那麼MyObserver就可以觀察到MainActivity的各個生命周期的變化

3.2 MVP中使用

改寫第一小節MVP的例子,先實現MyPresenter,如下所示

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接口繼承自LifecycleObserver接口,MyPresenter又實現瞭IPresenter接口,這樣MyPresenter成為瞭一個觀察者。 接在在MainActivity中加入MyPresenter:

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成為瞭被觀察者,當它的生命周期發生變化時,MyPresenter就可以觀察到,這樣就不需要在MainActivity的多個生命周期方法中調用MyPresenter的方法瞭

打印的日志如下:

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

4.自定義LifecycleOwner

如果想實現自定義LifecycleOwner,可以使用LifecycleRegistry,它是Lifecycle的實現類。Android Support Library 26.1.0及其之後的版本,Activity和Fragment已經默認實現瞭LifecycleOwner接口,因此我們可以這麼寫:

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;
    }
}

通過新建LifecycleRegistry,為LifecycleRegistry設置Lifecycle的各種狀態,並通過getLifecycle方法返回該LifecycleRegistry。

到此這篇關於Android開發Jetpack組件Lifecycle使用介紹上篇的文章就介紹到這瞭,更多相關Android Jetpack組件Lifecycle內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: