Explicación detallada del uso de los componentes LifeCycle de Jetpack

1. Introducción al ciclo de vida

LifeCycle es un componente que está al tanto de los cambios en el ciclo de vida del host. Los hosts comunes incluyen Actividad/Fragmento, Servicio y Aplicación. LifeCycle contiene información sobre el estado del ciclo de vida del host y notifica a los observadores que escuchan al host cuando cambia el ciclo de vida del host.

La aparición de LifeCycle es principalmente para resolver: el acoplamiento entre el ciclo de vida de los componentes del sistema y los componentes ordinarios.

  • Los componentes del sistema se refieren a: Actividad/Fragmento, Servicio y Aplicación.
  • Los componentes ordinarios se refieren a componentes que encapsulan código según funciones o funciones.

imagen.png

¿En qué circunstancias se acoplará el ciclo de vida de los componentes del sistema con el ciclo de vida de los componentes ordinarios?

Toma una castaña:

Existe una necesidad comercial de reproducción de video en el negocio de las 58 tribus. Necesitamos inicializar el componente de reproducción de video en la actividad, detener la reproducción de video en el método onPause() y reciclar el componente de reproducción de video y algunos recursos en el método onDestroy(). Tal enfoque es muy engorroso y aumentará el acoplamiento entre la página y el componente.

Para este tipo de problema, se puede utilizar LifeCycle para resolverlo. No solo reduce el acoplamiento entre módulos, sino que también reduce la posibilidad de fugas de memoria .

2. Uso del ciclo de vida

Jetpack nos proporciona dos interfaces:

observado ​LifecycleOwner​:

observador ​LifecycleObserver​:

El componente del sistema supervisado debe implementar la interfaz LifecycleOwner y el observador debe implementar la interfaz LifecycleObserver.

(1) Escenario 1: use LifeCycle para desacoplar páginas y componentes

(1) Actividad de desacoplamiento

Paso 1: Agregar dependencias

implementation 'androidx.appcompat:appcompat:1.2.0'  

复制代码

在 AndroidX 里面 ComponentActivity 已经默认实现了 LifecycleOwner 接口。如果项目没有迁移到 AndroidX,还是用的 Support 库,新版本的 SDK 也通过 SupportActivity 实现了 LifecycleOwner 接口。

imagen.png

在 LifecycleOwner 接口中,只有一个 getLifecycle 方法。

第二步:实现观察者

如果是想监听某个 Activity 的生命周期,需要我们做的就是自定义组件,实现 LifecycleObserver 接口即可,该接口没有接口方法,不需要任何具体的实现。

比如以刚刚的视频播放为例:

  1. 创建一个 MyVideoPlayListener 类,实现 LifecycleObserver 接口,与视频播放相关的逻辑全在这个类里面完成。对于组件里面需要在 Activity 生命周期变化时得到通知的方法,用 @OnLifecycleEvent(Lifecycle.Event.ON_XXX) 注解进行标记,这样当 Activity 生命周期发生变化时,被标记过的方法便会被自动调用。
public class MyVideoPlayListener implements LifecycleObserver {  
    private static String TAG = "MyVideoPlayListener";  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_CREATE)  
    private void initVideo(){  
        Log.d(TAG,"initVideo");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_RESUME)  
    private void startPlay(){  
        Log.d(TAG,"startPlay");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_PAUSE)  
    private void pausePlay(){  
        Log.d(TAG,"pausePlay");  
    }  
}  

复制代码

2.在 MainActivity 中对 MyVideoPlayListener 进行引用即可。

public class MainActivity extends AppCompatActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity\_main);  
  
        MyVideoPlayListener listener = new MyVideoPlayListener();  
        getLifecycle().addObserver(listener);  
    }  
}  

复制代码

#####(2)解耦 Fragment

在新版的 SDK 中,Fragment 同样也默认实现了 LifecycleOwner 接口,因此,以上的例子同样适合于 Fragment。

####(二)使用场景2:使用 LifecycleService 解耦 Service 与组件

(1)LifecycleService 基本介绍

