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 {
@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;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
State 和Event 的关系图
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) {
this(provider, true);
}
private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
mEnforceMainThread = enforceMainThread;
}
我们接下来再看一下addObserver 方法。
addObserver
LifecycleRegistry --> addObserver方法
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
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);
}
statefulObserver.dispatchEvent(lifecycleOwner, event);
popParentState();
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
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) {
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;
}
}
ObserverWithState 带状态的观察者,它统一了全部3种情况的LifecycleObserver ,以及dispatchEvent 方法,用转换后的LifecycleEventObserver 通知被Lifecycle 添加的LifecycleObserver 状态改变。我们再来看一下Lifecycling 它是如何统一的。
Lifecycling
Lifecycling --> lifecycleEventObserver方法
@NonNull
@SuppressWarnings("deprecation")
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;
}
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);
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);
}
我们再来看一下具体实现。
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;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
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;
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;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 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) {
enforceMainThreadIfNeeded("removeObserver");
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) {
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();
manager.executePendingTransactions();
}
}
}
SDK >= 29
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
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) {
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);
}
}
}
由于ComponentActivity 已经实现LifecycleOwner ,并getLifecycle 方法返回的是LifecycleRegistry ,所以我们接下来看一下LifecycleRegistry 的handleLifecycleEvent 方法。
LifecycleRegistry–> handleLifecycleEvent()方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
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.");
}
while (!isSynced()) {
mNewEventOccurred = false;
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
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);
}
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) {
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 其它源码系列,请及时关注。如果你有什么问题,大家评论区见!
|