1. Introdução ao Ciclo de Vida
LifeCycle é um componente que está ciente das mudanças no ciclo de vida do host. Os hosts comuns incluem Atividade/Fragmento, Serviço e Aplicativo. O LifeCycle contém informações sobre o status do ciclo de vida do host e notifica os observadores que estão ouvindo o host quando o ciclo de vida do host é alterado.
O surgimento do LifeCycle é principalmente para resolver: o acoplamento entre o ciclo de vida dos componentes do sistema e os componentes comuns.
- Os componentes do sistema referem-se a: Atividade/Fragmento, Serviço e Aplicação.
- Componentes comuns referem-se a componentes que encapsulam código de acordo com funções ou funções.
Sob quais circunstâncias o ciclo de vida dos componentes do sistema será acoplado ao ciclo de vida dos componentes comuns?
Pegue uma castanha:
Há uma necessidade comercial de reprodução de vídeo no negócio de 58 tribos. Precisamos inicializar o componente de reprodução de vídeo na Activity, parar a reprodução de vídeo no método onPause() e reciclar o componente de reprodução de vídeo e alguns recursos no método onDestroy(). Essa abordagem é muito complicada e aumentará o acoplamento entre a página e o componente.
Para esse tipo de problema, o LifeCycle pode ser usado para resolvê-lo. Isso não apenas reduz o acoplamento entre os módulos, mas também reduz a possibilidade de vazamentos de memória .
2. Uso do LifeCycle
O Jetpack nos fornece duas interfaces:
Observado LifecycleOwner
:
Observador LifecycleObserver
:
O componente do sistema monitorado precisa implementar a interface LifecycleOwner e o observador precisa implementar a interface LifecycleObserver.
(1) Cenário 1: Use o LifeCycle para desacoplar páginas e componentes
(1) Atividade de desacoplamento
Etapa 1: adicionar dependências
implementation 'androidx.appcompat:appcompat:1.2.0'
复制代码
在 AndroidX 里面 ComponentActivity 已经默认实现了 LifecycleOwner 接口。如果项目没有迁移到 AndroidX,还是用的 Support 库,新版本的 SDK 也通过 SupportActivity 实现了 LifecycleOwner 接口。
在 LifecycleOwner 接口中,只有一个 getLifecycle 方法。
第二步:实现观察者
如果是想监听某个 Activity 的生命周期,需要我们做的就是自定义组件,实现 LifecycleObserver 接口即可,该接口没有接口方法,不需要任何具体的实现。
比如以刚刚的视频播放为例:
- 创建一个 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());
}
}
复制代码
注意事项:
- ProcessLifecycleOwner 是针对整个应用程序的监听,与 Activity 的数量无关。
- Lifecycle.Event.ON_CREATE 只会被调用一次,而 Lifecycle.Event.ON_DESTROY 永远不会被调用。
- Lifecycle.Event.ON_PAUSE 和 Lifecycle.Event.ON_STOP 的调用会有一定的延后,因为系统需要为“屏幕旋转,由于配置发生变化而导致的 Activity 重新创建” 的情况预留一些时间。
三、Lifecycle 的另外两种写法
Lifecycle 有三种实现方法:
- LifecycleObserver 配合注解
- FullLifecyclerObserver 拥有宿主所有生命周期事件
- LifecycleEventObserver宿主生命周期事件封装成 Lifecycle.Event
Na seção anterior, usamos o primeiro método: LifecycleObserver com anotações.
Esse método é relativamente simples de usar, mas observe que é melhor adicionar o compilador de ciclo de vida do processador de anotações, caso contrário, ele usará a reflexão para chamar de volta o método correspondente em tempo de execução:
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"
复制代码
Após adicionar este processador de anotação, o método @OnLifecycleEvent
marcado com não pode mais ser declarado comoprivate
, caso contrário, o seguinte erro será relatado:
method marked with OnLifecycleEvent annotation can not be private
复制代码
As outras duas implementações são descritas abaixo:
(1) FullLifecyclerObserver tem todos os eventos de ciclo de vida do 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 hospeda eventos de ciclo de vida encapsulados em 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. Resumo
O principal significado da existência de componentes LifeCycle é nos ajudar a desacoplar, para que os componentes que definimos também possam sentir as mudanças no ciclo de vida.
5. Suplemento
No momento da publicação deste artigo, a versão mais recente de lifecycle_version é 2.2.0
. Para obter a versão mais recente, consulte o site oficial:
Nota lifecycle-extensions
: A API em foi obsoleta. Quando você precisa usar uma ferramenta em Ciclo de vida, você pode adicionar a dependência correspondente:
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"
}
复制代码