LifeCycle
總體來(lái)說LifeCycle組件使用分為三個(gè)部分:
LifecycleRegistry LifeCycle子類
LifecycleOwner 被觀察者
LifecycleObserver 觀察者
先貼一下代碼
LifecycleOwner
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyLifeCycle myLifeCycle = new MyLifeCycle();
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
mLifecycleRegistry.addObserver(myLifeCycle);
}
@Override
protected void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@Override
protected void onPause() {
super.onPause();
}
}
看到以上代碼主要分為幾個(gè)步驟:
- 對(duì)接LifecycleOwner接口
- 實(shí)例化LifecycleRegistry, 這個(gè)LifecycleRegistry類其實(shí)是LifeCycle的子類
- 實(shí)例化觀察者
- 將觀察者注入LifecycleRegistry
- 添加生命周期標(biāo)記
LifecycleObserver
public class MyLifeCycle implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
protected void myCreate(){
Log.d("test", "myCreate: 已啟動(dòng)");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void MyStart(){
Log.d("test", "myStart: 已開始");
}
}
看到以上代碼主要分為幾個(gè)步驟:
- 對(duì)接LifecycleObserver接口
- 根據(jù)標(biāo)記的生命周期進(jìn)行方法的實(shí)現(xiàn)即可
LifeCycle類源代碼
public abstract class Lifecycle {
//注冊(cè)LifecycleObserver (比如Presenter)
public abstract void addObserver(@NonNull LifecycleObserver observer);
//移除LifecycleObserver
public abstract void removeObserver(@NonNull LifecycleObserver observer);
//獲取當(dāng)前狀態(tài)
public abstract State getCurrentState();
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和我們平時(shí)說的生命周期略有不同,我的理解是,不是所有生命周期都是直接觀察的岔冀,比如說onPause,但是為什么不能添加onPause的狀態(tài)標(biāo)記卻可以在觀察者中實(shí)現(xiàn)方法呢使套,可能是因?yàn)楫?dāng)被觀察者執(zhí)行到下一個(gè)可直接觀察狀態(tài)時(shí),其實(shí)之前的狀態(tài)已經(jīng)觀察到了嫉柴,就直接在所到之處執(zhí)行了,但事實(shí)是有的會(huì)執(zhí)行奉呛,有的不會(huì)執(zhí)行夯尽,目前沒找到明確的解釋匙握。