Lifecycle 框架是如何將 lifecycle 事件與 Android 組件的生命周期綁定的已脓?
LifecycleDispatcher,通過 ActivityLifecycleCallbacks驻仅、FragmentLifecycleCallbacks 及 Fragment 獲知 Activity谅畅、Fragment 的生命周期變化并產(chǎn)生相應(yīng)的 lifecycle 事件;
ProcessLifecycleOwner噪服,通過 ActivityLifecycleCallbacks 與 LifecycleDispatcher 配合監(jiān)聽當前進程中 Activities 的生命周期變化并在必要時產(chǎn)生相應(yīng)的 lifecycle 事件毡泻;
LifecycleService,通過重寫 Service 的生命周期方法并在相應(yīng)方法內(nèi)產(chǎn)生相應(yīng)的 lifecycle 事件粘优。
監(jiān)聽所有Activity的生命周期
Application中提供了一個ActivityLifecycleCallbacks接口黑低,并且維護了一個ArrayList<ActivityLifecycleCallbacks> mActivityLifecycleCallbacks列表锌妻,可通過實現(xiàn)ActivityLifecycleCallbacks接口并通過registerActivityLifecycleCallbacks()方法注冊,達到監(jiān)聽Activity生命周期的目的。
public interface ActivityLifecycleCallbacks {
void onActivityCreated(Activity activity, Bundle savedInstanceState);
void onActivityStarted(Activity activity);
void onActivityResumed(Activity activity);
void onActivityPaused(Activity activity);
void onActivityStopped(Activity activity);
void onActivitySaveInstanceState(Activity activity, Bundle outState);
void onActivityDestroyed(Activity activity);
}
Activity在執(zhí)行生命周期方法時争剿,會調(diào)用持有的Application的dispatchActivityXXX方法璃谨,在這個方法里曼氛,會遍歷注冊了生命周期監(jiān)聽的實例剂碴,執(zhí)行對應(yīng)的接口方法,達到通知的效果。典型的觀察者模式王财。
- Activity
protected void onCreate(Bundle savedInstanceState) {
getApplication().dispatchActivityCreated(this, savedInstanceState);
}
- Application
/* package */ void dispatchActivityCreated(Activity activity, Bundle savedInstanceState) {
Object[] callbacks = collectActivityLifecycleCallbacks();
if (callbacks != null) {
for (int i=0; i<callbacks.length; i++) {
((ActivityLifecycleCallbacks)callbacks[i]).onActivityCreated(activity,
savedInstanceState);
}
}
}
通過Lifecycle監(jiān)聽指定Activity的生命周期
項目中添加了lifecycle依賴后卵迂,編譯會在manifest中注冊初始化Lifecycle相關(guān)的provider。
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
// 只用于初始化
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
...
}
LifecycleDispatcher在初始化時會調(diào)用Application的registerActivityLifecycleCallbacks方法進行注冊绒净,監(jiān)聽所有的Activity见咒。
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
LifecycleDispatcher的靜態(tài)內(nèi)部類DispatcherActivityCallback實現(xiàn)了Application.ActivityLifecycleCallbacks接口,并在每個Activity的回調(diào)方法中獲取指定Activity的LifecycleRegistry實例挂疆,修改LifecycleRegistry的state改览,遍歷注冊了該Activity生命周期的Observer,通知Activity生命周期發(fā)生了變化缤言。
- DispatcherActivityCallback
private static void markStateIn(Object object, State state) {
if (object instanceof LifecycleRegistryOwner) {
LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
registry.markState(state);
}
}
- LifecycleRegistry
public void markState(@NonNull State state) {
moveToState(state);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
sync();
}
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
forwardPass(lifecycleOwner);
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
}
}
- FullLifecycleObserverAdapter
/**
* 狀態(tài)模式宝当,根據(jù)不同event執(zhí)行LifecycleObserver的不同方法
*/
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mObserver.onCreate(source);
break;
case ON_START:
mObserver.onStart(source);
break;
case ON_RESUME:
mObserver.onResume(source);
break;
case ON_PAUSE:
mObserver.onPause(source);
break;
case ON_STOP:
mObserver.onStop(source);
break;
case ON_DESTROY:
mObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
}