Jetpack-Lifecycle源码解析

Lifecycle源码解析

源码版本:

  • Lifecycle:2.4.0
  • androidx.activity:activity:1.4.0
  • androidx.fragment:fragment:1.4.0

导航:

  • Jetpack-Lifecycle源码解析
  • Jetpack-LiveData源码解析
  • Jetpack-ViewModel源码详解
  • 更多的文章看这里:主页

使用

声明LifecycleObserver

1. DefaultLifecycleObserver

生命周期状态改变时,会调用对应的方法。可根据需要,重写某个方法。

val lifecycleObserver = object : DefaultLifecycleObserver {

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
    }
}

2. LifecycleEventObserver

生命周期状态改变时,会调用onStateChanged方法。

val lifecycleObserver = object : LifecycleEventObserver {

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        
    }
}

3. OnLifecycleEvent(已弃用)

生命周期状态改变时,会调用LifecycleObserver子类被对应event标注的方法。使用OnLifecycleEvent注解标注方法上,方法要求:方法名称任意,方法参数可无可1个(必须是LifecycleOwner)、可2个(必须先后是LifecycleOwnerLifecycle.Event、且event必须是Lifecycle.Event.ON_ANY)。

val lifecycleObserver = object : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume(owner: LifecycleOwner) {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onAny(owner: LifecycleOwner, event: Lifecycle.Event) {
    }
}

添加观察者

lifecycle.addObserver(lifecycleObserver)

移除观察者

lifecycle.removeObserver(lifecycleObserver)

获取当前状态

val state = lifecycle.currentState

源码

声明LifecycleObserver

1. DefaultLifecycleObserver

DefaultLifecycleObserver接口

public interface DefaultLifecycleObserver extends FullLifecycleObserver {
    @Override
    default void onCreate(@NonNull LifecycleOwner owner) {}
    
    @Override
    default void onStart(@NonNull LifecycleOwner owner) {}
    
    @Override
    default void onResume(@NonNull LifecycleOwner owner) {}
    
    @Override
    default void onPause(@NonNull LifecycleOwner owner) {}
    
    @Override
    default void onStop(@NonNull LifecycleOwner owner) {}
    
    @Override
    default void onDestroy(@NonNull LifecycleOwner owner) {}
}

DefaultLifecycleObserver接口对FullLifecycleObserver接口进行了默认实现,所以可以按需实现某个方法。由于此接口方法使用default,这一特性是从 Java 8才开始有的,所以需要配置以 Java 8及以上作为编译版本才可以使用。

FullLifecycleObserver接口

interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}

生命周期状态改变时,会调用对应的方法(调用逻辑后面讲)。FullLifecycleObserver接口不是public的,所以不能使用,推荐使用DefaultLifecycleObserver

LifecycleObserver接口

public interface LifecycleObserver {

}

LifecycleObserver是一个空接口,用于标记可以被Lifecycle添加、删除。可以使用它的子接口DefaultLifecycleObserverLifecycleEventObserverOnLifecycleEvent(已弃用)标注方法的子类,来通知生命周期事件。

2. LifecycleEventObserver

LifecycleEventObserver接口

public interface LifecycleEventObserver extends LifecycleObserver {

    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

生命周期状态改变时,会调用onStateChanged方法(调用逻辑后面讲)。参数event为当前的事件(ON_CREATEON_STARTON_RESUMEON_PAUSEON_STOPON_DESTROY)。

3. OnLifecycleEvent(已弃用)

OnLifecycleEvent注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Deprecated
public @interface OnLifecycleEvent {
    Lifecycle.Event value();
}

生命周期状态改变时,会调用LifecycleObserver子类被对应event标注的方法(调用逻辑后面讲)。OnLifecycleEvent已被@Deprecated标注,已经被弃用,后面会减少对此的讲解。

添加观察者

使用

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 添加
        lifecycle.addObserver(lifecycleObserver)
    }
}

获取到Lifecycle,然后进行添加。我们先看一下Lifecycle类。

Lifecycle

Lifecycle类

public abstract class Lifecycle {

    // 协程相关,存放coroutineScope的。
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference mInternalScopeRef = new AtomicReference<>();