Android 中拥有生命周期的组件除了 Activity/Fragment ,还有一个非常重要的组件就是 Service。LifecycleService 就是用来监听和解耦 Service 组件的。

public class LifecycleService extends Service implements LifecycleOwner {  
  
    private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);  
  
    ......  
  
    @Override  
    @NonNull  
    public Lifecycle getLifecycle() {  
        return mDispatcher.getLifecycle();  
    }  
}  

复制代码
(2)具体使用方法

第一步:添加相关依赖

implementation "androidx.lifecycle:lifecycle-service:2.2.0"  

复制代码

第二步:创建 MyServiceObserver 类,实现 LifecycleObserver 接口。使用 @OnLifecycleEvent 标记希望在 Server 生命周期发生变化时得到同步调用的方法。

public class MyServiceObserver implements LifecycleObserver {  
    private static String TAG = "MyServiceObserver";  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_CREATE)  
    private void initVideo(){  
        Log.d(TAG,"initVideo");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_DESTROY)  
    private void pausePlay(){  
        Log.d(TAG,"stopPlay");  
    }  
}  

复制代码

第三步:创建一个 MyService 的类,继承 LifecycleService。由于 LifecycleService 是 Service 的直接子类,所以使用起来与普通的 Service 没有差别。

public class MyService extends LifecycleService {  
    private MyServiceObserver myServiceObserver;  
  
    public MyService(){  
        myServiceObserver = new MyServiceObserver();  
        getLifecycle().addObserver(myServiceObserver);  
    }  
}  

复制代码

#####(三)使用场景3:使用 ProcessLifecycleOwner 监听应用程序的生命周期

具有生命周期的组件除了 Activity、Fragment 和 Service 外,还有 Application。ProcessLifecycleOwner 就是用来监听整个应用程序的生命周期情况。

具体使用方法:

第一步:添加依赖项

implementation "androidx.lifecycle:lifecycle-process:2.2.0"  

复制代码

第二步:定义一个 ApplicationObserver,实现 LifecycleObserver 接口。

public class ApplicationObserver implements LifecycleObserver {  
    private String TAG = this.getClass().getName();  
  
    /\*\*  
     \* 在应用程序的整个生命周期中只会被调用一次  
     \*/  
    @OnLifecycleEvent(Lifecycle.Event.ON\_CREATE)  
    public void onCreate() {  
        Log.d(TAG,"Lifecycle.Event.ON\_CREATE");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_START)  
    public void onStart() {  
        Log.d(TAG,"Lifecycle.Event.ON\_START");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_RESUME)  
    public void onResume() {  
        Log.d(TAG,"Lifecycle.Event.ON\_RESUME");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_PAUSE)  
    public void onPause() {  
        Log.d(TAG,"Lifecycle.Event.ON\_PAUSE");  
    }  
  
    @OnLifecycleEvent(Lifecycle.Event.ON\_STOP)  
    public void onStop() {  
        Log.d(TAG,"Lifecycle.Event.ON\_STOP");  
    }  
  
    /\*\*  
     \* 永远不会被调用,系统不会分发调用 ON\_DESTROY 事件  
     \*/  
    @OnLifecycleEvent(Lifecycle.Event.ON\_DESTROY)  
    public void onDestroy() {  
        Log.d(TAG,"Lifecycle.Event.ON\_DESTROY");  
    }  
}  

复制代码

第三步:在 Application 中关联 ApplicationObserver。

public class App extends Application {  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationObserver());  
    }  
}  

复制代码

注意事项:

  1. ProcessLifecycleOwner 是针对整个应用程序的监听,与 Activity 的数量无关。
  2. Lifecycle.Event.ON_CREATE 只会被调用一次,而 Lifecycle.Event.ON_DESTROY 永远不会被调用。
  3. Lifecycle.Event.ON_PAUSE 和 Lifecycle.Event.ON_STOP 的调用会有一定的延后,因为系统需要为“屏幕旋转,由于配置发生变化而导致的 Activity 重新创建” 的情况预留一些时间。

三、Lifecycle 的另外两种写法

