Lifecycle
- 定义
- Lifecycle使用
- 源码中如何使用Lifecycle
定义
构建生命周期感知型组件,这些组件可以根据 Activity 或 Fragment 的当前生命周期状态调整行为。
Lifecycle使用 三种方式
LifecycleObserver, FullLifecycleObserver, LifecycleEventObserver (后面两个继承前者)
1. 自定义的LifecycleObserver观察者,用注解声明每个方法观察的宿主的状态
class LocationObserver extends LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStart(@NotNull LifecycleOwner owner){
//开启定位
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(@NotNull LifecycleOwner owner){
//停止定位
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(@NotNull LifecycleOwner owner){
//释放资源
}
}
// 注册观察者,观察宿主生命周期状态变化
// 使用Fragment或者Activity中使用 (Activity使用,需要Activity继承CommontActivity)
class MyFragment extends Fragment{
public void onCreate(Bundle bundle){
MyLifecycleObserver observer =new MyLifecycleObserver()
getLifecycle().addObserver(observer);
}
}
使用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);
}
// 使用DefaultLifecycleObserver 默认实现了所有接口 实现此接口,不需要所有的方法都要实现
class MyObserver implements DefaultLifecycleObserver {
void onStart(LifecycleOwner owner) {
// 开启定位
}
void onStop(LifecycleOwner owner) {
// 停止定位
}
void onDestroy(LifecycleOwner owner) {
// 释放资源
}
}
// 使用Fragment或者Activity中使用 (Activity使用,需要Activity继承CommontActivity)
class MyFragment extends Fragment{
public void onCreate(Bundle bundle){
MyObserver observer =new MyObserver()
getLifecycle().addObserver(observer);
}
}
使用LifecycleEventObserver
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}
class LocationObserver extends LifecycleEventObserver{
@override
void onStateChanged(LifecycleOwner source, Lifecycle.Event event){
//需要自行判断life-event是onStart, 还是onStop,亦或者是onDestroy
}
}
Lifecycle 抽象类
- 注册监听
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
- 移除监听
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
- 获取当前状态
@MainThread
@NonNull
public abstract State getCurrentState();
- Event
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE, // 宿主发送onCreate事件
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,// 宿主发送onStart事件
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,// 宿主发送onResume事件
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,// 宿主发送onPause事件
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,// 宿主发送onStop事件
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,// 宿主发送onDestroy事件
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY // 宿主发送onCreate事件
}
- State
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;
}
}
- DESTROYED: Activity执行onDestroy的状态
- INITIALIZED:当Activity执行onCreate之前会置为当前状态,也是Activity默认状态
- CREATED: 当执行onCreate之后或者执行onStop后的状态
- STARTED: 执行onStart或者onPause后的状态
- RESUMED:执行onResume后的状态
LifecycleRegistry
- LifecycleRegistry 继承Lifecycle,Activity/Fragment宿主生命周期分发主要的在此类中
LifecycleOwner、Lifecycle、LifecycleObserver
LifecycleOwner:宿主,一般Fragment和Activity实现LifecycleOwner,并实现getLifecycle()方法,宿主成员变量中创建Lifecycle(LifecycleRegistry)对象,用来事件的分发
Lifecycle:在宿主中创建,并提供LifecycleRegistry对象,便于外界获取并通知生命周期
LifecycleObserver: 创建的Observer对象,注册到宿主中LifecycleRegistry对象里,达到对应的生命周期时,做对应的业务
Activity/Fragment生命周期管理
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
// Activity/ Fragment 生命周期分发都会走到LifecycleRegistry的当前方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next); // 将当前状态与Activity/Fragment生命周期对其, 会调用到sysc()方法
}
// 根据当前传入的event 获取对应的状态, 如果是Stop或者Pause 则状态回退
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE: // 如果是create或者stop 则返回CREATED状态
case ON_STOP:
return CREATED;
case ON_START: // 如果是Start或者Pause 则返回STARTED状态
case ON_PAUSE:
return STARTED;
case ON_RESUME: // 如果是resume,则返回Resumed状态
return RESUMED;
case ON_DESTROY: // Destroy 返回Destoryed状态
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
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.");
}
while (!isSynced()) {
// 判断条件为,当前宿主的Observer中如果有与宿主对象状态不一致,才会进入循环体,如果一致,则不处理
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
// 判断宿主当前的状态是否比 Observer的状态小,如果是,则原来注册的Observer状态回退
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
// 如果Observer状态新加入,则需要将新加进来的Observer对齐宿主状态
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
// 状态回退
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
// 事件回退
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
// 递归调用事件处理
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
// 状态前进,保持与宿主状态对齐
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
// 根据不同的事件,事件回退
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
// 事件前进
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}