    // 添加观察者
    @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; // 任何事件都会触发
    }

    // 状态类
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        
        // 比较这个状态是否大于等于给定的状态,RESUMED > STARTED > CREATED > INITIALIZED > DESTROYED。
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}
 
 

StateEvent的关系图

lifecycle-states.png

LifecycleOwner

我们再来看一下,从ActvityFragment中是如何获取到Lifecycle的,因为androidx.activity.ComponentActivityandroidx.fragment.app.Fragment都实现了LifecycleOwner接口,表明可以提供Lifecycle实例,相关的源码如下:

LifecycleOwner接口

public interface LifecycleOwner {

    @NonNull
    Lifecycle getLifecycle();
}
Activity

androidx.activity.ComponentActivity --> getLifecycle方法

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        ContextAware,
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner,
        ActivityResultRegistryOwner,
        ActivityResultCaller,
        MenuHost {

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

androidx.core.app.ComponentActivity --> getLifecycle方法

public class ComponentActivity extends Activity implements
        LifecycleOwner,
        KeyEventDispatcher.Component {
        
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

说明:

  1. MyActivity继承关系:MyActivity->AppCompatActivity->FragmentActivity->androidx.activity.ComponentActivity->androidx.core.app.ComponentActivity
  2. 虽然androidx.activity.ComponentActivity和父类androidx.core.app.ComponentActivity都实现了LifecycleOwner接口,但是androidx.core.app.ComponentActivity的被子类androidx.activity.ComponentActivity覆盖,导致父类的无效。
Fragment

androidx.fragment.app.Fragment --> getLifecycle方法

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
        ActivityResultCaller {
    LifecycleRegistry mLifecycleRegistry;
    
    @Override
    @NonNull
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    
    public Fragment() {
        initLifecycle();
    }
    
    private void initLifecycle() {
        mLifecycleRegistry = new LifecycleRegistry(this);
    }
}

androidxActivityFragment都实现了LifecycleOwner接口,并返回的都是LifecycleRegistry类。我们接下来看一下LifecycleRegistry类。

LifecycleRegistry

构造方法

LifecycleRegistry --> 构造方法

public LifecycleRegistry(@NonNull LifecycleOwner provider) {
    // 默认,强制在主线程执行,mEnforceMainThread为true
    this(provider, true);
}

private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
    // 记录LifecycleOwner
    mLifecycleOwner = new WeakReference<>(provider);
    // 当前状态为INITIALIZED
    mState = INITIALIZED;
    mEnforceMainThread = enforceMainThread;
}

我们接下来再看一下addObserver方法。

addObserver

LifecycleRegistry --> addObserver方法

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    // 当mEnforceMainThread为true时,必须是在主线程调用,否则抛出异常
    enforceMainThreadIfNeeded("addObserver");  
    // 观察者的初始化状态
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    // 生成ObserverWithState,它包含状态和观察者,它会把上面全部3种情况的LifecycleObserver统一转换成LifecycleEventObserver。
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    // 将观察者添加到map,如果已经添加,则直接返回。
    // putIfAbsent,如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,并返回null。
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);    
    if (previous != null) {
        return;
    }
    // 获取LifecycleOwner实例,一般来说是Activity或者Fragment实例。
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // 对象为空,说明已经被销毁,直接返回。
        return;
    }

    // isReentrance:是否是再次进入
    // 1.mAddingObserverCounter:添加中的观察者数量。在执行前加1,在执行后减1,又因为addObserver方法强制在主线程执行(没有并发),所以它一般都为0。之所以不为0,是因为它在添加的observer的生命周期回调的方法内,又调用addObserver方法增加了一个新的LifecycleObserver。
    // 2.mHandlingEvent:是否正在处理事件中。
    boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    // 计算目标状态
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    // statefulObserver.mState.compareTo(targetState) < 0:说明观察者ObserverWithState的状态未到达目标状态。
    // mObserverMap.contains(observer):上面已添加,这边再判断是否包含,是因为它在添加的observer的生命周期回调的方法内,调用了removeObserver。
    // 使用while,保证依次分发所有的事件。
    while ((statefulObserver.mState.compareTo(targetState) < 0
            && mObserverMap.contains(observer))) {            
        pushParentState(statefulObserver.mState);
        // 获取观察者状态的下一个事件
        final Event event = Event.upFrom(statefulObserver.mState);
        if (event == null) {
            throw new IllegalStateException("no event up from " + statefulObserver.mState);
        }
        // 观察者ObserverWithState分发事件,通知被Lifecycle添加的LifecycleObserver状态改变,讲ObserverWithState时会介绍。
        statefulObserver.dispatchEvent(lifecycleOwner, event);        
        popParentState();
        // mState可能被更改,重新计算。
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}

