JetPack-Lifecycle

概述

Lifecycle生命周期感知型组件,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态

使用

导入依赖
//如果已经集成了AndroidX的不需要额外操作,没有集成的话需要导入对应的依赖

implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
Lifecycle管理Activity的生命周期
class TestActivity : AppCompatActivity() {

    private lateinit var mObserver: LifecycleObserver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mObserver = MyObserver()
        lifecycle.addObserver(mObserver)
    }

    override fun onStart() {
        super.onStart()

        println("owner onStart")
    }

    override fun onStop() {
        super.onStop()
        println("owner onStop")
    }
}

internal class MyObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun connectListener() {
        println("MyObserver connectListener")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopListener() {
        println("MyObserver stopListener")
    }
}

//打印的日志如下

2021-06-02 11:34:42.902 23976-23976/com.xz.fksj I/System.out: owner onStart
2021-06-02 11:34:42.903 23976-23976/com.xz.fksj I/System.out: MyObserver connectListener
2021-06-02 11:35:04.872 23976-23976/com.xz.fksj I/System.out: MyObserver stopListener
2021-06-02 11:35:04.883 23976-23976/com.xz.fksj I/System.out: owner onStop


可以明显的看出,设置的MyObserver能监听到Activity的生命周期的变化情况
监听整个app的生命周期,可以判断app是否处于前台
class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
    
        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleObserver())
    }
  
     /**
     * Application生命周期观察,提供整个应用进程的生命周期
     *
     * Lifecycle.Event.ON_CREATE只会分发一次,Lifecycle.Event.ON_DESTROY不会被分发。
     *
     * 第一个Activity进入时,ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
     * 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP,将在最后一个Activit退出后后延迟分发。如果由于配置更改而销毁并重新创建活动,则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
     *
     * 作用:监听应用程序进入前台或后台
     */
    private class ApplicationLifecycleObserver : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        private fun onAppForeground() {
            println("ApplicationObserver: app moved to foreground")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        private fun onAppBackground() {
            println("ApplicationObserver: app moved to background")
        }
    }
}

源码分析

开始之前先简单介绍一下几个重要的类

  • **LifecycleObserver : **Lifecycle观察者。我们需要自定义类实现LifecycleObserver,通过注解的方式可观察生命周期方法。
  • LifecycleOwner : Lifecycle持有者。让Activity或者fragment实现该接口,当生命周期改变是事件会被LifecycleObserver接收到。
  • Lifecycle : 生命周期抽象类。持有添加和移除监听方法。定义State和Event枚举。
  • LifecycleRegistry : Lifecycle的实现类
  • **State 枚举 : ** 当前生命周期所处状态。Lifecycle 将 Activity 的生命周期函数对应成 State (不可等同)
  • Event 枚举 : 当前生命周期变化所对应的事件。State 变化触发 Event 事件,事件会被注册的观察者LifecycleObserver 接收处理。

首先来看Lifecycle这个抽象类

public abstract class Lifecycle {
  
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    @NonNull
    public abstract State getCurrentState();
        
    //前面六个事件对应生命周期的方法,最后一个ON_ANY可以响应任何事件
    @SuppressWarnings("WeakerAccess")
    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }
        
    //5种状态,状态的变化都是由上面的六个事件所触发变化的
    @SuppressWarnings("WeakerAccess")
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}
具体的事件和状态对应变化图如下
image

Event 表示生命周期事件,与 Activity/Fragment 生命周期方法对应。State 是 Lifecycle 这些生命周期对应的状态。

为什么不直接用对应的生命周期设置对应的状态呢,而是设置了五个状态呢?原因很简单,因为 Lifecycle 不仅仅只是给自己用这些状态,还有 LiveData,ViewMode 等控件也会用到这些状态的进行逻辑判断,所以 Google 工程师做了更好的封装和管理。

Event 中的 ON_CREATE,ON_START,ON_RESUME 是在 LifecyclerOwner 对应的方法执行之后分发,ON_PAUSE,ON_STOP,ON_DESTROY 是在 LifecyclerOwner 对应的方法执行之前分发。

具体lifecycle是如何监听Activity的生命周期的呢?接着往下看

我们先回到开头的例子中,例子中能直接使用lifecycle.addObserver(mObserver),

那是因为AppCompatActivity内部肯定是实现了 LifecycleOwner,通过LifecycleOwner获取Lifecycle的实例,这样才能调用 addObserver().具体看ComponentActivity下。

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
            
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

//具体的实现是由LifecycleRegistry来实现的,来看下对应的addObserver方法

