[Android] Lifecycle总结

Lifecycle 框架是如何将 lifecycle 事件与 Android 组件的生命周期绑定的?

  • LifecycleDispatcher,通过 ActivityLifecycleCallbacks、FragmentLifecycleCallbacks 及 Fragment 获知 Activity、Fragment 的生命周期变化并产生相应的 lifecycle 事件;

  • ProcessLifecycleOwner,通过 ActivityLifecycleCallbacks 与 LifecycleDispatcher 配合监听当前进程中 Activities 的生命周期变化并在必要时产生相应的 lifecycle 事件;

  • LifecycleService,通过重写 Service 的生命周期方法并在相应方法内产生相应的 lifecycle 事件。

监听所有Activity的生命周期

Application中提供了一个ActivityLifecycleCallbacks接口,并且维护了一个ArrayList mActivityLifecycleCallbacks列表,可通过实现ActivityLifecycleCallbacks接口并通过registerActivityLifecycleCallbacks()方法注册,达到监听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在执行生命周期方法时,会调用持有的Application的dispatchActivityXXX方法,在这个方法里,会遍历注册了生命周期监听的实例,执行对应的接口方法,达到通知的效果。典型的观察者模式。

  • 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

通过Lifecycle监听指定Activity的生命周期

项目中添加了lifecycle依赖后,编译会在manifest中注册初始化Lifecycle相关的provider。

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        // 只用于初始化
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }
    ...
}

LifecycleDispatcher在初始化时会调用Application的registerActivityLifecycleCallbacks方法进行注册,监听所有的Activity。

static void init(Context context) {
    if (sInitialized.getAndSet(true)) {
        return;
    }
    ((Application) context.getApplicationContext())
            .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}

LifecycleDispatcher的静态内部类DispatcherActivityCallback实现了Application.ActivityLifecycleCallbacks接口,并在每个Activity的回调方法中获取指定Activity的LifecycleRegistry实例,修改LifecycleRegistry的state,遍历注册了该Activity生命周期的Observer,通知Activity生命周期发生了变化。

  • 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> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
    }
}
  • FullLifecycleObserverAdapter
/**
 * 状态模式,根据不同event执行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");
    }
}

你可能感兴趣的:([Android] Lifecycle总结)