说明:

  1. 目标状态一般为mState(当前状态),观察者ObserverWithState初始化状态一般为INITIALIZED,如果观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
    例如:如果在ActivityonResumeaddObserver,则当前状态为RESUMED,观察者的状态为INITIALIZEDRESUMED,所以此观察者会依次接收到ON_CREATEON_STARTON_RESUME事件或对应的回调。

我们再来看一下带状态的观察者ObserverWithState,以及它的dispatchEvent分发方法。

ObserverWithState

ObserverWithState类

static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        // 把上面全部3种情况的LifecycleObserver统一转换成LifecycleEventObserver。
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = event.getTargetState();
        mState = min(mState, newState);
        // 用转换后的LifecycleEventObserver通知被Lifecycle添加的LifecycleObserver状态改变。
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

ObserverWithState带状态的观察者,它统一了全部3种情况的LifecycleObserver,以及dispatchEvent方法,用转换后的LifecycleEventObserver通知被Lifecycle添加的LifecycleObserver状态改变。我们再来看一下Lifecycling它是如何统一的。

Lifecycling

Lifecycling --> lifecycleEventObserver方法

@NonNull
@SuppressWarnings("deprecation")
static LifecycleEventObserver lifecycleEventObserver(Object object) {
    // 是否是LifecycleEventObserver子类
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    // 是否是FullLifecycleObserver子类
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        // 两者都是,需要适配,两个样式回调都通知。
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    if (isFullLifecycleObserver) {
        // 只是FullLifecycleObserver,需要适配,只回调一个。
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    if (isLifecycleEventObserver) {
        // 只是LifecycleEventObserver,不用适配,直接返回即可。
        return (LifecycleEventObserver) object;
    }

    // 使用OnLifecycleEvent注解的处理
    final Class klass = object.getClass();
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        // 使用OnLifecycleEvent注解,并且依赖了androidx.lifecycle:lifecycle-compiler注解处理器,使用注解处理器优化反射带来的性能问题。
        List> constructors =
                sClassToAdapters.get(klass);
        if (constructors.size() == 1) {
            GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                    constructors.get(0), object);
            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);
    }
    // 使用OnLifecycleEvent注解,并且未依赖注解处理器,使用反射处理。
    return new ReflectiveGenericLifecycleObserver(object);
}

我们再来看一下具体实现。

LifecycleEventObserver Adapter

LifecycleEventObserver Adapter一共有4个,FullLifecycleObserverAdapterSingleGeneratedAdapterObserverCompositeGeneratedAdaptersObserverReflectiveGenericLifecycleObserver。和OnLifecycleEvent注解相关的3个,由于OnLifecycleEvent已经弃用,所以我们只讲1个反射的,注解处理器的2个它们的方法要求和反射的相同,只不过它们是在编译期检测的。

FullLifecycleObserverAdapter

FullLifecycleObserverAdapter类

class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        // 以对应生命周期方法回调方式通知
        switch (event) {
            case ON_CREATE:
                mFullLifecycleObserver.onCreate(source);
                break;
            case ON_START:
                mFullLifecycleObserver.onStart(source);
                break;
            case ON_RESUME:
                mFullLifecycleObserver.onResume(source);
                break;
            case ON_PAUSE:
                mFullLifecycleObserver.onPause(source);
                break;
            case ON_STOP:
                mFullLifecycleObserver.onStop(source);
                break;
            case ON_DESTROY:
                mFullLifecycleObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
        // 以状态改变回调方式通知
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }
}

ObserverWithState调用dispatchEvent的时候,如果是使用DefaultLifecycleObserverLifecycleEventObserver,则会调用此onStateChanged方法,以通知被Lifecycle添加的LifecycleObserver状态改变。

ReflectiveGenericLifecycleObserver

ReflectiveGenericLifecycleObserver类

