- 什么是Lifecycle
- 如何使用lifecycle观察宿主状态
- Fragment是如何实现Lifecycle的
- Lifecycle是如何分发宿主状态的
- Activity中是如何实现事件分发的
Lifecycle是可用于构建生命周期感知型组件的类和接口 - 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。
我们有三种方法去使用Lifecycle观察宿主的生命周期(宿主:实现LifecycleOwner的类)
/**
* 第一种实现LifecycleObserver
*需要用注解来实现事件的接受
* 这种方式会通过反射或者编译时生成代码来实现事件分发,不建议使用
*/
class TestLifecycleObserver : LifecycleObserver{
private val TAG = "TestLifecycleObserver"
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStart(){
Log.e(TAG, "ON_STOP")
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(){
Log.e(TAG, "ON_CREATE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(){
Log.e(TAG, "ON_DESTROY")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause(){
Log.e(TAG, "ON_PAUSE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(){
Log.e(TAG, "ON_RESUME")
}
}
/**
* 第二种
* 通过实现LifecycleEventObserver来接受事件分发,需要自己解析是那种事件
*/
class TestLifecycleEventObserver : LifecycleEventObserver {
private val TAG = "TestLifecycleEventObserver"
@SuppressLint("LongLogTag")
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when(event){
Lifecycle.Event.ON_RESUME->{
Log.e(TAG, "ON_RESUME")
}
Lifecycle.Event.ON_PAUSE->{
Log.e(TAG, "ON_PAUSE")
}
Lifecycle.Event.ON_DESTROY->{
Log.e(TAG, "ON_DESTROY")
}
Lifecycle.Event.ON_ANY->{
Log.e(TAG, "ON_ANY")
}
Lifecycle.Event.ON_START->{
Log.e(TAG, "ON_START")
}
Lifecycle.Event.ON_CREATE->{
Log.e(TAG, "ON_CREATE")
}
}
}
}
/**
* 第三种
* 实现DefaultLifecycleObserver, 需要添加androidx.lifecycle:common-java8:<version>依赖
* 这种方式事件分发比较清楚
*/
class TestFullLifecycleObserver : DefaultLifecycleObserver{
private val TAG = "TestFullLifecycleObserver"
@SuppressLint("LongLogTag")
override fun onCreate(owner: LifecycleOwner) {
Log.e(TAG, "onCreate")
}
@SuppressLint("LongLogTag")
override fun onDestroy(owner: LifecycleOwner) {
Log.e(TAG, "onDestroy")
}
@SuppressLint("LongLogTag")
override fun onPause(owner: LifecycleOwner) {
Log.e(TAG, "onPause")
}
@SuppressLint("LongLogTag")
override fun onResume(owner: LifecycleOwner) {
Log.e(TAG, "onResume")
}
@SuppressLint("LongLogTag")
override fun onStart(owner: LifecycleOwner) {
Log.e(TAG, "onStart")
}
@SuppressLint("LongLogTag")
override fun onStop(owner: LifecycleOwner) {
Log.e(TAG, "onStop")
}
}
class LifecycleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.frament_test)
lifecycle.addObserver(TestLifecycleObserver())
lifecycle.addObserver(TestLifecycleEventObserver())
lifecycle.addObserver(TestFullLifecycleObserver())
}
}
上述三个类,分别实现了LifecycleObserver,LifecycleEventObserver,DefaultLifecycleObserver(FullLifecycleObserver和DefaultLifecycleObserver的实现是一样的),最后在宿主中调用getLifecycle()方法将观察者注册进去。
源码解析
要了解lifecycle的运行原理,首先要知道LifecycleOwner,Lifecycle,lifecycleObserver三者之间的关系。
LifecycleOwner
如果要让类成为宿主必须要实现LifecycleOwner接口,并且实现接口中唯一的方法
Lifecycle getLifecycle();
Lifecycle
Lifecycle实现的核心接口,拥有注册观察者,分发事件的能力。注册进宿主的观察者实际上都是注册到Lifecycle的实现类中。
lifecycleObserver
lifecycle中的观察者。宿主每次生命周期改变,都会通知所有的观察,并且如果观察者注册在中间的生命周期那么观察者会收到之前所有的生命周期事件
解析
这张图解析了宿主生命周期的流程以及事件的传递,宿主的生命周期可以向前传递,也可以向后传递,每个事件都会将宿主的生命周期推向相应的阶段。可以将状态看作图中的节点,将事件看作这些节点之间的边。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wmsWNHMt-1665970267988)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e3c90dbaa61a4dfa810a3af6d459c8cf~tplv-k3u1fbpfcp-watermark.image?)]
我们先来看看在fragment中的生命周期是怎么分发的
public class Fragment implements LifecycleOwner{
public Fragment() {
initLifecycle();
}
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
}
void performCreate(Bundle savedInstanceState) {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
...
}
上面的代码是Fragment的分发流程,Fragment继承了LifecycleOwner,并实现了getLifecycle方法。之后我们注册的观察者都将注册到mLifecycleRegistry中。随后的生命周期方法会通过mLifecycleRegistry.handleLifecycleEvent向观察者分发事件。
我们先来看看当我们注册到宿主的时候发生了什么。代码中的注释详细的描述了addObserver中的操作。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//校验addObserver方法是否是在主线程上调用
enforceMainThreadIfNeeded("addObserver");
//mState是宿主当前的生命周期,如果观察者不是在宿主DESTROYED生命周期时注册进来的话
//,会被赋予初始生命周期,为INITIALIZED。
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//传递进来的观察者会和初始生命周期共同被包装成ObserverWithState对象,
//ObserverWithState对象会将观察者包装成LifecycleEventObserver,并记录当前的生命周期状态
//这个类后面会说
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//将观察者放入mObserverMap集合中,并校验观察者是否重复添加,如果集合中存在,会返回null
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
//软引用获取获取宿主,如果获取为null,则表示宿主应该被销毁了
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//计算观察者需要前进到的目标状态,因为添加观察者状态时,初始状态为INITIALIZED
//这个方法后面会详细说明
State targetState = calculateTargetState(observer);
//标记需要分发的观察者个数
mAddingObserverCounter++;
//通过while循环来逐个分发观察者和宿主之间相差的生命周期事件。直到观察者的生命周期和
//宿主的生命周期相同
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
//将当前观察者的状态记录到一个mParentStates中,具体原因下面说
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);
//将当前观察者的状态从mParentStates中移除
popParentState();
// mState / subling may have been changed recalculate
//计算观察者需要前进到的目标生命周期
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
//第一次注册都会进入这个方法校验观察者和宿主的生命周期是否同步完成
sync();
}
//事件分发结束,减去需要分发的观察者个数
mAddingObserverCounter--;
}
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);
}
//如果宿主的生命周期大于观察者集合中最后一个状态,则需要观察者状态需要前进
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//遍历每个观察者并将状态向前进
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
//校验观察者的状态是否和宿主的状态同步
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;
}
阅读完上面的源码,我们现在应该有几个疑问
- 为什么观察者在不同的生命周期注册进入宿主,都需要将生命周期初始化为INITIALIZED
- LifecycleRegistry是怎么计算出观察者需要前进的目标生命周期的
- 为什么需要将当前观察者的生命周期记录到mParentStates中
- 事件是怎么分发的
为什么观察者在不同的生命周期注册进入宿主,都需要将生命周期初始化为INITIALIZED
这是为了我们在宿主不同生命周期注册观察者都能接收到完整的生命周期事件。
比如你在Activity的onResume中注册了观察者,你可以收到onCreate,onStart,onResume生命周期的通知。
LifecycleRegistry是怎么计算出观察者需要前进的目标生命周期的
当观察者被注册进入宿主,会被包装成ObserverWithState放进FastSafeIterableMap集合中(FastSafeIterableMap是一个用HashMap包裹的SafeIterableMap数据结构,SafeIterableMap是用链表维护的一种类似Map的数据结构,你可以通过HashMap快速查找到Key所对应的观察者,并可以通过获得的观察者查找到链表前一个对象)关于FastSafeIterableMap数据结构
LifecycleRegistry通过下面的方法来推导出观察者需要前进到的目标生命周期
private State calculateTargetState(LifecycleObserver observer) {
//取出这次添加的观察者前一个的观察者数据
Map.Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
//如果前一个观察者为空则siblingState为空否则siblingState为前一个观察者当前的状态
//(前一个观察者已经通过同步前进到和当前宿主相同的生命周期状态)
State siblingState = previous != null ? previous.getValue().mState : null;
//如果此时mParentStates不为空则取列表中最后一个否则取null
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
//min()方法会取两个中较小的一个,此时mState和siblingState都为宿主当前的生命周期状态,且parentState为null固会返回宿主的生命周期为目标生命周期
return min(min(mState, siblingState), parentState);
}
为什么需要将当前观察者的生命周期记录到mParentStates中
源码中是这么说的,我实在没懂, debug了很多种情况,mParentStates都是空,似乎这个代码去掉也没有影响。哪位大佬了解可以留言告诉我一下
// we have to keep it for cases:
// void onStart() {
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
private ArrayList<State> mParentStates = new ArrayList<>();
事件是怎么分发的
当观察者被注册到宿主上后,会被包装成ObserverWithState
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//这是一个包装器会将传入的观察者全部包装成LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
//记录观察者当前的状态
mState = initialState;
}
//之后调用dispatchEvent分发消息
void dispatchEvent(LifecycleOwner owner, Event event) {
//根据当前的事件推断出新的事件后新的宿主状态
State newState = event.getTargetState();
mState = min(mState, newState);
//向被包装起包装后的观察者分发事件
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
LifecycleEventObserver包装器
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
//判断观察者是否是实现LifecycleEventObserver
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
//判断观察者是否实现FullLifecycleObserver
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
//如果观察者同事实现两者则返回FullLifecycleObserverAdapter
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
//如果是实现LifecycleEventObserver直接返回
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
//如果是实现LifecycleObserver这个空的接口,会根据是否导入Lifcycle注解处理器,
//来使用反射或者编译时代码来调用对应的方法。
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);
}
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");
}
//如果同时实现两个接口则会同时调用onStateChanged
if (mLifecycleEventObserver != null) {
mLifecycleEventObserver.onStateChanged(source, event);
}
}
}
最后我们看一下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;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
附上我调试的例子
因为Activity中有很多观察者,并且Activity的生命周期变换我们不能控制,所以自己写个观察者时最简单的调试方法
class LifecycleActivity : AppCompatActivity() {
val testFullLifecycleObserver = TestFullLifecycleObserver()
val testLifecycleEventObserver = TestLifecycleEventObserver();
val lifecycleOwner = LifecycleOwnerTest()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.frament_test)
tvTest.setOnClickListener {
lifecycleOwner.lifecycle.addObserver(TestLifecycleEventObserver())
//lifecycle.addObserver(TestLifecycleEventObserver())
}
create.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
start.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
resumed.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
pause.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
}
stop.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
destroy.setOnClickListener {
lifecycleOwner.lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
}
class LifecycleOwnerTest : LifecycleOwner{
val lifecycleRegistry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
Actvity中如何分发消息的
如果我们的Activity是继承自AppCompatActivity,AppCompatActivity继承自ComponentActivity,ComponentActivity实现了LifecycleOwner
public class ComponentActivity implements
LifecycleOwner,
{
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
//将事件分发交由ReprotFragment来执行
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
}
可以看到AppCompatActivity中是添加了一个透明的Fragment来事件分发。
那如果我们没有继承AppCompatActivity呢?
这时我们需要引入
implementation("androidx.lifecycle:lifecycle-process:2.4.0-alpha01")
在这个jar包中LifecycleDispatcher会注册Application中的registerActivityLifecycleCallbacks
从而在Activity创建的时候添加Fragment
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) {
//Activity创建时添加Fragment
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
}
private LifecycleDispatcher() {
}
}