Lifecycle
- 定義
- Lifecycle使用
- 源碼中如何使用Lifecycle
定義
構(gòu)建生命周期感知型組件,這些組件可以根據(jù) Activity 或 Fragment 的當(dāng)前生命周期狀態(tài)調(diào)整行為。
Lifecycle使用 三種方式
LifecycleObserver, FullLifecycleObserver, LifecycleEventObserver (后面兩個繼承前者)
1. 自定義的LifecycleObserver觀察者,用注解聲明每個方法觀察的宿主的狀態(tài)
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){
//釋放資源
}
}
// 注冊觀察者,觀察宿主生命周期狀態(tài)變化
// 使用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 默認(rèn)實現(xiàn)了所有接口 實現(xiàn)此接口,不需要所有的方法都要實現(xiàn)
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){
//需要自行判斷l(xiāng)ife-event是onStart, 還是onStop,亦或者是onDestroy
}
}
Lifecycle 抽象類
- 注冊監(jiān)聽
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
- 移除監(jiān)聽
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
- 獲取當(dāng)前狀態(tài)
@MainThread
@NonNull
public abstract State getCurrentState();
- Event
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE, // 宿主發(fā)送onCreate事件
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,// 宿主發(fā)送onStart事件
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,// 宿主發(fā)送onResume事件
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,// 宿主發(fā)送onPause事件
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,// 宿主發(fā)送onStop事件
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,// 宿主發(fā)送onDestroy事件
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY // 宿主發(fā)送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執(zhí)行onDestroy的狀態(tài)
- INITIALIZED:當(dāng)Activity執(zhí)行onCreate之前會置為當(dāng)前狀態(tài),也是Activity默認(rèn)狀態(tài)
- CREATED: 當(dāng)執(zhí)行onCreate之后或者執(zhí)行onStop后的狀態(tài)
- STARTED: 執(zhí)行onStart或者onPause后的狀態(tài)
- RESUMED:執(zhí)行onResume后的狀態(tài)
LifecycleRegistry
- LifecycleRegistry 繼承Lifecycle,Activity/Fragment宿主生命周期分發(fā)主要的在此類中
LifecycleOwner、Lifecycle、LifecycleObserver
LifecycleOwner:宿主,一般Fragment和Activity實現(xiàn)LifecycleOwner,并實現(xiàn)getLifecycle()方法,宿主成員變量中創(chuàng)建Lifecycle(LifecycleRegistry)對象,用來事件的分發(fā)
Lifecycle:在宿主中創(chuàng)建,并提供LifecycleRegistry對象,便于外界獲取并通知生命周期
LifecycleObserver: 創(chuàng)建的Observer對象,注冊到宿主中LifecycleRegistry對象里,達(dá)到對應(yīng)的生命周期時,做對應(yīng)的業(yè)務(wù)
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 生命周期分發(fā)都會走到LifecycleRegistry的當(dāng)前方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next); // 將當(dāng)前狀態(tài)與Activity/Fragment生命周期對其, 會調(diào)用到sysc()方法
}
// 根據(jù)當(dāng)前傳入的event 獲取對應(yīng)的狀態(tài), 如果是Stop或者Pause 則狀態(tài)回退
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE: // 如果是create或者stop 則返回CREATED狀態(tài)
case ON_STOP:
return CREATED;
case ON_START: // 如果是Start或者Pause 則返回STARTED狀態(tài)
case ON_PAUSE:
return STARTED;
case ON_RESUME: // 如果是resume,則返回Resumed狀態(tài)
return RESUMED;
case ON_DESTROY: // Destroy 返回Destoryed狀態(tài)
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()) {
// 判斷條件為,當(dāng)前宿主的Observer中如果有與宿主對象狀態(tài)不一致,才會進(jìn)入循環(huán)體,如果一致,則不處理
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
// 判斷宿主當(dāng)前的狀態(tài)是否比 Observer的狀態(tài)小,如果是,則原來注冊的Observer狀態(tài)回退
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
// 如果Observer狀態(tài)新加入,則需要將新加進(jìn)來的Observer對齊宿主狀態(tài)
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
// 狀態(tài)回退
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));
// 遞歸調(diào)用事件處理
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
// 狀態(tài)前進(jìn),保持與宿主狀態(tài)對齊
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();
}
}
}
// 根據(jù)不同的事件,事件回退
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);
}
// 事件前進(jìn)
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);
}