@Deprecated
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final androidx.lifecycle.ClassesInfoCache.CallbackInfo mInfo;

    @SuppressWarnings("deprecation")
    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        // 获取观察者类的信息,内部会解析判断被OnLifecycleEvent注解的方法声明是否正确。
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        // 调用被OnLifecycleEvent标注的对应的方法,通知回调。
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

ObserverWithState调用dispatchEvent的时候,如果是使用OnLifecycleEvent并且无添加依赖androidx.lifecycle:lifecycle-compiler注解处理器,则会调用此onStateChanged方法,以通知被Lifecycle添加的LifecycleObserver状态改变。

ClassesInfoCache --> getInfo方法

CallbackInfo getInfo(Class klass) {
    CallbackInfo existing = mCallbackMap.get(klass);
    if (existing != null) {
        return existing;
    }
    existing = createInfo(klass, null);
    return existing;
}

ClassesInfoCache类的getInfo方法,一开始缓存里面是没有的,然后会调用createInfo方法进行创建并存储到缓存并返回其结果。

ClassesInfoCache --> createInfo方法

private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
    ...
    for (Method method : methods) {
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation == null) {
            continue;
        }
        hasLifecycleMethods = true;
        Class[] params = method.getParameterTypes();
        int callType = CALL_TYPE_NO_ARG;
        if (params.length > 0) {
            callType = CALL_TYPE_PROVIDER;
            // 第1个参数必须是LifecycleOwner,否则抛异常。
            if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. Must be one and instanceof LifecycleOwner");
            }
        }
        Lifecycle.Event event = annotation.value();

        if (params.length > 1) {
            callType = CALL_TYPE_PROVIDER_WITH_EVENT;
            // 第2个参数必须是Lifecycle.Event,否则抛异常。
            if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                throw new IllegalArgumentException(
                        "invalid parameter type. second arg must be an event");
            }
            // 并且OnLifecycleEvent注解的值必须是Lifecycle.Event.ON_ANY,否则抛异常。
            if (event != Lifecycle.Event.ON_ANY) {
                throw new IllegalArgumentException(
                        "Second arg is supported only for ON_ANY value");
            }
        }
        if (params.length > 2) {
            // 超过2个参数,报错。
            throw new IllegalArgumentException("cannot have more than 2 params");
        }
        ...
    }
    CallbackInfo info = new CallbackInfo(handlerToEvent);
    // 存储到缓存
    mCallbackMap.put(klass, info);
    ...
    return info;
}

说明:

  1. 使用OnLifecycleEvent注解标注方法上,方法要求:方法名称任意,方法参数可无可1个(必须是LifecycleOwner)、可2个(必须先后是LifecycleOwnerLifecycle.Event、且event必须是Lifecycle.Event.ON_ANY)。

总结

代码流程:

  1. androidxActivityFragment都实现了LifecycleOwner接口,并getLifecycle方法返回的都是LifecycleRegistry类。
  2. LifecycleRegistryaddObserver方法,会把观察者状态的包装为ObserverWithState,并添加到mObserverMap集合以记录所有观察者。
  3. 如果观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
  4. 分发事件是由ObserverWithState进行分发的,它统一了所有形式的LifecycleObserver,并处理dispatchEvent方法,用转换后的LifecycleEventObserver通知被Lifecycle添加的LifecycleObserver状态改变。

移除观察者

LifecycleRegistry --> removeObserver方法

@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    // 当mEnforceMainThread为true时,必须是在主线程调用,否则抛出异常
    enforceMainThreadIfNeeded("removeObserver");
    // 从map中移除
    mObserverMap.remove(observer);
}

获取当前状态

LifecycleRegistry --> getCurrentState方法

@NonNull
@Override
public State getCurrentState() {
    return mState;
}

此状态是如何被通知的,它又是如何感知生命周期的,我们一起看生命周期感知

生命周期感知

Lifecycle是一个生命周期感知的框架,那么它是如何感知ActivityFragment的生命周期的呢?

Activity

MyActivity继承关系:MyActivity->AppCompatActivity->FragmentActivity->androidx.activity.ComponentActivity->androidx.core.app.ComponentActivity

androidx.activity.ComponentActivity

androidx.activity.ComponentActivity--> onCreate方法

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    ...
}
androidx.core.app.ComponentActivity

androidx.core.app.ComponentActivity--> onCreate方法

@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}

