@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun disconnect() {
Log.e(TAG, “disconnect”)
}
companion object {
private const val TAG = “lifecycle_observer_demo”
}
}
// 将 Lifecycle 对象和 LifecycleObserver 对象进行绑定
LifecycleOwner.getLifecycle().addObserver(MyLifecycleObserver())
关联接口
LifecycleOwner
// LifecycleOwner.java
// 具有Android生命周期的类。自定义组件可以使用这些事件来处理生命周期更改,而无需在Activity或Fragment中实现任何代码。
@SuppressWarnings({“WeakerAccess”, “unused”})
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
LifecycleObserver
// LifecycleObserver.java
// 将一个类标记为LifecycleObserver。它没有任何方法,而是依赖于{@link OnLifecycleEvent}注解方法。
@SuppressWarnings(“WeakerAccess”)
public interface LifecycleObserver {
}
LifecycleEventObserver
LifecycleEventObserver 可以获取哪个生命周期事件发生了变化
- 如果同时使用了 DefaultLifecycleObserver,会优先调用 DefaultLifecycleObserver 的对应方法;
- 如果同时使用了 OnLifecycleEvent 注解,将会忽略注解;
// LifecycleEventObserver.java
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
FullLifecycleObserver
注意: 该修饰符为缺省访问修饰符
// FullLifecycleObserver.java
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);
}
DefaultLifecycleObserver
DefaultLifecycleObserver 存在于 androidx.lifecycle:lifecycle-common-java8:xxx 这个依赖库内;
- 相比于注解的形式,官方推荐使用此方式来监听生命周期;
- 如果同时使用了 LifecycleEventObserver,会先调用 DefaultLifecycleObserver 的对应方法;
- 如果同时使用了 OnLifecycleEvent 注解,将会忽略注解;
// DefaultLifecycleObserver.java
@SuppressWarnings(“unused”)
public interface DefaultLifecycleObserver extends FullLifecycleObserver {
// LifecycleOwner 的 onCreate 方法之后调用
@Override
default void onCreate(@NonNull LifecycleOwner owner) {
}
// LifecycleOwner 的 onStart 方法之后调用
@Override
default void onStart(@NonNull LifecycleOwner owner) {
}
// LifecycleOwner 的 onResume 方法之后调用
@Override
default void onResume(@NonNull LifecycleOwner owner) {
}
// LifecycleOwner 的 onPause 方法之前调用
@Override
default void onPause(@NonNull LifecycleOwner owner) {
}
// LifecycleOwner 的 onStop 方法之前调用
@Override
default void onStop(@NonNull LifecycleOwner owner) {
}
// LifecycleOwner 的 onDestroy 方法之前调用
@Override
default void onDestroy(@NonNull LifecycleOwner owner) {
}
}
FullLifecycleObserverAdapter
注意: 该修饰符为缺省访问修饰符
// FullLifecycleObserverAdapter.java
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);
}
}
}
Activity 的 LifecycleRegistry 如何感知生命周期
先来看下 Activity 的基类 ComponentActivity
// androidx.core.app.ComponentActivity
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
…
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
…
@SuppressLint(“RestrictedApi”)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
…
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
再来看下 ReportFragment
// ReportFragment.java
public class ReportFragment extends android.app.Fragment {
private static final String REPORT_FRAGMENT_TAG = “androidx.lifecycle”
- “.LifecycleDispatcher.report_fragment_tag”;
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// 在API 29+上,我们可以直接注册正确的生命周期回调
LifecycleCallbacks.registerIn(activity);
}
// 在API 29之前,并且为了保持与较旧版本的ProcessLifecycleOwner的兼容性(当生命周期运行时已经更新的时候可能不会更新
// 和需要支持未从support lib的FragmentActivity继承的activities),请使用framework fragment来获取正确的生命周期事件
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@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);
}
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
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);
// 只是想确保我们不会泄漏对activity的引用
mProcessListener = null;
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// 仅在API 29之前的API上从ReportFragment调度事件。在API 29+上,
// 这由ReportFragment.injectIfNeededIn中添加的ActivityLifecycleCallbacks处理
dispatch(getActivity(), event);
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
// 此类不是内联的,仅因为我们需要为其添加一个proguard规则(b / 142778206)除此之外,registerIn方法还可以避免类验证失败,
// 因为registerActivityLifecycleCallbacks仅从api 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) {
}
}
}
LifecycleRegistry 如何将事件分发到 LifecycleObserver
// LifecycleRegistry.java
// 设置当前状态并通知观察者。
// 请注意,如果{@code currentState}与该方法的最后一次调用的状态相同,则调用此方法无效。
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;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
// 仅发生在堆栈的顶部(永远不可再进入)
// 因此不必考虑父类
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;
// 无需检查最老的是否可空, 因为在 isSynced 已经验证了
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;
}
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);
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.[外链图片转存中…(img-ynwGOyfs-1643011709702)]
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);