avatar

目录
Jetpack学习-Lifecycle

个人博客

http://www.milovetingting.cn

Jetpack学习-Lifecycle

Lifecycle是什么

Lifecycle是Jetpack提供的一个组件,可以感知Activity,Fragment的生命周期变化。

简单使用

定义一个类继承自LifecycleObserver,根据业务需要,在这个类中重写相应的方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class LifecycleObserverImpl implements LifecycleObserver {

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(MainActivity.TAG, "onCreate");
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(MainActivity.TAG, "onStart");
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(MainActivity.TAG, "onResume");
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(MainActivity.TAG, "onPause");
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(MainActivity.TAG, "onStop");
}

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(MainActivity.TAG, "onDestroy");
}

}

在Activity中使用

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class LifeCycleActivity extends AppCompatActivity {

LifecycleObserverImpl observer;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle);
//实例化
observer = new LifecycleObserverImpl();
//添加observer
getLifecycle().addObserver(observer);
}

@Override
protected void onDestroy() {
super.onDestroy();
//移除observer
getLifecycle().removeObserver(observer);
}
}

这样,当Activity的生命周期变化时,我们自定义的observer就可以获取到变化。

运行应用,输出日志如下:

Code
1
2
3
4
5
6
2020-04-14 11:08:06.579 22908-22908/com.wangyz.jetpack D/Jetpack: onCreate
2020-04-14 11:08:06.580 22908-22908/com.wangyz.jetpack D/Jetpack: onStart
2020-04-14 11:08:06.584 22908-22908/com.wangyz.jetpack D/Jetpack: onResume
2020-04-14 11:08:11.350 22908-22908/com.wangyz.jetpack D/Jetpack: onPause
2020-04-14 11:08:11.711 22908-22908/com.wangyz.jetpack D/Jetpack: onStop
2020-04-14 11:08:11.713 22908-22908/com.wangyz.jetpack D/Jetpack: onDestroy

一个最简单的Demo就写好了。

原理

Lifecycle为什么可以感知生命周期变化,并通知到observer,我们来看一下。

添加observer

首先从添加observer这里看起:getLifecycle().addObserver(observer)

我们的Activity是继承自AppCompatActivity,调用getLifecycle()后,其实是调用了FragmentActivitygetLifecycle方法

java
1
2
3
4
@Override
public Lifecycle getLifecycle() {
return super.getLifecycle();
}

FragmentActivity中的getLifecycle方法又调用了父类的ComponentActivity的getLifecycle方法

java
1
2
3
4
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}

最终是返回mLifecycleRegistry

调用getLifecycle().addObserver(observer)方法,其实就是调用mLifecycleRegistry的addObserver方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//设置初始状态
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//1.将observer和state组装成一个ObserverWithState对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//2.以observer为key,ObserverWithState为value,保存到map中
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;
}

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

在上面的注释1处,将observerstate组装成一个ObserverWithState对象

java
1
2
3
4
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}

在这个构造方法里,调用了 Lifecycling.getCallback(observer)方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}

if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) 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);
}
//1
return new ReflectiveGenericLifecycleObserver(object);
}

在这个方法里,由于我们传入的是继承自LifecycleObserver的observer,最终返回的是ReflectiveGenericLifecycleObserver

java
1
2
3
4
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}

ReflectiveGenericLifecycleObserver的构造方法中,创建了CallbackInfo信息

java
1
2
3
4
5
6
7
8
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}

如果没有缓存过,则创建

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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;
}

在这个方法里,通过注解,将方法添加到了map中。

在注释2处,以observer为key,ObserverWithState为value,保存到map中

添加observer先看到这里。

生命周期变化时的通知

由于我们的Activity继承自AppCompatActivity,而AppCompatActivity最终继承自ComponentActivity,那么在oncreate执行时,会执行ComponentActivity的onCreate方法

java
1
2
3
4
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}

在这个方法中,执行了ReportFragment.injectIfNeededIn(this)方法;

java
1
2
3
4
5
6
7
8
9
10
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}

可以看到,其实就是创建了一个Fragment,然后关联了Activity,这里Activity生命周期变化时,Fragment也会感知到。

下面以onResume为例,来看下onResume时,我们定义的observer是怎样感知到的。

java
1
2
3
4
5
6
//ReportFragment
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}

我们在observer中注册了Lifecycle.Event.ON_RESUME事件监听,看下dispatch方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
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);
}
}
}

在这个方法中,都会调用到handleLifecycleEvent方法

java
1
2
3
4
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}

这个方法调用了moveToState方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
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;
}

在sync方法中,经过判断,会调用backwardPassforwardPass方法。我们选择forwardPass方法来看

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
}
}
}

在forwardPass方法中,会取出之前添加的observer,再依次调用dispatchEvent方法

java
1
2
3
4
5
6
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}

这个方法调用到ReflectiveGenericLifecycleObserver的onStateChanged方法

java
1
2
3
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}

这个方法调用invokeCallbacks方法

java
1
2
3
4
5
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);
}

在这里又调用了invokeMethodsForEvent方法

java
1
2
3
4
5
6
7
8
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);
}
}
}

调用invokeCallback方法

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
}
}

这个方法最终是反射调用。而method在addObserver的时候已经通过解析注解,保存了起来。

最后,附一张简单的时序图:

Lifecycle时序图

文章作者: milovetingting
文章链接: http://www.milovetingting.cn/2020/04/14/Android/Jetpack%E5%AD%A6%E4%B9%A0-Lifecycle/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 milovetingting

评论