评论

收藏

[Hbase] Jetpack-Lifecycle源码解析

数据库 数据库 发布于:2021-12-25 11:28 | 阅读数:304 | 评论:0

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个(必须先后是​​LifecycleOwner​​​、​​Lifecycle.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​​​添加、删除。可以使用它的子接口​​DefaultLifecycleObserver​​​、​​LifecycleEventObserver​​或​​OnLifecycleEvent(已弃用)​​标注方法的子类,来通知生命周期事件。
2. LifecycleEventObserver
LifecycleEventObserver接口
public interface LifecycleEventObserver extends LifecycleObserver {
  void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
生命周期状态改变时,会调用​​onStateChanged​​​方法(调用逻辑后面讲)。参数​​event​​​为当前的事件(​​ON_CREATE​​​、​​ON_START​​​、​​ON_RESUME​​​、​​ON_PAUSE​​​、​​ON_STOP​​​、​​ON_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;
    }
  }
}
​​State​​​和​​Event​​的关系图
DSC0000.png

LifecycleOwner
我们再来看一下,从​​Actvity​​​或​​Fragment​​​中是如何获取到​​Lifecycle​​​的,因为​​androidx.activity.ComponentActivity​​​和​​androidx.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;
  }
}


说明:




  • ​​MyActivity​​​继承关系:​​MyActivity​​​->​​AppCompatActivity​​​->​​FragmentActivity​​​->​​androidx.activity.ComponentActivity​​​->​​androidx.core.app.ComponentActivity​​
  • 虽然​​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);
  }
}
​​androidx​​​的​​Activity​​​和​​Fragment​​​都实现了​​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--;
}


说明:

  • 目标状态一般为​​mState​​​(当前状态),观察者​​ObserverWithState​​​初始化状态一般为​​INITIALIZED​​,如果观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
例如:如果在​​Activity​​​的​​onResume​​​后​​addObserver​​​,则当前状态为​​RESUMED​​​,观察者的状态为​​INITIALIZED​​​到​​RESUMED​​,所以此观察者会依次接收到​​ON_CREATE​​​、​​ON_START​​​、​​ON_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个,​​FullLifecycleObserverAdapter​​​、​​SingleGeneratedAdapterObserver​​​、​​CompositeGeneratedAdaptersObserver​​​、​​ReflectiveGenericLifecycleObserver​​​。和​​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​​​的时候,如果是使用​​DefaultLifecycleObserver​​​或​​LifecycleEventObserver​​​,则会调用此​​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;
}


说明:

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


总结


代码流程:




  • ​​androidx​​​的​​Activity​​​和​​Fragment​​​都实现了​​LifecycleOwner​​​接口,并​​getLifecycle​​​方法返回的都是​​LifecycleRegistry​​类。
  • ​​LifecycleRegistry​​​类​​addObserver​​方法,会把观察者状态的包装为​​ObserverWithState​​​,并添加到​​mObserverMap​​集合以记录所有观察者。
  • 如果观察者的状态一直未到达目标状态,则一直循环分发事件,直到相同为止。
  • 分发事件是由​​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​​​是一个生命周期感知的框架,那么它是如何感知​​Activity​​​或​​Fragment​​的生命周期的呢?
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() {
  }
}


说明:

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




问题:

  • 为什么在App全局内监听了所有的​​Activity​​​,还要在​​androidx.activity.ComponentActivity​​​、​​androidx.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 >= 29, ​​Activity​​​会注册一个​​ActivityLifecycleCallbacks​​​监听此​​Activity​​​的生命周期变化,会在​​onCreate​​​、​​onStart​​​、​​onResume​​ 方法被调用后, ​​onPause​​​、​​onStop​​​、​​onDestroy​​ 方法被调用前分发对应的 ​​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​​​,所以我们接下来看一下​​LifecycleRegistry​​​的​​handleLifecycleEvent​​方法。
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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
    if (!mNewEventOccurred && newest != null
        && mState.compareTo(newest.getValue().mState) > 0) {
      // 大于当前State,调用forwardPass向前。
      forwardPass(lifecycleOwner);
    }
  }
  mNewEventOccurred = false;
}
​​backwardPass​​​和​​forwardPass​​​类似,我们只看​​forwardPass​​。
LifecycleRegistry–> forwardPass()方法
private void forwardPass(LifecycleOwner lifecycleOwner) {
  Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
      mObserverMap.iteratorWithAdditions();
  // 遍历所有的观察者
  while (ascendingIterator.hasNext() && !mNewEventOccurred) {
    Map.Entry<LifecycleObserver, ObserverWithState> 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 < 29, ​​Activity​​​会添加一个无布局的​​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​​方法进行的分发。
总结


代码流程:




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






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






关注下面的标签,发现更多相似文章