Lifecycle 有三种实现方法:

  1. LifecycleObserver 配合注解
  2. FullLifecyclerObserver 拥有宿主所有生命周期事件
  3. LifecycleEventObserver宿主生命周期事件封装成 Lifecycle.Event

En la sección anterior, usamos el primer método: LifecycleObserver con anotaciones.

Este método es relativamente simple de usar, pero tenga en cuenta que es mejor agregar el compilador del ciclo de vida del procesador de anotaciones; de lo contrario, usará la reflexión para volver a llamar al método correspondiente en tiempo de ejecución:

annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"  

复制代码

Después de agregar este procesador de anotaciones, el método ​@OnLifecycleEvent​marcado con ya no se puede declarar como ​private​, de lo contrario, se informará el siguiente error:

method marked with OnLifecycleEvent annotation can not be private  

复制代码

Las otras dos implementaciones se describen a continuación:

(1) FullLifecyclerObserver tiene todos los eventos del ciclo de vida del host
//该接口中定义好了生命周期方法,我们只需要实现 FullLifecycleObserver 接口,重写对应的  
//生命周期方法即可。不过目前 FullLifecycleObserver 这个接口未开放给开发者使用。  
interface FullLifecycleObserver extends LifecycleObserver {  
  
    void onCreate(LifecycleOwner owner);  
  
    void onStart(LifecycleOwner owner);  
  
    void onResume(LifecycleOwner owner);  
  
    void onPause(LifecycleOwner owner);  
  
    void onStop(LifecycleOwner owner);  
  
    void onDestroy(LifecycleOwner owner);  
}  

复制代码
(2) LifecycleEventObserver aloja eventos del ciclo de vida encapsulados en Lifecycle.Event
//通过实现 LifecycleEventObserver 接口,重写 onStateChanged 方法,在该方法内部  
//通过判断 Lifecycle.Event 来实现具体的业务逻辑  
public class MyVideoPlayObserver implements LifecycleEventObserver {  
    private static String TAG = "MyVideoPlayObserver";  
  
    @Override  
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {  
        switch (event){  
            case ON\_CREATE:  
                Log.d(TAG,"initVideo");  
                break;  
            case ON\_START:  
                Log.d(TAG,"startPlay");  
                break;  
            case ON\_RESUME:  
                Log.d(TAG,"resumePlay");  
                break;  
            default:  
                 break;  
        }  
    }  
}  

复制代码

4. Resumen

El significado principal de la existencia de componentes LifeCycle es ayudarnos a desacoplarnos, para que los componentes que definimos también puedan sentir los cambios en el ciclo de vida.

5. Suplemento

Al momento de la publicación de este artículo, la última versión ​2.2.0​de Para obtener la última versión, consulte el sitio web oficial:

Nota ​lifecycle-extensions​: La API en ha quedado obsoleta. Cuando necesite usar una herramienta en Lifecycle, puede agregar la dependencia correspondiente:

    dependencies {  
        def lifecycle\_version = "2.2.0"  
        def arch\_version = "2.1.0"  
  
        // ViewModel  
        implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle\_version"  
        // LiveData  
        implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle\_version"  
        // Lifecycles only (without ViewModel or LiveData)  
        implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle\_version"  
  
        // Saved state module for ViewModel  
        implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle\_version"  
  
        // Annotation processor  
        annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle\_version"  
        // alternately - if using Java8, use the following instead of lifecycle-compiler  
        implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle\_version"  
  
        // optional - helpers for implementing LifecycleOwner in a Service  
        implementation "androidx.lifecycle:lifecycle-service:$lifecycle\_version"  
  
        // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process  
        implementation "androidx.lifecycle:lifecycle-process:$lifecycle\_version"  
  
        // optional - ReactiveStreams support for LiveData  
        implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle\_version"  
  
        // optional - Test helpers for LiveData  
        testImplementation "androidx.arch.core:core-testing:$arch\_version"  
    }  

复制代码

Supongo que te gusta

Origin juejin.im/post/7086763634864422920
Recomendado
Clasificación