public class LifecycleRegistry extends Lifecycle {
  
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        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) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }
            
        //通过while循环,把新的观察者的状态连续不断的同步到最新的状态
                //就算添加的晚了,还是会把之前的事件一个个分发给你(upEvent方法),这也是liveData数据倒灌的原因
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }

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

我们先来看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 = getStateAfter(event);
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

事件的发送者是mLifecycleObserver,具体的创建者是Lifecycling.lifecycleEventObserver(observer)

static LifecycleEventObserver lifecycleEventObserver(Object object) {
  ...
  //直接看这一行,通过反射创建对应的监听者
  return new ReflectiveGenericLifecycleObserver(object);
}

我们再往下面跟

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }
}

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

//处理被OnLifecycleEvent注释的注解,存到mCallbackMap下,便于后续监听者的使用。
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
  Class<?> superclass = klass.getSuperclass();
  Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
  if (superclass != null) {
    CallbackInfo superInfo = getInfo(superclass);
    if (superInfo != null) {
      handlerToEvent.putAll(superInfo.mHandlerToEvent);
    }
  }

  Class<?>[] interfaces = klass.getInterfaces();
  for (Class<?> intrfc : interfaces) {
    for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
      intrfc).mHandlerToEvent.entrySet()) {
      verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
    }
  }

  Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
  boolean hasLifecycleMethods = false;
  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");
    }
    MethodReference methodReference = new MethodReference(callType, method);
    verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
  }
  CallbackInfo info = new CallbackInfo(handlerToEvent);
  mCallbackMap.put(klass, info);
  mHasLifecycleMethods.put(klass, hasLifecycleMethods);
  return info;
}

这个时候回到ObserverWithStatedispatchEvent方法,进行事件发送。最终的调用者为

ReflectiveGenericLifecycleObserver

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    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);
    }
}

//ClassesInfoCache.class

void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
  invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
  invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                        target);
}

private static void invokeMethodsForEvent(List<MethodReference> handlers,
                                          LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
  if (handlers != null) {
    for (int i = handlers.size() - 1; i >= 0; i--) {
      handlers.get(i).invokeCallback(source, event, mWrapped);
    }
  }
}

//这里是最终的回调
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
  //noinspection TryWithIdenticalCatches
  try {
    switch (mCallType) {
      case CALL_TYPE_NO_ARG:
        mMethod.invoke(target);
        break;
      case CALL_TYPE_PROVIDER:
        mMethod.invoke(target, source);
        break;
      case CALL_TYPE_PROVIDER_WITH_EVENT:
        mMethod.invoke(target, source, event);
        break;
    }
  } catch (InvocationTargetException e) {
    throw new RuntimeException("Failed to call observer method", e.getCause());
  } catch (IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}

那么是如何保持生命周期同步的呢?

回到 ComponentActivity,其中有这么一段

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

ComponentActivity中绑定一个透明的ReportFragment,这里的写法跟Glide里的是一样的,主要是用来感知生命周期的作用

public class ReportFragment extends Fragment {
 
  public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
      // On API 29+, we can register for the correct Lifecycle callbacks directly
      activity.registerActivityLifecycleCallbacks(
        new LifecycleCallbacks());
    }
    // Prior to API 29 and to maintain compatibility with older versions of
    // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
    // need to support activities that don't extend from FragmentActivity from support lib),
    // use a framework fragment to get the correct timing of Lifecycle events
    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();
    }
  }
}

接着通过dispatch将生命周期分发出去

@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);
  // just want to be sure that we won't leak reference to an activity
  mProcessListener = null;
}

//这里加了版本判断,>=29的,处理流程交给ActivityLifecycleCallbacks
private void dispatch(@NonNull Lifecycle.Event event) {
  if (Build.VERSION.SDK_INT < 29) {
    // Only dispatch events from ReportFragment on API levels prior
    // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
    // added in ReportFragment.injectIfNeededIn
    dispatch(getActivity(), event);
  }
}

//根据我们传入的参数,只需要看第一个if语句
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);
    }
  }
}

回到LifecycleRegistryd,看handleLifecycleEvent方法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
  State next = getStateAfter(event);
  moveToState(next);
}

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;
}

通过 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;
    // no need to check eldest for nullability, because isSynced does it for us.
    if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
      backwardPass(lifecycleOwner);
    }
    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<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
    mObserverMap.iteratorWithAdditions();
  while (ascendingIterator.hasNext() && !mNewEventOccurred) {
    Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
    ObserverWithState observer = entry.getValue();
    while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
            && mObserverMap.contains(entry.getKey()))) {
      pushParentState(observer.mState);
      observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
      popParentState();
    }
  }
}

看到最后发现还是熟悉的 observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));

后面的流程就跟上面说过的一样。

整体流程图如下
image

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容