目錄
問題
在使用Android Architecture Component的時候谚攒,Lifecycle的存在感是最低的腰耙,因為AppCompat包已經(jīng)幫我們實現(xiàn)了Activity和Fragment的Lifecycle。Lifecycle最主要的作用是抽象生命周期枪芒,讓包括LiveData在內(nèi)的觀察者實現(xiàn)對生命周期的感知彻况。關(guān)于Lifecycle,我能想到如下一些問題:
- 什么是Lifecycle舅踪?
- 怎樣以無侵入的方式實現(xiàn)Lifecycle纽甘?
- 我們經(jīng)常使用Activity和Fragment的Lifecycle,按道理說抽碌,Application也有Lifecycle悍赢,該怎么實現(xiàn)它的Lifecycle?
帶著這些問題货徙,去源碼中找尋答案左权。(源碼版本androidx.lifecycle:lifecycle-runtime:2.2.0
)
1. Lifecycle概覽
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
Lifecycle是一個持有組件生命周期狀態(tài)的類,它允許其它類來觀察這種的狀態(tài)痴颊。說白了就是讓Activity赏迟、Fragment之類的生命周期狀態(tài)“轉(zhuǎn)移”到Lifecycle類中,因此我們就可以通過Lifecycle類去觀察生命周期蠢棱,完成相應(yīng)的行為锌杀。
但是,為什么要這么做呢泻仙?在Activity或者Fragment生命周期函數(shù)中完成我們想要的行為不也一樣嗎抛丽?
首先,使用Lifecycle一個顯而易見的好處就是解耦饰豺。假設(shè)我們需要在Activity的onStart
方法中去觸發(fā)十個八個行為,并且在onStop
方法中去停止這些行為允蜈,如果把這些代碼都堆在Activity的生命周期的方法中冤吨,顯然是非常丑陋的蒿柳。使用Lifecycle,我們可以為每一個行為定義一個觀察者類漩蟆,再讓這十個八個觀察者類去觀察Lifecycle垒探,這樣代碼結(jié)構(gòu)會清晰很多,并且也更加符合單一職責(zé)原則怠李。
其次圾叼,使用Lifecycle可以更加方便地處理一些生命周期狀態(tài)和用戶狀態(tài)相互影響的情況。Google文檔中給出了一個例子捺癞。
最后夷蚊,Lifecycle的抽象給LiveData的實現(xiàn)提供了便利。
2. 什么是Lifecycle
/**
* Lifecycle的注釋中有兩個重要信息:
* 1. ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相應(yīng)方法之后才發(fā)出的.
* ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相應(yīng)方法之前就發(fā)出的.
* 這是為了保證 LifecycleOwner 的確切狀態(tài)髓介。
* 2. 相較于使用 OnLifecycleEvent 注解的方式去定義 LifecycleObserver惕鼓,
* 你應(yīng)該更加傾向于使用 DefaultLifecycleObserver(包含在 androidx.lifecycle:common-java8 中)
* 在Java 8成為Android主流之后,使用注解的方式就會被廢棄唐础。
*/
public abstract class Lifecycle {
/**
* 添加觀察者
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
*/
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
/**
* 移除觀察者
* Removes the given observer from the observers list.
* <p>
* If this method is called while a state change is being dispatched,
* <ul>
* <li>If the given observer has not yet received that event, it will not receive it.
* <li>If the given observer has more than 1 method that observes the currently dispatched
* event and at least one of them received the event, all of them will receive the event and
* the removal will happen afterwards.
* </ul>
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
}
/**
* LifecycleObserver只是一個標(biāo)記接口箱歧,沒有方法
* 可以使用 OnLifecycleEvent 注解去定義 LifecycleObserver
* 但是,如前所述一膨,更應(yīng)該使用 Java 8 的 DefaultLifecycleObserver 去實現(xiàn)
*/
public interface LifecycleObserver {
}
/**
* 與 Lifecycle有關(guān)的 LifecycleOwner接口
*/
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
Lifecycle就是這么簡單呀邢,總結(jié)起來就是:一、有狀態(tài)豹绪;二价淌、可以增刪觀察者。另外Lifecycle類中還定義了State和Event:
public abstract class Lifecycle {
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
State和Event的關(guān)系如圖所示:
LifecycleOwner,Lifecycle,LifecycleObserver關(guān)系如圖所示:
圖片來源https://blog.kyleduo.com/2019/01/17/lifecycle-source-code/
3. Activity和Fragment如何實現(xiàn)Lifecycle
AppCompat包從26.1.0開始森篷,就已經(jīng)幫我們在Activity和Fragment中實現(xiàn)了LifecycleOwner接口输钩。androidx包下的Activity和Fragment自然就更不用說了。
3.1 Activity如何實現(xiàn)Lifecycle
盡管我們使用了AppCompat包仲智,但是并不能保證應(yīng)用中所有的Activity一定繼承自AppCompatActivity(例如买乃,使用的第三方庫中的Activity沒有繼承自AppCompatActivity),因此就不能直接在AppCompatActivity或者其某個基類的生命周期方法中去實現(xiàn)Lifecycle钓辆。Google的做法是向Activity中添加一個看不見的Fragment剪验,名為ReportFragment,專門向Activity“報告”當(dāng)前的生命周期前联,這樣就保證了所有Activity的生命周期都會通過ReportFragment被“報告”功戚。由于不能確定Activity的具體類型,因此ReportFragment必須繼承自android.app.Fragment似嗤,不能使用兼容包下的Fragment啸臀。
按理說,對于沒有繼承自兼容包的Activity,是完全有理由放棄為其實現(xiàn)Lifecycle的乘粒,因為即使使用了ReportFragment豌注,也僅僅保證了Activity的生命周期被正常的“報告”,這個Activity并沒有實現(xiàn)LifecycleOwner接口灯萍,這導(dǎo)致ReportFragment的“報告”沒有辦法被獲取轧铁,因此,使用ReportFragment并不是為了讓所有的Activity都實現(xiàn)Lifecycle旦棉。其實齿风,這么做是為了讓Application能正確的實現(xiàn)Lifecycle,這一點后面的源碼中會有體現(xiàn)绑洛。
/**
* AppCompatActivity的基類救斑,實現(xiàn)了LifecycleOwner接口
*/
public class ComponentActivity implements LifecycleOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//injectIfNeededIn 如果需要就注入
ReportFragment.injectIfNeededIn(this);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
LifecycleOwner的實現(xiàn)非常簡單,把一切都交給了LifecycleRegistry诊笤,看來LifecycleRegistry才是關(guān)鍵系谐。LifecycleRegistry是實現(xiàn)Lifecycle的關(guān)鍵,待我們把相關(guān)的源碼看完之后讨跟,再回過頭來看LifecycleRegistry纪他。
ReportFragment在onCreate方法中被添加到Activity中,并且是通過ReportFragment的靜態(tài)方法injectIfNeededIn
晾匠,需要才添加茶袒。那還有不需要的時候嗎?前面說了凉馆,你的Activity并不一定會繼承自這個ComponentActivity薪寓,如果Activity不繼承自這個ComponentActivity,ReportFragment依然會被添加澜共,只是不是通過這里被添加的(后文會講到)向叉,為了防止Activity重復(fù)添加ReportFragment,因此ReportFragment實現(xiàn)了靜態(tài)方法injectIfNeededIn
嗦董。好吧母谎,來瞄一眼ReportFragment吧。
//繼承自android.app.Fragment
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
//如果沒有添加過ReportFragment才進(jìn)行添加
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// API 29+ 流程略有不同京革,并不影響主流程奇唤,可以忽略
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
//不使用兼容包下的FragmentManager
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@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 onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
}
private void dispatch(Lifecycle.Event event) {
dispatch(getActivity(), event);
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
ReportFragment的職責(zé)非常簡單,在對應(yīng)的生命周期中分發(fā)對應(yīng)的事件給Activity的LifecycleRegistry匹摇。
Lifecycle的注釋中提到
ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相應(yīng)方法之后才發(fā)出的.
ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相應(yīng)方法之前就發(fā)出的.
頭一句沒有問題咬扇,第二句話似乎跟代碼不符,ReportFragment明明是在onPause
,onStop
,onDestroy
方法之后才分發(fā)的對應(yīng)的事件廊勃。但是別忘了懈贺,ReportFragment是為了監(jiān)聽Activity的生命周期,ReportFragment的onPause
,onStop
,onDestroy
確實是在Activity對應(yīng)方法之前被調(diào)用的,因為ReportFragment是android.app.Fragment隅居,如果是兼容包的Fragment钠至,其onPause
,onStop
,onDestroy
是在Activity對應(yīng)方法之后被調(diào)用,我也是剛剛發(fā)現(xiàn)胎源。
總結(jié)一下,Activity是如何實現(xiàn)Lifecycle的屿脐。ReportFragment被添加到Activity中涕蚤,并在ReportFragment相應(yīng)的生命周期方法中,通知Activity的LifecycleRegistry相應(yīng)的事件的诵。
3.2 Fragment如何實現(xiàn)Lifecycle
從Android P開始万栅,android.app.Fragment已經(jīng)被標(biāo)記為廢棄的,顯然Google已經(jīng)不推薦我們使用“原生”的Fragment西疤,相反烦粒,我們應(yīng)該使用兼容包中的Fragment。android.app.Fragment也沒有實現(xiàn)Lifecycle代赁,我們只需要看兼容包中的Fragment是如何實現(xiàn)Lifecycle的即可扰她。
//androidx.fragment.app.Fragment
public class Fragment implements LifecycleOwner {
LifecycleRegistry mLifecycleRegistry;
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
//...
}
/**
* 先調(diào)用Fragment的onCreate,然后發(fā)送ON_CREATE事件
*/
void performCreate(Bundle savedInstanceState) {
//...
onCreate(savedInstanceState);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
//...
}
/**
* 先發(fā)送ON_DESTROY事件芭碍,然后調(diào)用Fragment的onDestroy
*/
void performDestroy() {
//...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
onDestroy();
//...
}
//其它生命周期類似徒役,不再列出
}
比Activity還要簡單,直接在相應(yīng)的生命周期中通知LifecycleRegistry即可窖壕。并且Fragment的源碼再次印證了Lifecycle注釋中的那句話:
ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相應(yīng)方法之后才發(fā)出的.
ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相應(yīng)方法之前就發(fā)出的.
通過分析Activity和Fragment中的源碼可以看出忧勿,Lifecycle真正的實現(xiàn)是在LifecycleRegistry中。
4. Lifecycle的本尊LifecycleRegistry
兜兜轉(zhuǎn)轉(zhuǎn)還得回到LifecycleRegistry瞻讽。在分析LifecycleRegistry源碼之前鸳吸,先明確一下LifecycleRegistry的職責(zé):
- 持有生命周期的狀態(tài)。
- 接收生命周期事件速勇,完成在生命周期狀態(tài)之間的跳轉(zhuǎn)晌砾。
- 可以添加多個觀察者,并且可以隨時移除觀察者快集。
- 向多個觀察者傳遞生命周期事件贡羔,維護(hù)多個觀察者的生命周期狀態(tài)。
以上職責(zé)大致分為兩部分:第一个初,觀察者的添加和移除乖寒;第二,生命周期狀態(tài)的管理院溺,包括LifecycleRegistry本身的生命周期狀態(tài)和觀察者的生命周期狀態(tài)(注意區(qū)分兩者)楣嘁。
4.1 LifecycleRegistry觀察者的添加和移除
public class LifecycleRegistry extends Lifecycle {
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*
* Invariant: at any moment of time for observer1 & observer2:
* if addition_order(observer1) < addition_order(observer2), then
* state(observer1) >= state(observer2)
*
* 以上這段話非常重要,先添加的觀察者observer1的狀態(tài)state1,永遠(yuǎn)要比
* 后添加的觀察者observer2的狀態(tài)state2大逐虚,即state1 >= state2
* 或者表達(dá)為state(observer1) >= state(observer2)
* 這被稱為“不變性”
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
/**
* 當(dāng)前的 state
*/
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
//記錄是否正在添加觀察者
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
// we have to keep it for cases:
// void onStart() {
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
// 舉了一個例子來說明 parentStates的作用
private ArrayList<State> mParentStates = new ArrayList<>();
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* 計算目標(biāo)State
* 由于要保持“不變性”聋溜,被計算的observer的State必要小于等于mState及在它之前添加的觀察者的State
*/
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
/**
* 添加觀察者,核心是把觀察者的狀態(tài)驅(qū)動到目標(biāo)狀態(tài)
*/
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//我們定義的LifecycleObserver只關(guān)心事件發(fā)生后的行為叭爱,并沒有保存狀態(tài)
//因此做一層包裝撮躁,做個有狀態(tài)的觀察者,ObserverWithState的定義在下方
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//putIfAbsent买雾,如果之前沒有添加過就添加把曼,添加過則返回之前的對象
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
//如果正在添加觀察者或者正在處理事件
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
//新添加的observer的state被驅(qū)動到目標(biāo)state
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
/**
* 移除觀察者,詳細(xì)闡述了為什么移除觀察者的時候沒有發(fā)送“反向”的事件
*/
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
// we consciously decided not to send destruction events here in opposition to addObserver.
// Our reasons for that:
// 1. These events haven't yet happened at all. In contrast to events in addObservers, that
// actually occurred but earlier.
// 2. There are cases when removeObserver happens as a consequence of some kind of fatal
// event. If removeObserver method sends destruction events, then a clean up routine becomes
// more cumbersome. More specific example of that is: your LifecycleObserver listens for
// a web connection, in the usual routine in OnStop method you report to a server that a
// session has just ended and you close the connection. Now let's assume now that you
// lost an internet and as a result you removed this observer. If you get destruction
// events in removeObserver, you should have a special case in your onStop method that
// checks if your web connection died and you shouldn't try to report anything to a server.
mObserverMap.remove(observer);
}
/**
* 做個有狀態(tài)的觀察者
*/
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//我們定義的observer又被轉(zhuǎn)換了一下子
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
其實漓穿,添加和移除觀察者是件簡單的事情嗤军,我們通常的做法是把觀察者放入一個List中,但是在這里是行不通的晃危,因為觀察者可能隨時被移除叙赚,在遍歷觀察者通時,有的觀察者可能就被移除了僚饭,這顯然需要使用鏈表去完成震叮。而保存觀察者的容器FastSafeIterableMap就是這么一個底層以鏈表實現(xiàn),表面上卻像個Map的鏈表浪慌,其實現(xiàn)比較簡單冤荆,感興趣可以去看一下。
如果只是個簡單的觀察者权纤,我們把它加到容器中也就可以了钓简,但是這里真正的觀察者是有狀態(tài)的,新進(jìn)的觀察者在被添加到容器中時汹想,需要被驅(qū)動到目標(biāo)狀態(tài)外邓。再加上觀察者可能隨時被添加進(jìn)來,譬如古掏,在事件正分發(fā)的時候损话。所有這些情況綜合在一起就使得添加觀察者的代碼變得比較復(fù)雜。
其中最難理解的應(yīng)該是mParentStates
的作用槽唾,注釋中給了一種情況丧枪,大致意思是說,在ON_START
事件分發(fā)時庞萍,某個觀察者的onStart
方法中把自己給移除了拧烦,把另外一個觀察者添加進(jìn)去了(真尼瑪是騷操作),這時候應(yīng)該保證新添加的觀察者的正確目標(biāo)狀態(tài)钝计。嗯恋博,雖然很難理解齐佳,但是這并不是源碼的主線,我就姑且這么一說债沮,你就姑且那么一聽炼吴,就當(dāng)自己懂了。
4.2 LifecycleRegistry生命周期狀態(tài)的管理
把文中第一張圖旋轉(zhuǎn)一下疫衩,就會變成這個樣子
意思是狀態(tài)有上下之分硅蹦,這張圖有助于理解LifecycleRegistry生命周期狀態(tài)間的轉(zhuǎn)換。
public class LifecycleRegistry extends Lifecycle {
/**
* 直接設(shè)置當(dāng)前狀態(tài)隧土,主要作用是在onSaveInstanceState時候就把狀態(tài)設(shè)置為CREATED
* 為什么要這么做提针,Google文檔中有解釋
* https://developer.android.google.cn/topic/libraries/architecture/lifecycle
*/
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
/**
* 正常情況下會調(diào)用這個方法,發(fā)送事件并更改狀態(tài)
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
//正在處理Event事件曹傀,或者正在添加觀察者
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
/**
* 判斷所有觀察者是否已經(jīng)“同步”
* 同步的意思是所有的觀察者都處于相同的狀態(tài)
* 由之前說的“不變性”可知,最新的觀察者和最老的觀察者的狀態(tài)如果相等饲宛,則足以說明已經(jīng)同步
*/
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
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);
}
/**
* 從前向后改變狀態(tài)皆愉,由于要保持“不變性”,所以狀態(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();
}
}
}
/**
* 從后向前改變狀態(tài)艇抠,由于要保持“不變性”幕庐,所以狀態(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));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
// 把所有觀察者的狀態(tài)同步
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()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
}
要完成的事情很簡單,就是先改變LifecycleRegistry的狀態(tài)家淤,然后把狀態(tài)“同步”到所有的觀察者异剥。聽上去挺簡單的,但是狀態(tài)同步的途中有可能新的狀態(tài)又來了絮重,這時候所有觀察者的狀態(tài)只同步到了一半冤寿,你說咋辦,不上不下的青伤,所以才有了所謂的“不變性”督怜,“不變性”方便我們?nèi)ヅ袛嗍欠褚呀?jīng)同步完成,但是為了在任意時刻都保持這種“不變性”狠角,我們就需要在從前向后同步或者從后向前同步(取決于狀態(tài)的上下關(guān)系)号杠。妙啊,實在是妙胺岣琛姨蟋!
5. Application的Lifecycle
什么是Application的生命周期呢?這里并不是指Application類的存活周期立帖,而是指我們的應(yīng)用在前臺眼溶,或者被切換到后臺這種周期,或者說是Activity們的生命周期厘惦。表達(dá)為Application的生命周期并不準(zhǔn)確偷仿,你理解什么意思就好哩簿。我們已經(jīng)知道Activity的生命周期是通過ReportFragment被報告的,Application的生命周期也得通過ReportFragment來報告酝静,ReportFragment之前的代碼被我刪掉了一些東西节榜,現(xiàn)在回頭來看看:
public class ReportFragment extends Fragment {
private ActivityInitializationListener mProcessListener;
//以下三個方法就是為了通知Application生命周期的擁有者切換其狀態(tài)
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
可見ReportFragment在onCreate
,onStart
别智,onResume
中不僅通知了Activity宗苍,還通知了Application。至于為什么onPause
薄榛,onStop
讳窟,onDestroy
沒有通知Application,之后會說敞恋。
Application生命周期的擁有者:
/**
* Class that provides lifecycle for the whole application process.
* <p>
* You can consider this LifecycleOwner as the composite of all of your Activities, except that
* {@link Lifecycle.Event#ON_CREATE} will be dispatched once and {@link Lifecycle.Event#ON_DESTROY}
* will never be dispatched. Other lifecycle events will be dispatched with following rules:
* ProcessLifecycleOwner will dispatch {@link Lifecycle.Event#ON_START},
* {@link Lifecycle.Event#ON_RESUME} events, as a first activity moves through these events.
* {@link Lifecycle.Event#ON_PAUSE}, {@link Lifecycle.Event#ON_STOP}, events will be dispatched with
* a <b>delay</b> after a last activity
* passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner
* won't send any events if activities are destroyed and recreated due to a
* configuration change.
*
* <p>
* It is useful for use cases where you would like to react on your app coming to the foreground or
* going to the background and you don't need a milliseconds accuracy in receiving lifecycle
* events.
*
* 注釋說的很明白丽啡,總結(jié)起來就是這里的生命周期指的是Activity是否存在于前臺
* 第一個Activity onStart,onResume時就會發(fā)出ON_RESUME,ON_RESUME事件
* 最后一個Activity onPause,onStop之后一小段時間后就會發(fā)出ON_PAUSE,ON_STOP事件
* 開始時會發(fā)出一次ON_CREATE事件,ON_DESTROY事件不會發(fā)出
*/
public class ProcessLifecycleOwner implements LifecycleOwner {
//避免配置發(fā)生變化(屏幕旋轉(zhuǎn)等)時無謂的生命周期的變化
static final long TIMEOUT_MS = 700; //mls
// ground truth counters
private int mStartedCounter = 0;
private int mResumedCounter = 0;
private boolean mPauseSent = true;
private boolean mStopSent = true;
private Handler mHandler;
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
private Runnable mDelayedPauseRunnable = new Runnable() {
@Override
public void run() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
/**
* The LifecycleOwner for the whole application process. Note that if your application
* has multiple processes, this provider does not know about other processes.
*
* @return {@link LifecycleOwner} for the whole application.
*/
@NonNull
public static LifecycleOwner get() {
return sInstance;
}
//初始化
static void init(Context context) {
sInstance.attach(context);
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
private ProcessLifecycleOwner() {
}
void attach(Context context) {
mHandler = new Handler();
//一開始先變?yōu)镃REATED狀態(tài)
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
//為所有Activity注冊生命周期的回掉
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
//在Activity onPause方法之后被調(diào)用
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
}
這里解釋一下為什么不在ReportFragmentonPause
硬猫,onStop
补箍,onDestroy
中通知Application。答案很簡單啸蜜,沒有必要坑雅。因為有ActivityLifecycleCallbacks回掉,我們可以在那里面完成衬横,但是為什么又必須在ReportFragmentonCreate
裹粤,onStart
,onResume
中通知呢蜂林?因為ActivityLifecycleCallbacks相應(yīng)回掉是在對應(yīng)生命周期方法之后才被調(diào)用的遥诉,而這里想實現(xiàn)的是在這之前就發(fā)出事件。我的理解是悉尾,對于ON_RESUME
事件突那,通知順序是這樣的:Application->Activity;對于ON_PAUSE
事件构眯,通知順序是這樣的:Activity->Application愕难,其它事件類似。
ProcessLifecycleOwner是需要初始化的惫霸,并且需要盡早進(jìn)行猫缭,這是在ProcessLifecycleOwnerInitializer中完成的:
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
}
這是個ContentProvider,它的onCreate方法是要早于Application的onCreate方法的壹店,是個初始化的好地方猜丹,嗯,拿小本本記下來了硅卢。里面還有個LifecycleDispatcher射窒,必然跟Lifecycle有關(guān)藏杖,去看看
class LifecycleDispatcher {
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.injectIfNeededIn(activity);
}
}
private LifecycleDispatcher() {
}
}
果然,是為了添加ReportFragment脉顿,前面已經(jīng)說了蝌麸,不保證我們的Activity都繼承自兼容包,如果這樣的話艾疟,ReportFragment就不會被添加到Activity中来吩,你都不用兼容包了,看來你也是不想用Lifecycle了蔽莱,這倒無所謂弟疆,但是,ReportFragment還和Application的生命周期相關(guān)盗冷,不能因為哪個Activity沒用兼容包就導(dǎo)致Application的生命周期出現(xiàn)錯誤怠苔,所以還得保證ReportFragment被正確地添加到Activity中,LifecycleDispatcher就起到這個作用仪糖。
6. 隱藏技能
Lifecycle的源碼基本上分析完了嘀略,要完成的任務(wù)其實挺簡單的,但是實現(xiàn)起來還是挺復(fù)雜的乓诽。從源碼中我們可以發(fā)現(xiàn)一些隱藏的“技能”:
- 應(yīng)該盡量使用DefaultLifecycleObserver,而不是使用OnLifecycleEvent注解的方式咒程,因為后者會使用反射的方式來實現(xiàn)觀察者鸠天。
- Application在前后臺切換時也會有生命周期,我們可以通過ProcessLifecycleOwner去獲取帐姻。
- 監(jiān)聽Activity的生命周期有兩種方式稠集,第一注冊ActivityLifecycleCallbacks回調(diào),第二添加一個看不見的Fragment饥瓷,并且最好是android.app.Fragment剥纷,這樣適用性更廣。
- ContentProvider的onCreate方法比Application的onCreate方法還要早呢铆,可以初始化一些全局性的東西晦鞋,這樣就不必侵入到Application中。
- 如果遍歷一個集合的時候可能會增刪其中的元素棺克,應(yīng)該考慮使用鏈表的形式存儲悠垛。
Lifecycle源碼中最妙的點應(yīng)該是以“不變性”的方式實現(xiàn)觀察者狀態(tài)的管理∧纫辏可能通用性并不是那么強(qiáng)确买,看看就好,說不定哪天吹牛逼就用上了纱皆。
7. 總結(jié)
回答文章開頭提到的幾個問題:
- 什么是Lifecycle湾趾?
Lifecycle是一個持有組件生命周期狀態(tài)的類芭商,它允許其它類來觀察這種的狀態(tài)。 - 怎樣以無侵入的方式實現(xiàn)Lifecycle搀缠?
這里主要指怎樣以無侵入的方式實現(xiàn)Activity的Lifecycle铛楣。關(guān)鍵是使用ReportFragment,這個看不見的Fragment胡嘿,這樣既能監(jiān)聽Activity的生命周期又方便通知Activity這個LifecycleOwner蛉艾。 - 我們經(jīng)常使用Activity和Fragment的Lifecycle,按道理說衷敌,Application也有Lifecycle勿侯,該怎么實現(xiàn)它的Lifecycle?
通過ProcessLifecycleOwner去實現(xiàn)缴罗。其實助琐,Service也有生命周期,實現(xiàn)類是LifecycleService面氓,代碼很簡單兵钮,這里就不展開分析了。
Lifecycle源碼思想總結(jié):
Android中擁有生命周期的類有很多舌界,以Activity和Fragment最為常見掘譬、典型。Lifecycle的核心思想在于呻拌,盡量少的侵入到擁有生命周期的類中葱轩,而把生命周期內(nèi)聚到Lifecycle
類中,Activity藐握、Fragment等被抽象為了LifecycleOwner
靴拱。
作為核心的Lifecycle
既是Activity、Fragment等生命周期的觀察者猾普,又是LifecycleObserver
的被觀察者袜炕。它既需要接收來自Activity、Fragment的生命周期事件初家,改變自己的狀態(tài)偎窘,又需要把這種狀態(tài)同步給自己所有的LifecycleObserver
。為了適應(yīng)事件分發(fā)笤成、觀察者增減交織嵌套等等的復(fù)雜性评架,LifecycleRegistry
以一種“不變性”的方式來存儲和管理所有的LifecycleObserver
,既簡單又非常巧妙炕泳。
參考
Lifecycle源碼分析這篇文章比較詳細(xì)地解釋了LifecycleRegistry狀態(tài)同步的一些細(xì)節(jié)纵诞,寫得很好。