Android Jetpack架构组件(二)Lifecycle使用

前言

Lifecycle是生命周期感知组件,可以对Activity或者Fragment的生命周期的状态变化做出响应,帮助开发者写出更好组织的,轻量级的代码,更容易维护。

为什么需要Lifecycle

举个栗子,在应用开发过程中,处理Activity或者Fragment的生命周期不可避免,先看官方文档举的例子,是一段对获取位置的监听代码,分别在onStart()里启动监听和在onStop()里停止监听,代码如下:

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

   fun start(){
       // 连接接定位系统服务
   }

   fun stop(){
       // 断开与定位服务的连接
   }
}

class MyLocationActivity : AppCompatActivity() {

    private lateinit var myLocationListener: MyLocationListener

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

        myLocationListener = MyLocationListener(this) {
          // updata UI
        }
    }

    override fun onStart() {
        super.onStart()
        myLocationListener.start()
    }

    override fun onStop() {
        super.onStop()
        myLocationListener.stop()
    }
}

在实际开发中,可能要在多个Activity的生命周期进行回调,这样,Activity中就要写大量代码,造成代码难以维护。还有一个问题,如果我们在onStart()方法里做了耗时操作,就可能造成当Activity或者Fragment的onStop()方法在onStart()方法之前结束,所以,我们需要一个感知生命周期的组件,这就是Lifecycle。

使用Lifecycle

添加依赖

官方给出的添加Lifecycle的依赖如下:

dependencies {
    def lifecycle_version = "2.1.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"
}

创建MyObserver

创建MyObserver并实现LifecycleObserver接口,Lifecycle实现的过程实际上是观察者模式。

package cn.appblog.jetpack.lifecycle;

public interface LifecycleCallback {
    void update(String message);
}
package cn.appblog.jetpack.lifecycle;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

public class MyObserver implements LifecycleObserver {

    private Lifecycle lifecycle;
    private LifecycleCallback lifecycleCallback;

    public MyObserver(Lifecycle lifecycle, LifecycleCallback lifecycleCallback) {
        this.lifecycle = lifecycle;
        this.lifecycleCallback = lifecycleCallback;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void connectOnCreate() {
        Log.i("yezhou", "OnCreate");
        update("OnCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void connectOnStart() {
        Log.i("yezhou", "OnStart");
        update("OnStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectOnResume() {
        Log.i("yezhou", "OnResume");
        update("OnResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void connectOnPause() {
        Log.i("yezhou", "OnPause");
        update("OnPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void connectOnStop() {
        Log.i("yezhou", "OnStop");
        update("OnStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void connectOnDestroy() {
        Log.i("yezhou", "OnDestroy");
        update("OnDestroy");
    }

    private void update(String message) {
        lifecycleCallback.update(message);
    }
}

在Activity中使用

在Activity中,只要将自定义的MyObserver添加到监听列表中,就可以监听到Activity的生命周期变化。

package cn.appblog.jetpack.lifecycle;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

public class LifecycleActivity extends AppCompatActivity {

    private MyObserver myObserver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Lifecycle lifecycle = getLifecycle();
        myObserver = new MyObserver(lifecycle, new LifecycleCallback() {
            @Override
            public void update(String message) {
                Log.i("yezhou", "LifecycleActivity.myObserver.update: " + message);
            }
        });

        lifecycle.addObserver(myObserver);
    }

}

从执行结果中,看到了是执行了索要监听的生命周期。

cn.appblog.jetpack I/yezhou: OnCreate
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnCreate
cn.appblog.jetpack I/yezhou: OnStart
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnStart
cn.appblog.jetpack I/yezhou: OnResume
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnResume
cn.appblog.jetpack I/yezhou: OnPause
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnPause
cn.appblog.jetpack I/yezhou: OnStop
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnStop
cn.appblog.jetpack I/yezhou: OnDestroy
cn.appblog.jetpack I/yezhou: LifecycleActivity.myObserver.update: OnDestroy

实现自定义的LifecycleOwner

LifecycleOwner是一个接口,定义如下:

package androidx.lifecycle;

import androidx.annotation.NonNull;

/**
 * A class that has an Android lifecycle. These events can be used by custom components to
 * handle lifecycle changes without implementing any code inside the Activity or the Fragment.
 *
 * @see Lifecycle
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

可以看到,LifecycleOwner只有一个方法,返回了Lifecycle,Lifecycle这个类包含Fragments 和 Activities的生命周期状态,并且可以让其他的组件观察这个状态。

Fragment 和 AppCompatActivity在Support Library 26.1.0及以后的版本已经实现了LifecycleOwner接口,如果我们想要一个自定义类,拥有Fragments 和 Activities的生命周期状态,可以实现LifecycleOwner接口,使用LifecycleRegistry类,具体代码如下:

package cn.appblog.jetpack.lifecycle;

import android.app.Activity;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

public class BaseActivity extends Activity implements LifecycleOwner {

    protected LifecycleRegistry lifecycleRegistry;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycleRegistry = new LifecycleRegistry(this);
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
    }

    @Override
    protected void onStart() {
        super.onStart();
        lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }
}

通过新建LifecycleRegistry,为LifecycleRegistry设置Lifecycle的各个状态。

同上注册观察者即可:

package cn.appblog.jetpack.lifecycle;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;

public class LifecycleOwnerActivity extends BaseActivity {

    private MyObserver myObserver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Lifecycle lifecycle = getLifecycle();
        myObserver = new MyObserver(lifecycle, new LifecycleCallback() {
            @Override
            public void update(String message) {
                Log.i("yezhou", "LifecycleOwnerActivity.myObserver.update: " + message);
            }
        });
        lifecycle.addObserver(myObserver);
    }
}
cn.appblog.jetpack I/yezhou: OnCreate
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnCreate
cn.appblog.jetpack I/yezhou: OnStart
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnStart
cn.appblog.jetpack I/yezhou: OnResume
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnResume
cn.appblog.jetpack I/yezhou: OnPause
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnPause
cn.appblog.jetpack I/yezhou: OnStop
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnStop
cn.appblog.jetpack I/yezhou: OnDestroy
cn.appblog.jetpack I/yezhou: LifecycleOwnerActivity.myObserver.update: OnDestroy

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/25/android-jetpack-architecture-components-lifecycle-usage/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android Jetpack架构组件(二)Lifecycle使用
前言 Lifecycle是生命周期感知组件,可以对Activity或者Fragment的生命周期的状态变化做出响应,帮助开发者写出更好组织的,轻量级的代码,更容易维护。 为什……
<<上一篇
下一篇>>
文章目录
关闭
目 录