是什么
是具备宿主生命周期感知能力的组件。它能持有组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他观察者监听宿主的状态。
各类之间的关系
如何使用 Lifecycle 观察宿主状态
1. LifecycleObserver 配合注解
这种方式需要添加lifecycle-compiler注解处理器。
//1. 自定义的LifecycleObserver观察者,在对应方法上用注解声明想要观 察的宿主的生命周期事件即可
class LocationObserver extends LifecycleObserver{
//宿主执行了onstart时,会分发该事件
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStart(@NotNull LifecycleOwner owner){
//开启定位
}
//宿主执行了onstop时 会分发该事件
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(@NotNull LifecycleOwner owner){
//停止定位
}
}
//2. 注册观察者,观察宿主生命周期状态变化
class MyFragment extends Fragment{
public void onCreate(Bundle bundle){
LocationObserver observer =new LocationObserver()
getLifecycle().addObserver(observer);
}
}
2. FullLifecyclerObserver 拥有宿主所有生命周期事件
//1.源码,目前这个类权限不可见,即便如此,我们也要了解它
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.用法,需要监听那个事件,复写那个方法即可
class LocationObserver extends FullLifecycleObserver{
void onStart(LifecycleOwner owner){}
void onStop(LifecycleOwner owner){}
}
3. LifecycleEventObserver宿主生命周期事件封装成 Lifecycle.Event
//1.源码
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}
//2.用法
class LocationObserver extends LifecycleEventObserver{
@override
void onStateChanged(LifecycleOwner source, Lifecycle.Event event){
//需要自行判断life-event是onstart, 还是onstop
}
}
Fragment 是如何实现 Lifecycle 的
在各个生命周期方法内利用LifecycleRegistry分发相应的事件给每个观察者。
public class Fragment implements LifecycleOwner {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
//复写自LifecycleOwner,所以必须new LifecycleRegistry对象返回
return mLifecycleRegistry;
}
void performCreate(){
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart(){
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
.....
void performResume(){
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
}
Activity 是如何实现 Lifecycle 的
借助于 ReportFragment 往 Activity 上添加一个 fragment 用以报告生命周期的变化。目的是为了兼顾不是继承自 AppCompactActivity 的场景, 同时也支持我们自定义 LifecycleOwner 的场景。
public class ComponentActivity extends Activity implements LifecycleOwner{
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
protected void onCreate(Bundle bundle){
super.onCreate(savedInstanceState);
//往Activity上添加一个fragment,用以报告生命周期的变化
//目的是为了兼顾不是继承自AppCompactActivity的场景.
ReportFragment.injectIfNeededIn(this);
}
}
public class ReportFragment extends Fragment{
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
}
private void dispatch(Lifecycle.Event event) {
Lifecycle lifecycle = activity.getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
宿主生命周期与宿主状态模型图
Lifecycle添加observer的源码分析
// LifecycleRegistry.class
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
// 添加新的Observer时,会首先根据宿主的状态计算出它的初始状态,只要不是在onDestroy中注册的,它的初始状态都是INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 接着会把observer包装成ObserverWithState,这个类主要是包含了观察者及其状态。每个事件都会经由这个对象类转发
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 添加到集合,如果之前已经添加过了,则return
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// 页面被回收时为null,return
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
// 计算目标state,之后会将当前state和目标state之间的所有event回调给observer
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
// 拿观察者的状态和宿主当前状态做比较,如果小于0,说明两者状态还没有对齐
while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
// 获取下一个生命周期事件对应的event,例如当前state是INITIALIZED,则下一个生命周期事件对应的event是ON_CREATE
final Event event = Event.upFrom(statefulObserver.mState);
// 如果当前state没有对应的下一个event,抛异常
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
// 分发event
statefulObserver.dispatchEvent(lifecycleOwner, event);
popParentState();
// 页面状态可能发生变化,重新计算目标state,继续做循环和目标state做比较,直到两者一样
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
// 状态同步过程中,宿主状态可能有变动,比如由RESUMED-> STARTED,调用sync()完成事件的分发和观察者状态的同步
sync();
}
mAddingObserverCounter--;
}
// ObserverWithState.class,持有观察者及其状态的内部类
static class ObserverWithState {
// 持有Observer的状态,方便与宿主状态做比对同步:
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// 根据observer的类型(FullLifecycleObserver、LifecycleEventObserver)转换成对应的适配器类,适配器类会对onStateChanged方法进行适配,并以相应的方式(反射、中转)把事件转发到我们的observer上;统一事件的分发形式。
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
// observer初始状态:INITIALIZED、DESTROYED
mState = initialState;
}
// 分发event
void dispatchEvent(LifecycleOwner owner, Event event) {
// 根据event获取对应的state
State newState = event.getTargetState();
mState = min(mState, newState);
// 回调通知observer生命周期事件
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
sequenceDiagram
LifecycleRegistry->>LifecycleRegistry: addObserver( LifecycleObserver)
LifecycleRegistry->>LifecycleRegistry: calculateTargetState(observer)
LifecycleRegistry->>ObserverWithState: dispatchEvent(owner, event)
宿主生命周期变化后相应事件的分发
// LifecycleRegistry.class
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
// 获取event对应的state,同步observer的state
moveToState(event.getTargetState());
}
private void moveToState(State next) {
// 如果LifecycleRegistry的状态没有改变,不做处理
if (mState == next) {
return;
}
// 保存宿主state
mState = next;
// 如果正在分发生命周期事件 或者 刚注册了observer(也是正在分发生命周期事件),则不做处理,因为后面都会调sync()同步所有observer的状态
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
// 同步观察者状态
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
// 同步LifecycleRegistry注册了的所有observer的状态
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
// 如果observer的状态和LifecycleRegistry的状态不同步,则同步它们的状态
while (!isSynced()) {
mNewEventOccurred = false;
// mObserverMap中的节点以链表的形式连接
// 如果宿主state小于最先添加的observer(头节点)的state,则说明宿主可能发生了状态回退,比如当前是RESUMED状态,执行了onPause则回退到STARTED状态,此时调用backwardPass把集合中的每个一观察者分发一个on_pause事件,并同步它的状态,即将所有observer的state回退到和宿主state一致
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
// 如果宿主state大于最后的observer(尾节点)的state,则说明宿主可能发生了状态前进,比如当前是STARTED状态,执行了onResume则前进到RESUMED状态,此时调用forwardPass把集合中的每个一观察者分发一个on_resume事件,并同步它的状态。
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}