Lifecycle的原理

        Lifecycle是Android Architecture Components的成员,是一个生命周期感知组件,能够感知Activity、Fragment等组件的生命周期变化,并将变化通知到已注册的观察者。正确的使用有助于更好地组织代码,减少内存泄漏,增强稳定。下面分析他的实现原理,看看到底只怎么感知生命周期的。

一、基本使用

1、引入依赖库

dependencies {
    def lifecycle_version = "2.5.0-alpha01"
    def arch_version = "2.1.0"

    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
  
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

    //非java8使用
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" 
    //java8使用
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"  
}

2、自定义一个类实现LifecycleObserver,在类中监听生命周期回调

public class BaseJsApi implements LifecycleObserver {

  
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void create() {
        onCreate();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroy() {
        onDestroy();
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void resume() {
        onResume();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pause() {
        onPause();
    }

    ……………………………………

  }

3、在Activity或者fragment中注册。

 getLifecycle().addObserver(getJsBridge());

通过以上两步就可以感知当前Activity的生命周期了,非常的简便实用。

二、LifecycleObserver接口和LifecycleOwner接口

public interface LifecycleObserver {

}

public interface LifecycleOwner {
  @NonNull
  Lifecycle getLifecycle();
}

        LifecycleObserver是一个空接口,LifecycleOwner提供getLifecycle返回Lifecycle,该接口由ComponentActivity实现,提供了getLifecycle的实现。

三、getLifecycle()

        getLifecycle方法实际上是调用的ComponentActivity的getLifecycle方法,通过查看,Activity确实也是继承的ComponentActivity,该方法返回mLifecycleRegistry对象,该对象继承自Lifecycle,具体实现了添加观察者,移出观察者的方法,还定义了一个生命周期的枚举。

public class LifecycleRegistry extends Lifecycle {
  

}

public abstract class Lifecycle {

    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    @NonNull
    public abstract State getCurrentState();

    public enum Event {
       
        ON_CREATE,
       
        ON_START,
        
        ON_RESUME,
        
        ON_PAUSE,
        
        ON_STOP,
        
        ON_DESTROY,
       
        ON_ANY;
        …………………………………………
      }
      ………………………………
}

        也就可以看出getLifecycle().addObserver实际上就是执行LifecycleRegistry的addObserver的方法添加观察者,做一个小总结如下:

  1. 观察者实现LifecycleObserver,实现需要的生命周期。
  2. 在Activity、Fragment中添通过getLifecycle().addObserver加观察者。
  3. 实际上调用的是ComponentActivity的getLifecycle方法返回mLifecycleRegistry。
  4. 调用LifecycleRegistry的addObserver加观察者。

三、添加观察者的流程

        详情看注释:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    //检查是否在主线程
    enforceMainThreadIfNeeded("addObserver");
    //设置状态值
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    //将观察者和初始化的值封装到ObserverWithState中
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    //以观察者为key,statefulObserver为value放到hashMap集合中
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    //不为null表示之前已经放进去了,否则没放进去,放进去了就添加结束
    if (previous != null) {
        return;
    }
    //获取被观察者对象,即Activity,如果被销毁了,则结束
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        return;
    }

    //mAddingObserverCounter 表示正在添加的观察者的数量,
    //开始添加新的observe之前,对该变量进行++操作,添加完成后,进行--操作。
    //mHandlingEvent表示是否正在处理
    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    //计算状态,进行while循环
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    //新添加的LifecycleObserver ,会不断更新自己的生命周期到指定的targetState
    while ((statefulObserver.mState.compareTo(targetState) < 0
            && mObserverMap.contains(observer))) {
        //添加状态到list,计算当前状态,用于计算状态calculateTargetState
        pushParentState(statefulObserver.mState);
        //
        final Event event = Event.upFrom(statefulObserver.mState);
        if (event == null) {
            throw new IllegalStateException("no event up from " + statefulObserver.mState);
        }
        //生命周期分发:分发到mLifecycleObserver里面
        statefulObserver.dispatchEvent(lifecycleOwner, event);
        //移除状态到list
        popParentState();
        // mState / subling may have been changed recalculate
        //重新计算状态
        targetState = calculateTargetState(observer);
    }
    //没有事件正在处理,或者是添加了observe,就需要重新同步一次状态,下面详细介绍
    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}
//计算状态规则
private State calculateTargetState(LifecycleObserver observer) {
    //在map中获取到当前observer的前一个observer
    Map.Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
    //前一个observer的state
    State siblingState = previous != null ? previous.getValue().mState : null;
    //如果是嵌套添加observer,获取父级observer的状态
    State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
            : null;
    //获取最小状态,DESTROYED < INITIALIZED < CREATED < STARTED < RESUMED
    return min(min(mState, siblingState), parentState);
}

四、绑定生命周期

