Lifecycle,是用于帮助开发者管理Activity和Fragment的生命周期,它是LiveData和ViewModel的基础。
比如说,某个界面中发起了一条网络请求,但是当请求得到响应时,界面或许已经关闭了,这个时候就不应该继续对响应的结果进行处理。因此,需要时刻感知到Activity的生命周期,以便在适当的时候进行相应的逻辑控制。
通常的做法是:监听器的方式来对Activity的生命周期进行感知:
public class ExJetPackActivity extends AppCompatActivity {
private MyObserver observer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ex_jetpack);
observer=new MyObserver();
}
@Override
protected void onResume() {
super.onResume();
observer.activityResume();
}
@Override
protected void onPause() {
super.onPause();
observer.activityPause();
}
class MyObserver implements LifecycleObserver{
void activityResume(){
}
void activityPause(){
}
}
}
可以看到,为了让MyObserver能够感知到Activity 的生命周期,需要重写Activity 相应的生命周期方法,然后再通MyObserver。但实际开发中,可能会有多个组件在Activity的生命周期中进行回调,这样Activity的生命周期的方法中可能就需要放大量的代码,这就使得它们难以维护。如果我们在组件中做了耗时操作(比如在onStart方法),这种写法就无法保证组件在Activity或者Fragment停止之前完成启动。因此我们需要一个能管理Activity和Fragment的生命周期的库,这个库就是Lifecycle。
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
新建一个MyObsever 类,并实现LifecycleObserver 接口。
class MyObserver implements LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void activityResume(){
Log.e(TAG,"执行activityResume()方法");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void activityPause(){
Log.e(TAG,"activityPause()方法");
}
}
MyObserver实现了接口LifecycleObserver,LifecycleObserver用于标记一个类是生命周期观察者。LifecycleObserver是一个空方法接口,在接口中声明自己定义的方法。然后在activityResume() 方法、activityPause()方法上使用了@OnLifecycleEvent注解,并传入了一种声明生命周期事件。生命周期事件类型有:ON_CREATE、ON_START、ON_RESUME、ON_PAUSE、ON_STOP、ON_DESTROY分别匹配Activity中相应的生命周期回调;另外还有一种ON_ANY类型,表示可以匹配Activity的任何生命周期。
public class ExJetPackActivity extends AppCompatActivity {
public static final String TAG="ExJetPackActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ex_jetpack);
// 注释1
getLifecycle().addObserver(new MyObserver());
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG,"执行onResume()方法");
}
@Override
protected void onPause() {
super.onPause();
Log.e(TAG,"执行onPause()方法");
}
}
执行结果:
ExJetPackActivity: 执行onResume()方法
ExJetPackActivity: 执行activityResume()方法
ExJetPackActivity: 执行activityPause()方法
ExJetPackActivity: 执行onPause()方法
注释1 处代码调用LifecycleOwner的getLifecycle()方法,得到一个Lifecycle对象,然后再调用addObserver()方法来观察LifecycleOwner的生命周期,再把MyObserver 对象传进去。这样MyObserver就可以观察Activity的生命周期变化了,LifecycleOwner可以理解为被观察者。
只要Activity或者Fragment属于AndroidX库的,他们本身就是一个LifecycleOwner的实例,这部分工作已经由AndroidX库自动帮我们完成了。
如果想实现自定义LifecycleOwner,可以使用LifecycleRegistry,它是Lifecycle的实现类。
public class ExJetPackActivity extends AppCompatActivity {
public static final String TAG="ExJetPackActivity";
private LifecycleRegistry registry;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ex_jetpack);
registry=new LifecycleRegistry(this);
registry.setCurrentState(Lifecycle.State.CREATED);
}
@Override
protected void onStart() {
super.onStart();
registry.setCurrentState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return registry;
}
}
getLifecycle()返回lifecycleRegistry实例。lifecycleRegistry实例则是在onCreate创建,并且在各个生命周期内调用setCurrentState()方法完成生命周期事件的传递。
使用ProcessLifecycleOwner可以直接获取应用前后台切换状态。
依赖:
implementation "androidx.lifecycle:lifecycle-process:2.3.1"
使用ProcessLifecycleOwner.get()获取ProcessLifecycleOwner,代码如下:
class AppApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(new AppObserver());
}
}
public class AppObserver implements LifecycleObserver {
private static final String TAG = "AppObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForeground() {
Log.e(TAG, "进入前台");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackground() {
Log.w(TAG, "进入后台");
}
}
MyObserver 能够感知到Activity 的生命周期发生变化,同时要想主动获取当前的生命周期状态,可以在MyObserver 的构造函数中将Lifecycle对象传进来即可。
class MyObserver implements LifecycleObserver{
private Lifecycle mLifecycle;
public MyObserver(Lifecycle mLifecycle){
this.mLifecycle=mLifecycle;
}
}
有了Lifecycle对象之后,可以调用lifecycle.currentState来主动获知当前的生命周期状态。
Lifecycle 事件和状态:
// 事件
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
// 状态
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* right before Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
*
* - after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
*
- right before {@link android.app.Activity#onStop() onStop} call.
*
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
*
* - after {@link android.app.Activity#onStart() onStart} call;
*
- right before {@link android.app.Activity#onPause() onPause} call.
*
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
}