说明:
androidx.activity.ComponentActivity以及它的父类androidx.core.app.ComponentActivity都调用了ReportFragment.injectIfNeededIn(this),让其处理当前Activity的事件分发。

LifecycleDispatcher

LifecycleDispatcher类

class LifecycleDispatcher {

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);

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

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            ReportFragment.injectIfNeededIn(activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    }

    private LifecycleDispatcher() {
    }
}

说明:

  1. 添加依赖androidx.lifecycle:lifecycle-process:XXX库后,内部的startup库(底层ContentProvider)会调用LifecycleDispatcher.init方法进行初始化,然后会注册一个App级别的ActivityLifecycleCallbacks,监听所有Activity的生命周期变化,并在onActivityCreated的时候调用了ReportFragment.injectIfNeededIn(this)让其处理当前Activity的事件分发。

问题:

  1. 为什么在App全局内监听了所有的Activity,还要在androidx.activity.ComponentActivityandroidx.core.app.ComponentActivity内调用?
    因为可能没依赖androidx.lifecycle:lifecycle-process:XXX库。
  2. 为什么在androidx.activity.ComponentActivity内调用了,还要在其父类androidx.core.app.ComponentActivity内调用?
    因为MyActivity可能直接继承的是父类androidx.core.app.ComponentActivity
  3. 上面问题,会导致同一个Activity调用了多次,那addObserver增加的观察者会不会同一个状态被通知多次?
    不会,因为在LifecycleRegistry分发的时候,判断了,如果要分发的状态当前的状态相同,则不操作直接返回,所以不会被被通知多次。
  4. 为什么要用Fragment来实现Activity的事件分发?
    因为Fragment能感知生命周期变化,并且Fragment好在Activity中进行增删,例如MyActivity直接继承Activity,想要此功能,直接在onCreate方法内调用ReportFragment.injectIfNeededIn(this)即可。
ReportFragment

ReportFragment--> injectIfNeededIn方法

public class ReportFragment extends android.app.Fragment {

    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // 29及以上,直接向Activity注册ActivityLifecycleCallbacks。
            LifecycleCallbacks.registerIn(activity);
        }
        // 添加无布局的Fragment,如果之前已经添加,则不再添加。
        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();
        }
    }   
}

SDK >= 29

@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

    static void registerIn(Activity activity) {
        // 注册ActivityLifecycleCallbacks
        activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity,
            @Nullable Bundle bundle) {
    }

    @Override
    public void onActivityPostCreated(@NonNull Activity activity,
            @Nullable Bundle savedInstanceState) {
        dispatch(activity, Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
    }

    @Override
    public void onActivityPostStarted(@NonNull Activity activity) {
        dispatch(activity, Lifecycle.Event.ON_START);
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
    }

    @Override
    public void onActivityPostResumed(@NonNull Activity activity) {
        dispatch(activity, Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onActivityPrePaused(@NonNull Activity activity) {
        dispatch(activity, Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {
    }

    @Override
    public void onActivityPreStopped(@NonNull Activity activity) {
        dispatch(activity, Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity,
            @NonNull Bundle bundle) {
    }

    @Override
    public void onActivityPreDestroyed(@NonNull Activity activity) {
        dispatch(activity, Lifecycle.Event.ON_DESTROY);
    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
    }
}

SDK >= 29Activity会注册一个ActivityLifecycleCallbacks监听此Activity的生命周期变化,会在onCreateonStartonResume 方法被调用后onPauseonStoponDestroy 方法被调用前分发对应的 Event。同一个Activity可能会注册多个ActivityLifecycleCallbacks,则同一个状态会调用dispatch(Activity, Lifecycle.Event)多次。

ReportFragment--> dispatch(Activity, Lifecycle.Event)方法

@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    // LifecycleRegistryOwner已被弃用
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }
    
    // ComponentActivity已经实现LifecycleOwner,并getLifecycle方法返回的是LifecycleRegistry。
    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

由于ComponentActivity已经实现LifecycleOwner,并getLifecycle方法返回的是LifecycleRegistry,所以我们接下来看一下LifecycleRegistryhandleLifecycleEvent方法。

LifecycleRegistry--> handleLifecycleEvent()方法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    // 当mEnforceMainThread为true时,必须是在主线程调用,否则抛出异常
    enforceMainThreadIfNeeded("handleLifecycleEvent");
    moveToState(event.getTargetState());
}

private void moveToState(State next) {
    if (mState == next) {
        // 如果要设置的状态和当前的状态相同,则直接返回
        return;
    }
    // 记录当前状态
    mState = next;
    if (mHandlingEvent || mAddingObserverCounter != 0) {
        mNewEventOccurred = true;
        // we will figure out what to do on upper level.
        return;
    }
    mHandlingEvent = true;
    sync();
    mHandlingEvent = false;
}

由于moveToState判断了同状态不处理,所以同一个事件多次调用handleLifecycleEvent才不会有问题。
我们再来看一下sync方法

LifecycleRegistry--> 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.");
    }
    // 只要未同步,就一直同步。不用if用while的原因,因为同步过程中状态可能改变了。
    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) {
            // 小于当前State,调用backwardPass向后。
            backwardPass(lifecycleOwner);
        }
        Map.Entry newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            // 大于当前State,调用forwardPass向前。
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

backwardPassforwardPass类似,我们只看forwardPass

LifecycleRegistry--> forwardPass()方法

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    // 遍历所有的观察者
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        // 依次同步所有的状态
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            final Event event = Event.upFrom(observer.mState);
            if (event == null) {
                throw new IllegalStateException("no event up from " + observer.mState);
            }
            // 观察者ObserverWithState分发事件,通知被Lifecycle添加的LifecycleObserver状态改变。
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}