        上面介绍了addObserver的流程,在ComponentActivity的onCreate方法中:

ReportFragment.injectIfNeededIn(this);

        ReportFragment是一个Fragment,它负责分派生命周期的事件,injectIfNeededIn()就是在当前的Activity里添加一个ReportFragment,和glide的绑定生命周期比较类似。

public static void injectIfNeededIn(Activity activity) {
    //当API>=29注册registerIn绑定生命周期
    if (Build.VERSION.SDK_INT >= 29) {
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        LifecycleCallbacks.registerIn(activity);
    }
    android.app.FragmentManager manager = activity.getFragmentManager();
    if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
        // Hopefully, we are the first to make a transaction.
        manager.executePendingTransactions();
    }
}

         当API>=29是通过Application.ActivityLifecycleCallbacks的方式注册生命周期, 以onStart为例,其他onResume、onPause等类似:

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

         重点看看dispatch:

private void dispatch(@NonNull Lifecycle.Event event) {
    //当API<29分发dispatch绑定生命周期
    if (Build.VERSION.SDK_INT < 29) {
        // Only dispatch events from ReportFragment on API levels prior
        // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
        // added in ReportFragment.injectIfNeededIn
        dispatch(getActivity(), event);
    }
}

        不管是pplication.ActivityLifecycleCallbacks还是当前fragment的生命周期方式都会执行如下dispatch:

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

        调用LifecycleRegistry的handleLifecycleEvent将生命周期分发出去,LifecycleRegistry上面已经介绍过了addObserve逻辑了,代码比较长,只显示关键代码:

handleLifecycleEvent -> moveToState -> sync

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) {
            //如果ObserverWithState的state小于当前state,那么就调用forwardPass方法,
            backwardPass(lifecycleOwner);
        }
        Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            //如果大于当前state,那么就调用backwardPass方法。
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

        backwardPass和forwardPass的代码都会调用:

observer.dispatchEvent(lifecycleOwner, event)

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 = event.getTargetState();
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

        调用了Lifecycling.getCallback方法来获得mLifecycleObserver的实例,通过这个实例调用onStateChanged:

static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }
    //通过反射,找到Lifecycle 自动生成的类
    final Class<?> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List<Constructor<? extends GeneratedAdapter>> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            最终使用生成的Adapter,创建SingleGeneratedAdapterObserver
            return new SingleGeneratedAdapterObserver(generatedAdapter);
        }
        GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = createGeneratedAdapter(constructors.get(i), object);
        }
        return new CompositeGeneratedAdaptersObserver(adapters);
    }
    return new ReflectiveGenericLifecycleObserver(object);
}
class SingleGeneratedAdapterObserver implements LifecycleEventObserver {

    private final GeneratedAdapter mGeneratedAdapter;

    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}

        到这里会根据依赖中添加的annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"根据不同生命周期注解生成不同的类,整个过程还是比较复杂的。整体过程如下图:

Lifecycle的原理

上一篇:javascript – 基于背景图像颜色自动对比文本颜色


下一篇:设计模式之观察者模式(C语言)