Jetpack-Lifecycle源码解析

Posted 涂程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jetpack-Lifecycle源码解析相关的知识,希望对你有一定的参考价值。

Lifecycle源码解析

源码版本:

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

使用

声明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<Object> 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的关系图

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<Constructor<? extends GeneratedAdapter>> 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) 以上是关于Jetpack-Lifecycle源码解析的主要内容,如果未能解决你的问题,请参考以下文章

解释器在解析JavaScript代码时对于这两种方式

片段(Java) | 机试题+算法思路+考点+代码解析 2023

Android 逆向类加载器 ClassLoader ( 类加载器源码简介 | BaseDexClassLoader | DexClassLoader | PathClassLoader )(代码片段

无法解析片段中的 findViewById [重复]

C# 获得目录创建时间的源码片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段