1. 原理
基于Android10.0
源码
Lifecycle.java
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
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
Lifecycle是一个抽象类,内部有Event和State两种枚举类,用于对应生命周期,其中ON_ANY可用于对应任何事件。也有addObserver和removeObserver方法用于添加和删除观察者
由于Activity和Fragment默认实现了LifecycleOwner接口,LifecycleOwner即被观察者。以Activity举例,MainActivity继承了AppCompatActivity,而AppCompatActivity又继承于FragmentActivity。在Android 8.0时,FragmentActivity继承于SupportActivity,在Android 9.0时继承于ComponentActivity,两者相差不大,这里分析后者
ComponentActivity.java
@RestrictTo(LIBRARY_GROUP)
public class ComponentActivity extends Activity implements LifecycleOwner {
private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
new SimpleArrayMap<>();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@RestrictTo(LIBRARY_GROUP)
public void putExtraData(ExtraData extraData) {
mExtraDataMap.put(extraData.getClass(), extraData);
}
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
@RestrictTo(LIBRARY_GROUP)
public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
return (T) mExtraDataMap.get(extraDataClass);
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@RestrictTo(LIBRARY_GROUP)
public static class ExtraData {
}
}
开头的变量声明了LifecycleRegistry,是Lifecycle的实现类,并且在倒数第2个方法getLifecycle里返回实现类对象
在中间onSaveInstanceState方法里设置了最初的声明周期状态CREATED,其余状态由上面onCreate方法里的ReportFragment设置
ReportFragment.java
/**
* Internal class that dispatches initialization events.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@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;
}
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);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
开头的注释说明“分发初始化事件的内部类”。观察每一个声明周期方法里都会调用dispatch方法
dispatch方法里会先判断当前activity是否实现了LifecycleRegistryOwner接口或LifecycleOwner接口。与LifecycleOwner接口不同的是:LifecycleRegistryOwner接口定义的getLifecycle方法返回的是LifecycleRegistry,而LifecycleOwner接口定义的getLifecycle方法返回的是Lifecycle
回到方法里,判断activity实现了LifecycleOwner接口后,那么会调用LifecycleRegistry的handleLifecycleEvent方法
LifecycleRegistry.java的handleLifecycleEvent
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
这个方法用于设置当前的状态,并且提醒观察者,如果当前状态和最后一次调用这个方法时的状态是一样的,那么这个方法没有任何作用
getStateAfter方法将会获取即将到来的事件,当前事件执行后,即将会处于什么样的事件
LifecycleRegistry.java的getStateAfter
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
这个方法说明了event为ON_STOP的时候会返回CREATED,等等状态的声明时机,回到刚刚的handleLifecycleEvent,还有一个方法moveToState
LifecycleRegistry.java的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操作
LifecycleRegistry.java的sync
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;
}
开头进行判空操作,如果为空则警告LifecycleOwner已经被垃圾回收
在while循环里进行当前State和mObserverMap里的eldest状态和newest状态进行对比,判断当前状态向前还是向后,分别调用不同的方法
LifecycleRegistry.java的backwardPass和forwardPass
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
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();
}
}
}
这里大体逻辑相同,将状态封装为一个迭代器,当迭代器中还有元素,并且新的事件没有发生时,拿到ObserverWithState,并且调用其dispatchEvent方法进行事件的up或down,先看dispatchEvent方法
ObserverWithState的dispatchEvent
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;
}
}
ObserverWithState是LifecycleRegistry的一个静态内部类,包括了State,GenericLifecycleObserver。后者是一个接口,继承了LifecycleObserver接口
ReflectiveGenericLifecycleObserver 和 CompositeGeneratedAdaptersObserver是GenericLifecycleObserver的实现类,我们主要看ReflectiveGenericLifecycleObserver的onStateChanged方法
ReflectiveGenericLifecycleObserver.java的onStateChanged
/**
* An internal implementation of {@link GenericLifecycleObserver} that relies on reflection.
*/
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
方法里会调用CallbackInfo的invokeCallbacks方法,先来看看CallbackInfo是怎么实现的
CallbackInfo.java
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
···
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();
···
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;
}
开头,for循环遍历方法,获取注解OnLifecycleEvent,就是我们实现LifecycleObserver时用到的。而后将annotaion的value赋值给event,即@OnLifecycleEvent中定义的事件
新建一个MethodReference,其内部包括使用了该注解的方法。下一行verifyAndPutHandler方法用于将MethodReference和对应的Event存入类型为Map<MethodReference, Lifecycle.Event>的handlerToEvent中
最后创建CallbackInfo,传入handlerToEvent。回到上面的onStateChanged,查看invokeCallbacks
CallbackInfo.java的invokeCallbacks
@SuppressWarnings("WeakerAccess")
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
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);
}
}
}
}
第一个for循环处,handlerToEvent调用entrySet进行数据类型转换,转换为HashMap,其中key为event事件,value为MethodReference
invokeCallbacks方法里会调用invokeMethodsForEvent方法,传入mEventToHandlers.get(event)参数,也就是事件对应的MethodReference集合
在invokeMethodsForEvent方法中会遍历MethodReference的集合,调用MethodReference的invokeCallback方法
ClassesInfoCache.java的MethodReference
@SuppressWarnings("WeakerAccess")
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
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);
}
}
···
开头处有两个变量,mCallType,表示调用方法的类型。mMethod就代表方法
在invokeCallback方法中,无论是哪种callType都会通过invoke对方法进行反射
简单来说,就是实现LifecycleObserver接口的类中,注解修饰的方法和事件会被保存起来,通过反射对事件进行调用
2. 流程总结
从ComponentActivity开始,在onCreate方法中进入ReportFragment的injectIfNeededIn方法
在ReportFragment中,dispatch方法里调用LifecycleRegistry的handleLifecycleEvent设置状态
设置好状态后会通过moveToState,进行sync同步,判断此时的状态是向前还是向后,分别调用不同的方法
以forwardPass举例,内部创建ObserverWithState,以upEvent或downEvent作为参数传入ObserverWithState的dispatchEvent方法
由GenericLifecycleObserver的实现类ReflectiveGenericLifecycleObserver在dispatchEvent方法中调用onStateChanged方法,进入CallbackInfo的invokeCallbacks方法
由于CallbackInfo通过for循环获取我们声明的OnLifecycleEvent注解,拿到event。新建MethodReference包括了使用该注解的方法进行保存
所以最后invokeCallbacks就是通过反射对上面保存过的方法和事件进行调用
3. 有关类名区分
有些类名和作用有些相似,容易引起困惑,这里记录一下
Lifecycle
抽象类,感知生命周期的组件
LifecycleRegistry
普通类,继承Lifecycle,处理多个观察者
LifecycleObserver
观察者接口
LifecycleOwner
被观察者接口,Activity和Fragment默认实现此接口
LifecycleRegistryOwner
接口,继承LifecycleOwner接口,已被废弃
4. 应用举例
MyChronometer
public class MyChronometer extends Chronometer implements LifecycleObserver {
private long eplasedTime;
public MyChronometer(Context context, AttributeSet attrs) {
super(context, attrs);
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private void startMeter(){
setBase(SystemClock.elapsedRealtime() - eplasedTime);
start();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private void stopMeter(){
eplasedTime = SystemClock.elapsedRealtime() - getBase();
stop();
}
}
实现一个自定义的Chronometer,计时器,继承于TextView用于显示当前时间,通过注解与生命周期绑定方法,解耦于MainActivity
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".baseLifecycle.MainActivity">
<com.example.lifecycle.baseLifecycle.MyChronometer
android:id="@+id/chronometer"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
将自定义布局添加进xml
MainActivity
public class MainActivity extends AppCompatActivity {
private MyChronometer chronometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.chronometer);
getLifecycle().addObserver(chronometer);
}
}
Activity中先拿到Lifecycle对象,再把观察者添加进布局即可