Lifecycle学习

用于构建生命周期感知组件的类和接口,这些组件可以根据 Activity 或 Fragment 的当前生命周期自动调整其行为,在support版本为26.1.0中默认的AppCompatActivity和fragment已经集成这个功能。

用法

(1)首先让你的类实现LifecycleObserver接口,在类方法上加上注解OnLifecycleEvent

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
public class LifecycleTest implements LifecycleObserver {
private static final String TAG = "LifecycleTest";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
}

其中的Event为以下代码

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
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}

很清晰的看到各种的值对应的生命周期的哪个方法。

(2)在activity或者fragmetn中注册

1
getLifecycle().addObserver(new LifecycleTest());

源码分析

从addObserver这个方法切入,Lifecycle是一个抽象类,它的实现类是LifecycleRegistry,从下面我们可以猜测到运用了典型的观察者模式。

1
2
3
4
5
6
7
8
@MainThread
public abstract void addObserver(LifecycleObserver observer);
@MainThread
public abstract void removeObserver(LifecycleObserver observer);
@MainThread
public abstract State getCurrentState();
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
public class LifecycleRegistry extends Lifecycle {
....省略代码
@Override
public void addObserver(LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
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(mLifecycleOwner, 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--;
}
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
//noinspection TryWithIdenticalCatches
try {
final Class<?> klass = object.getClass();
Constructor<? extends GenericLifecycleObserver> cachedConstructor = sCallbackCache.get(
klass);
if (cachedConstructor != null) {
return cachedConstructor.newInstance(object);
}
cachedConstructor = getGeneratedAdapterConstructor(klass);
if (cachedConstructor != null) {
if (!cachedConstructor.isAccessible()) {
cachedConstructor.setAccessible(true);
}
} else {
cachedConstructor = sREFLECTIVE;
}
sCallbackCache.put(klass, cachedConstructor);
return cachedConstructor.newInstance(object);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public interface GenericLifecycleObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
//缓存ReflectiveGenericLifecycleObserver实例
@SuppressWarnings("WeakerAccess")
static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>();
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = getInfo(mWrapped.getClass());
}
private static CallbackInfo getInfo(Class klass) {
CallbackInfo existing = sInfoCache.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass);
return existing;
}
private static CallbackInfo createInfo(Class klass) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Method[] methods = klass.getDeclaredMethods();
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Entry<MethodReference, Event> entry : getInfo(intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
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");
}
}
Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != 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);
sInfoCache.put(klass, info);
return info;
}
}

ObserverWithState这个类保持当前的状态和GenericLifecycleObserver,其中GenericLifecycleObserver也是个接口,实现类为ReflectiveGenericLifecycleObserver,就是把LifecycleObserver添加了onStateChanged()的方法,这样在ObserverWithState的dispatchEvent的方法中调用onStateChanged,来通知状态发生变化,从而达到要调用那个注解方法,ReflectiveGenericLifecycleObserver里面有CallbackInfo mInfo,其实就是反射获取你添加了OnLifecycleEvent的注解的方法,以便到时候调用。

activity的生命周期和LifecycleRegistry关联,其中有个SupportActivity类,

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
public class SupportActivity extends Activity implements LifecycleOwner {
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
public class ReportFragment extends Fragment {
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();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
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);
}
}
}
}

就是通过添加个空的ReportFragment来监听activity的生命周期的变化(貌似很多地方都用到了这个),通过监听ReportFragment生命周期调用dispatch(Lifecycle.Event.ON_CREATE),最后到LifecycleRegistry的handleLifecycleEvent方法。

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
public void handleLifecycleEvent(Lifecycle.Event event) {
mState = getStateAfter(event);
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
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();
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass();
}
}
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;
}
private void forwardPass() {
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(mLifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
static class CallbackInfo {
final Map<Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Event> mHandlerToEvent;
}

sync同步状态,isSynced判断要不要同步,它是比较当前的状态和我们存我们存放观察者的集合最早或最新放入的观察者的状态,当前状态比之前状态消的时候就是要回滚,好比从OnPause到OnResume,则调用backwardPass回退,forwardPass则为前进,最后调用
dispatchEvent方法就是,ObserverWithState的,最后调用onStateChanged,之前CallbackInfo的mEventToHandlers根据key就是事件,vaule就是方法,通过事件获取方法最后调用方法,从value是个list可以看出你可以给多个方法注解同个生命周期。

总结

大致的流程就是通过在activity添加个空的fragment来和activity的生命周期同步,然后再调用LifecycleRegistry的handleLifecycleEvent方法到ObserverWithState的dispatchEvent方法到ReflectiveGenericLifecycleObserver的onStateChanged方法,根据注解方法获取各自监听生命周期的方法再调用,只是官方做的更加的完善方便。第一次写分析文章,大部分都是源码很少解读的,希望以后能够改进,通过这次的分析,可以学习到可以通过设置个空的fragment来监听activity的生命周末,很多高度抽象的东西,比如LifecycleObserver你只要实现,很多东西就会自动生成,让开发者集成更加的方便。