一、前言
Lifecycle 生命周期感知控件屬于谷歌在2018推出Android jetpack(外網(wǎng))其中的軟件架構(gòu)組件中的一個也榄。在谷歌開發(fā)者網(wǎng)站有介紹Lifecycle(外網(wǎng))趟脂。本文指在介紹Lifecycle的使用。讓你快速理解并上手Lifecycle庫抢韭。雖然Lifecycle很簡單薪贫,但我們還是應該仔細品一品。因為jetpack中太多庫依賴這種聲明周期管理了刻恭。
二瞧省、Lifecycle
谷歌爸爸是這么說的:生命周期感知型組件可執(zhí)行操作來響應另一個組件(如 Activity 和 Fragment)的生命周期狀態(tài)的變化。這些組件有助于您寫出更有條理且往往更精簡的代碼鳍贾,這樣的代碼更易于維護鞍匾。
簡單理解下:把聲明周期用觀察者模式來監(jiān)聽。把以前跟聲明周期相關(guān)操作代碼提出來寫骑科。
在介紹Lifecycle的兩種用法前橡淑,我們需要先導入。其它用法請參看Lifecycle 版本說明(外網(wǎng))
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
基本使用
三個步驟就可以使用起來了咆爽,就是普通觀察者模式的三個步驟梁棠。
1、創(chuàng)建一個被觀察者Lifecycle
對象
2伍掀、創(chuàng)建一個或多個觀察者LifecycleObserver對象
3掰茶、Lifecycle.addObserver把一個或多個LifecycleObserver觀察者添加
第一步:創(chuàng)建Lifecycle
public class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
protected void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLifecycleRegistry.markState(Lifecycle.State.DESTROYED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
- Lifecycle是一個抽象類,LifecycleRegistry就是它的一個具體實現(xiàn)
- LifecycleOwner接口蜜笤,就定義了一個getLifecycle濒蒋,方便獲取被觀察者。它存在的意義表示你的Activity或者Fragement具有Lifecycle特性把兔。很多依賴Lifecycle的組件就是通過這里來判斷的沪伙。
- mLifecycleRegistry.markState為了綁定狀態(tài),綁定了才好通知觀察者
第二步:創(chuàng)建LifecycleObserver觀察者
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destroy() {
}
}
- LifecycleObserver是一個空接口县好,目的是為了方便注解使用
第三步:添加觀察者
mLifecycleRegistry.addObserver(new MyObserver());
if (mLifecycleRegistry.getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
// do...
}
- addObserver添加就能監(jiān)聽了
- getCurrentState().isAtLeast提供了狀態(tài)的查詢
State和Event對應關(guān)系
三個步驟就完了围橡,比較簡單。細心的同學發(fā)現(xiàn)了缕贡,我們mark的時候狀態(tài)是Lifecycle.State
翁授。而在觀察者狀態(tài)是Lifecycle.Event
那么他們的對應關(guān)系如下圖:
常規(guī)情況
上面講的用法是我們使用的普通的Activity
拣播,而實際開發(fā)的時候,我們經(jīng)常使用的是MainActivity extends AppCompatActivity
而AppCompatActivity
已經(jīng)默認為我們實現(xiàn)了Lifecycle收擦。所以我們可以少些上面的第一步直接在MainActivity
中使用getLifecycle()
獲取被觀察者Lifecycle對象
再者如果你引用的是androidx中的Activity和Fragment他們也實現(xiàn)了Lifcycle的代碼贮配。
三、原理
對原理沒興趣的同學可以直接跳過這一節(jié)塞赂。
Lifecycle的運行機制也比較簡單泪勒,無非就是觀察者模式的慣用套路。我們也按步驟來解析
先看LifecycleRegistry.java
@Deprecated
@MainThread
public void markState(@NonNull State state) {
setCurrentState(state);
}
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
private void moveToState(State next) {
...
sync();
...
}
private void sync() {
...
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;
}
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();
}
}
}
- 1.我們再Activity里調(diào)用martState的時候就是響應的時候
- 2.根據(jù)martState的調(diào)用順序宴猾,最后走到了
backwardPass
和forwardPass
他們類似 - 3.在forwardPass里圆存,它遍歷了觀察者,調(diào)用了觀察者的dispatchEvent方法仇哆。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
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;
}
}
- 這里主要兩點
Lifecycling.lifecycleEventObserver
和onStateChanged
沦辙,而lifecycleEventObserver主要生成注解解析相關(guān)類
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...
return new ReflectiveGenericLifecycleObserver(object);
}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
通過反射調(diào)用就響應到了我們的方法上。
四税产、寫在最后
簡單的來看怕轿,Lifecycle通過觀察者模式獨立了生命周期的感知功能。一者方便了我們獨立的使用辟拷。二者也給一些需要生命周期感知的其它的組件提供了基礎(chǔ)撞羽。還是挺有意思的一個組件。