Android Jetpack Components 之 Architecture Lifecycles

管理应用Activity以及Fragment的生命周期(Manage your activity and fragment lifecycles),组件位于android.arch.lifecycle包下。

Lifecycles 解决了什么的问题?

通常在一个MVP架构的应用中,Presenter会或多或少的关注Activity或者Fragment的生命周期,如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class MainActivity : AppCompatActivity() {
private lateinit var mPresenter: MainPresenter

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mPresenter = MainPresenter()
mPresenter.onCreate()
}

override fun onResume() {
super.onResume()
mPresenter.onResume()
...
}


override fun onPause() {
super.onPause()
mPresenter.onPause()
...
}

override fun onDestroy() {
super.onDestroy()
mPresenter.onDestroy()
...
}
}

在实际生产环境中,代码会非常复杂,会导致生命周期方法非常臃肿。Lifecycles组件以观察者模式的设计实现对被观察者生命周期的感知,通过注解的方式注册对应的生命周期。一般这个组件会与其他jetpack组件一起组合使用,比如ViewModel,LiveData。

Lifecycles 使用

我们使用Lifecycles将上面的例子改造一下

  • 观察者LifecyclerObserver

当前例子中,观察者是Presenter,这里定义一个IPresenter接口,让所有的Presenter实现此接口。观察者需要实现LifecycleObserver接口,然后使用@OnLifecycleEvent注解的方式注册监听被观察者的生命周期。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface IPresenter : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate()

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart()

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume()

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause()

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop()

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy()

@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onLifecycleChange()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
open class BasePresenter : IPresenter {
companion object {
const val TAG = "BasePresenter"
}

override fun onResume() {
Log.d(TAG, "${this.javaClass.name} onResume")
}

override fun onPause() {
Log.d(TAG, "${this.javaClass.name} onPause")
}

override fun onStop() {
Log.d(TAG, "${this.javaClass.name} onStop")
}

override fun onStart() {
Log.d(TAG, "${this.javaClass.name} onStart")
}

override fun onCreate() {
Log.d(TAG, "${this.javaClass.name} onCreate")
}

override fun onDestroy() {
Log.d(TAG, "${this.javaClass.name} onDestroy")
}

override fun onLifecycleChange() {
Log.d(TAG, "${this.javaClass.name} onChange")
}
}
  • 被观察者

当前例子中,activity是被观察者,需要实现LifecycleOwner接口,接着维护一个LifecycleRegistry成员属性,在被观察者不同的生命周期函数中通过LifecycleRegistry成员属性通知生命周期的变化,调用addObserver方法添加观察者。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class MyActivity : AppCompatActivity(), LifecycleOwner {

private lateinit var mLifecycleRegistry: LifecycleRegistry
private lateinit var mPresenter: MainPresenter

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mPresenter = MainPresenter()
mLifecycleRegistry = LifecycleRegistry(this)
mLifecycleRegistry.markState(Lifecycle.State.CREATED)
mLifecycleRegistry.addObserver(mPresenter)
}

public override fun onStart() {
super.onStart()
mLifecycleRegistry.markState(Lifecycle.State.STARTED)
// 或者
// mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}

// LifecycleOwner需要重写的方法
override fun getLifecycle(): Lifecycle {
return mLifecycleRegistry
}

// 其他生命周期方法
...
}

如果正在使用26.1.0及其之后版本的Support Library,AppCompatActivity已经实现LifecycleOwner接口,可以查看SupportActivity的源码,相关代码如下

android.support.v4.app.SupportActivity

1
2
3
4
public class SupportActivity extends Activity implements LifecycleOwner, Component {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
}

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "MainActivity"
}

private lateinit var mPresenter: MainPresenter

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mPresenter = MainPresenter()
lifecycle.addObserver(mPresenter)
}
}

Lifecycle

Lifecycle是一个类,它包含关于组件生命周期状态(比如Activity,Fragment)的信息,并允许其他对象观察该状态。

Lifecycle使用两个枚举类来跟踪相关组件的生命周期状态。

  • Event(源码位于Lifecycle类中)从LifecycleOwner对象中发出这些事件,由LifecycleObserver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
}
  • State(源码位于Lifecycle类中)当前的组件的状态

以上图可以看出某个Event对应的State

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
* <b>right before</b> 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:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,

/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
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;

/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}

这里关于StateisAtLeast方法用法举个例子,通常Presenter会持有View对象,在一定的时候调用View提供的回调方法来做相应的操作,假设这里有个需求,由一个弹框提示至少在当前Activity Resume的时候才弹出来。观察State那张图,当Activity属于Resume状态时,State为RESUMED。

1
2
3
4
5
6
7
8
9
10
11
class MainActivity : AppCompatActivity(), MainViewer {
...

override fun onShowTip() {
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
AlertDialog ....
}
}

...
}

LifecycleOwner

LifecycleOwner是一个接口,它仅有一个方法getLifecycle,必须由子类实现,任何类都可以实现此接口,构建此类的生命周期感知。实现LifecycleObserver的类和实现LifecyclerOwner的类就组合成了经典的观察者和被观察者,任何被观察者都可以提供一个生命周期让观察者注册观察。

Lifecycles UML

参考

Lifecycles组件官方地址