概述
Lifecycle 是用来管理感知生命周期的Jetpack基础组件,主要是为了方便需要依赖生命周期来搭建的业务逻辑。其本质原理是观察者模式,即把生命周期组件作为被观察的对象,通过注册观察者,构建状态或者事件变化通知,从而达到感知生命周期的。
生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您编写出更有条理且往往更精简的代码,此类代码更易于维护。
Lifecycle 主要构成
三个重要角色
通过Lifecycle-common的源码,归结Lifecycle的三个重要角色
- LifeCycleOwner 生命周期拥有者,即Activity与Fragment(也可自定义,但局限性大)
- LifeCycleObserver 生命周期观察者,可以是任何类,常见的有mvp的p,自定义View等
- Lifecycle 是一个抽象类,其内部不仅包括了添加和移除观察者的方法,还包括了 Event 和 State 枚举。可以看到 Event 中的事件和 Activity 的生命周期几乎是对应的,除了 ON_ANY,它可用于匹配所有事件。
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();
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
* 见下图1
*/
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
state与event事件关系
state与event事件关系如下图,您可以将状态看作图中的节点,将事件看作这些节点之间的边。
基本使用方法
-
引入Lifecycle-lib
基础组件只需要通过appcompat, 无需再单独引用某一个lib
implementation 'androidx.appcompat:appcompat:1.3.0'
-
以activity生命周期感知
以activity生命周期的感知举例使用(lifecycle-runtime)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MainLifecycleObserver(getLifecycle()));
}
public class MainLifecycleObserver implements LifecycleObserver {
private static final String TAG = "MainLifecycleObserver";
Lifecycle lifecycle;
MainLifecycleObserver(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onActivityCreate() {
Log.d(TAG, "onActivityCreate");
}
...
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onActivityDestroy() {
Log.d(TAG, "onActivityDestroy");
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onActivityAny() {
Log.d(TAG, "onActivityAny : " + lifecycle.getCurrentState().name());
}
}
}
lifecycle-runtime 源码分析
在上面的例子中,我们注册的 MainLifecycleObserver
注册的监听者如何保存、增删的?到底是如何监听到activity生命周期变化的?事件又是如何分发的?接下来按照事件分发的流程逐步分析。
ReportFragment
Activity 生命周期的监听,是通过 ReportFragment向外传递的。
ComponentActivity | oncreate
在 androidx.activity.ComponentActivity 的oncreate方法中, 会调用ReportFragment.injectIfNeededIn
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
ReportFragment.injectIfNeededIn(this);
...
}
injectIfNeededIn
接入,在injectIfNeededIn() 方法中分为两种情况来处理
- SDK_INT >= 29 此情况会向 Activity 注册一个 LifecycleCallbacks ,以此来直接获得各个生命周期事件的回调通知。但也会继续执行第二种情况。
- SDK_INT < 29 此情况会通过向 Activity 添加一个无 UI 界面的 Fragment(即 ReportFragment),间接获得 Activity 的各个生命周期事件的回调通知
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
// 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();
}
}
SDK_INT >= 29
直接通过注册 activity.registerActivityLifecycleCallbacks
@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);
}
....
}
SDK_INT < 29
向activity添加了一个fragment后,ReportFragment 本身的生命周期函数和所在的 Activity 是相关联的,进而实现间接监听activity生命周期,这里列出fragment部分生命周期方法
@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);
}
此处会继续对版本判断,防止重复分发事件
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);
}
}
dispatch
两种情况中,最终都会调到 dispatch方法
@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);
}
}
}
在这个方法中最终通过 LifecycleRegistry.handleLifecycleEvent 来将事件传递出去,从而使得外部得到各个生命周期事件的通知。
LifecycleRegistry
拿到事件后,再来看下 LifecycleRegistry 是如何将 Event 值转发给 LifecycleObserver 的
可以看到在 androidx.activity.ComponentActivity、androidx.fragment.app.Fragment 中都定义了 LifecycleRegistry
// 在ComponentActivity
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
//在 Fragment
LifecycleRegistry mLifecycleRegistry;
...
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
....
}
...
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
...
handleLifecycleEvent
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
moveToState
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) { // 注释1
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
while (!isSynced()) { // 注释2
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
// 注释 3
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Map.Entry newest = mObserverMap.newest();
// 注释4
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
针对这个同步到各个观察者重要方法,我们逐个拆解
- 注释1 通过弱引用,判断当前的lifecycleowner是否已经被回收,避免无效同步
- 注释2 循环条件,是否已经同步完成,具体判断:当前的状态mState、第一个观察者状态eldestObserverState、最后一个观察者状态newestObserverState,三者否是相等,相等表明同步完成
private boolean isSynced() {
if (mObserverMap.size() == 0) { //无观察者了
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
- 如果这三个状态值不相等进入循环,就需要判断当前状态是向前还是向后,比如由 STARTED 到 RESUMED 是状态向前,反过来就是状态向后
- 注释3 表明当前状态是在第一个观察者前面,此时状态是向后,故走到
backwardPass
- 注释4 表明当前状态在最后一个观察者后面,此时状态是向前,故走到
forwardPass
接下里我们选择 forwardPass
分析,另一个类似,不在赘析
forwardPass
其实到这里,既然决定了同步状态方向,那就要轮询通知所有的观察者了吧?
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
// 注释1
Map.Entry entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
// 注释2
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
// 注释3
pushParentState(observer.mState);
// 注释4
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
// 注释5
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
- 注释1 进入ascendingIterator循环遍历,取出entry的value,即每一个观察者
ObserverWithState
- 注释2 由于我们选取的是向前同步,此处的判定条件有三个
- 此处的小于0 ,表明观察者状态位于当前状态之前 ,所以需要向前同步
- 无新的事件发生
- 再次判断map中依然含有此观察者,防止被移除
- 注释3 将 observer 已经遍历到的当前的状态值 mState 保存下来
- 注释4 获取当前观察者状态向前同步后,对应的事件
- 注释5 确定事件后,此处真正的去分发给观察者,即ObserverWithState
最终会调用到 ObserverWithState.dispatchEvent
ObserverWithState
这是LifecycleRegistry 一个内部类,会对注册进来的观察者会重新进行一次包装,成为 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;
}
}
dispatchEvent
这里主要做了两件事
- 更新观察者的当前的状态为最新的状态,即我们要同步的状态
- 调用
LifecycleObserver.onStateChanged
传递事件。这个LifecycleObserver 是在构造方法中通过Lifecycling.``*lifecycleEventObserver*
来统一包装后的接口对象
其实到这里整个事件分发的流程已经完成了,状态也同步了,也分发到每个观察者了,但可以注意到这里并没有直接调用开头示例中的那些注解方法?接下来我们继续分析 Lifecycling的包装流程
Lifecycling
如果在 LifecycleRegistry 中直接对外部传入的 Observer 来进行类型判断、接口回调、反射调用等一系列操作的话,那势必会使得 LifecycleRegistry 整个类非常的臃肿,所以 Lifecycling 的作用就是来将这一系列的逻辑给封装起来,仅仅开放一个 onStateChanged 方法即可让 LifecycleRegistry 完成整个事件分发,从而使得整个流程会更加清晰明了且职责分明。
lifecycleEventObserver
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
//注释1
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
// 注释2
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
// 注释3
final Class> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List> 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);
}
这里分为三种情况
- 注释1 自定义观察者:实现两个接口LifecycleEventObserver、FullLifecycleObserver
- 注释2 自定义观察者:只实现接口FullLifecycleObserver或者 LifecycleEventObserver
- 注释3 以注解的方式,此时就要通过反射来进行回调注解的生命周期方法
这里三种case后续的逻辑不在赘述,主要是采用适配器的设计模式,对观察者做onstatechange调用适配。
总结
这里总结一下整个事件分发的调用顺序
更多应用场景
你也可以单独使用其他lib,这些都是官方提供的具体的应用实现场景
- 如开头示例使用,解耦监听与activity/fragment组件的绑定
- 引入lifecycle-process, 使用ProcessLifecycleOwner快速监听应用前后台,监听应用生命周期
- 引入lifecycle-service, 解耦监听 Service 组件
- 可以使用lifecycle-viewmodel,lifecycle-livedata 等
https://developer.android.com/jetpack/androidx/releases/lifecycle
【参考文档】
https://developer.android.com/topic/libraries/architecture/lifecycle
https://developer.android.com/jetpack/androidx/releases/lifecycle