至此通过分发事件,被Lifecycle添加的LifecycleObserver也得到了通知。

SDK < 29
SDK < 29Activity会添加一个无布局的ReportFragment来监听此Activity的生命周期变化,会在对应的生命周期方法里分发对应的 Event。同一个Activity不会添加多个ReportFragment,所以同一个事件不会调用dispatch( Lifecycle.Event)多次。

ReportFragment--> 生命周期方法

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    dispatch(Lifecycle.Event.ON_CREATE);
}

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

@Override
public void onResume() {
    super.onResume();
    ...
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}

@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
    ...
}

ReportFragment--> dispatch(Activity, Lifecycle.Event)方法

private void dispatch(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 29) {
        // 仅在SDK 29之前分发,防止重复。
        dispatch(getActivity(), event);
    }
}

由于ReportFragment,在SDK所有版本都有添加,而在SDK >= 29的时候是使用ActivityLifecycleCallbacks处理的分发,所以ReportFragment的分发需要在SDK < 29下,防止重复。

Fragment

androidx.fragment.app.Fragment--> 生命周期方法

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
        ActivityResultCaller {
        
    void performCreate(Bundle savedInstanceState) {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    @SuppressWarnings("ConstantConditions")
    void performStart() {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        ...
    }
    
    @SuppressWarnings("ConstantConditions")
    void performResume() {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        ...
    }
    
    @SuppressWarnings("ConstantConditions")
    void performPause() {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        ...
    }
    
    void performStop() {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        ...
    }
    
    void performDestroy() {
        ...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        ...
    }

androidx.fragment.app.Fragment的实现是直接其生命周期方法内调用的handleLifecycleEvent方法进行的分发。

总结

代码流程:

  1. androidxActivity是使用ReportFragment处理,在其SDK >= 29的时候是使用ActivityLifecycleCallbacks进行的分发,在SDK < 29的时候是使用ReportFragment的生命周期方法进行的分发。
  2. androidxFragment是使用androidx Fragment的生命周期方法进行的分发。
  3. 分发方法最后会调用LifecycleRegistryhandleLifecycleEvent方法,如果当前的状态要分发的状态不同,则它会同步所有的观察者
  4. 如果某一个观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
  5. 分发事件是由ObserverWithState进行分发的,它统一了所有形式的LifecycleObserver,并处理dispatchEvent方法,用转换后的LifecycleEventObserver通知被Lifecycle添加的LifecycleObserver状态改变。

总结

以上就是全面的Jetpack-Lifecycle源码了!之后会出Jetpack其它源码系列,请及时关注。如果你有什么问题,大家评论区见!

最后推荐一下我的网站,开发者的技术博客: devbolg.cn ,目前包含android相关的技术,之后会面向全部开发者,欢迎大家来体验!

你可能感兴趣的:(Jetpack-Lifecycle源码解析)