Jetpack是谷歌在Google I/O 2017大会上发布一套帮助开发者解决Android架构设计的方案,而Lifecycle是Jetpack architecture下的一部分,一起来看一下Lifecycle的使用及原理分析。
一.什么是Lifecycle
Lifecycle 是android.arch.lifecycle 包下各种类和相关接口,androidx已经加入了对Lifecycle的支持,通过该Lifecycle 组件可以让开发者构建能够感知其他组件(主要是Activity,Fragment)的生命周期的变化。也就是说通过注册Lifecycle的类,可以监听Activity或者Fragment的生命周期的变化。
二.关键类
a.Lifecycle
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();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
Lifecycle是一抽象类,看起来也非常简洁,添加观察者、移除观察者、当前状态,以及event和state的设计,需要有具体的实现类。
b.LifecycleRegistry
public class LifecycleRegistry extends Lifecycle {
......
......
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
.....
.....
}
LifecycleRegistry继承了Lifecycle抽象类,相关的逻辑调用都是通过LifecycleRegistry来实现的。
c.LifeCycleOwner
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
LifecycleOwner从字面意思来看是Lifecycle的拥有者,activity或Fragment要想有可被观察的生命周期,需要实现LifecycleOwner接口。
d.LifecycleObserver
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
* <p>
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}
一个LifecycleOwner和一个LifecycleObserver,然后观察起来就好了,这样LifecycleObserver就会跟随LifecycleOwner的生命周期了,而实现LifecycleObserver的需要将自己的生命周期方法加上注释@OnLifecycleEvent来监听生命周期的变化。
三.基本使用
加入依赖
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
继承AppCompatActivity后,就自动实现了LifecycleOwner接口,即已经具备了LifecycleOwner,只需要自己实现LifecycleObserver,然后addObserver就可以建立生命周期监听了。
先看一下继承AppCompatActivity的实现方式:
1.继承AppCompatActivity
public class DebugActivity extends AppCompatActivity {
private DebugActivityLifecycleObserver mDebugActivityLifecycleObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_debug);
mDebugActivityLifecycleObserver = new DebugActivityLifecycleObserver();
getLifecycle().addObserver(mDebugActivityLifecycleObserver);
}
@Override
protected void onDestroy() {
super.onDestroy();
getLifecycle().removeObserver(mDebugActivityLifecycleObserver);
}
}
前面说到,继承AppCompatActivity后就自动实现了LifecycleOwner接口,后面章节会详细分析源码逻辑。
2.实现LifecycleObserver
public class DebugActivityLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.e("Seven", "onCreate: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.e("Seven", "onStart: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.e("Seven", "onResume: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.e("Seven", "onPause: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.e("Seven", "onStop: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.e("Seven", "onDestroy: " );
}
}
实现了LifecycleObserver接口后,直接在Activity中通过getLifecycle()来执行addObserver(observer)就建立了监听关系,接下来如果activity的生命周期发生变化后,都会回调observer的对应的生命周期方法。
3.运行结果
//启动后
11-07 15:43:47.839 E/Seven (14799): onCreate:
11-07 15:43:47.844 E/Seven (14799): onStart:
11-07 15:43:47.846 E/Seven (14799): onResume:
//按back键后
11-07 15:44:32.911 E/Seven (14799): onPause:
11-07 15:44:33.537 E/Seven (14799): onStop:
11-07 15:44:33.543 E/Seven (14799): onDestroy:
通过运行可以发现,DebugActivityLifecycleObserver可以监听到DebugActivity生命周期的变化。
如果Activity没有继承AppCompatActivity,那应该如何监听其生命周期的变化呢?接下来看一下如何实现:
1.实现LifecycleOwner接口
public class HookActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mRegistry;
private HookActivityLifecycleObserver mHookActivityLifecycleObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hook);
mHookActivityLifecycleObserver = new HookActivityLifecycleObserver();
mRegistry = new LifecycleRegistry(this);
//注册需要监听的 Observer
mRegistry.addObserver(mHookActivityLifecycleObserver);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
@Override
protected void onDestroy() {
super.onDestroy();
mRegistry.removeObserver(mHookActivityLifecycleObserver);
}
}
实现LifecycleOwner后,实现getLifecycle(),后续生命周期变化时会通过getLifecycle()获取到LifecycleRegistry来进行事件分发,创建LifecycleRegistry[即Lifecycle的实现类]实例,然后把自己作为参数传入,持有LifecycleOwner的弱引用:
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
在getLifecycle()内返回创建好的LifecycleRegistry,最后addObserver建立观察就行了。
2.实现LifecycleEventObserver接口
public class HookActivityLifecycleObserver implements LifecycleEventObserver {
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
if (source.getLifecycle().getCurrentState() == Lifecycle.State.CREATED) {
Log.e("Seven", "------------onCreate");
} else if (event == Lifecycle.Event.ON_START) {
Log.e("Seven", "------------onStart");
} else if (source.getLifecycle().getCurrentState() == Lifecycle.State.RESUMED) {
Log.e("Seven", "------------onResumed");
} else if (event == Lifecycle.Event.ON_PAUSE) {
Log.e("Seven", "------------onPause");
} else if (source.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
Log.e("Seven", "------------onDestroy");
} else if (event == Lifecycle.Event.ON_STOP) {
Log.e("Seven", "------------onStop");
}
}
}
LifecycleEventObserver继承了LifecycleObserver接口,内部有onStateChanged()可以监听状态的变化,当生命周期发生变化后会回调observer,可以通过source.getLifecycle().getCurrentState()或Lifecycle.Event来监听当前的生命周期状态。
3.运行结果
//启动后
11-07 15:42:35.192 E/Seven (14677): ------------onCreate
11-07 15:42:35.199 E/Seven (14677): ------------onStart
11-07 15:42:35.202 E/Seven (14677): ------------onResumed
//按back键后
11-07 15:42:39.828 E/Seven (14677): ------------onPause
11-07 15:42:40.233 E/Seven (14677): ------------onCreate
11-07 15:42:40.238 E/Seven (14677): ------------onDestroy
通过运行可以发现,DebugActivityLifecycleObserver可以监听到DebugActivity生命周期的变化。
四.Lifecycle相关源码分析
前面分析到,当Activity继承AppCompatActivity后,本身就是LifeCycleOwner了,通过源码调用关系可以发现,最终实现LifeCycleOwner的类是ComponentActivity,先看一下该类的内部逻辑:
1.ComponentActivity
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,xxxxx {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
........
........
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
........
}
通过以上可以看到,该类实现了LifecycleOwner接口,内部创建了LifecycleRegistry实例,然后在onCreate()是调用了ReportFragment.injectIfNeededIn(this),还有一个方法就是getLifecycle()来获取LifecycleRegistry对象。
2.ReportFragment
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
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();
}
}
执行injectIfNeededIn()时,1.先判断如果SDK大于29后,直接可以注册callback;2.在acitivity上添加一个Fragment,通过fragment的生命周期来反映出Activity的生命周期变化。
@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);
mProcessListener = null;
}
通过以上可以发现,Fragment在所以生命周期发生变化时,都会执行dispatch()对应生命周期的表示,接下来看一下dispatch()内部是如何将activity的生命周期通知出去的呢?
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
.......
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
首先判断该activity是否是LifecycleOwner的一个实例,然后通过getLifecycle()来获取到Lifecycle,最后通过LifecycleRegistry的handleLifecycleEvent()来对生命周期事件进行分发通知,再看一下LifecycleRegistry的实现:
3.LifecycleRegistry
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
......
sync();
......
}
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
......
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;
}
//backwardPass、forwardPass会调用到ObserverWithState即如下逻辑:
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
在调用handleLifecycleEvent()后,会先调用getStateAfter(event),通过event来判断接下来要进入的state,Lifecycle内部的Event与State对应的执行关系如下:
然后执行moveToState(),然后调用sync(),在sync()内部通过mState来判断是执行backwardPass()还是forwardPass(),在其两个方法内部,会调用到ObserverWithState的dispatchEvent(),再一起看一下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 = getStateAfter(event);
mState = min(mState, newState);
//状态变化通知
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
构造方法内会传入LifecycleObserver,即本地需要实现的生命周期监听类,该类是在addObserver时传入的,ObserverWithState是在什么地方创建的呢?接下来看一下以下方法:
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
}
接着上面的讲,在调用内部类ObserverWithState的dispatchEvent()来通知生命周期,我们可以看到,在ObserverWithState的构造方法内,会通过Lifecycling.lifecycleEventObserver(observer)来创建LifecycleEventObserver,最终调用onStateChanged()方法。
4.Lifecycling
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
.......
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
.......
return new ReflectiveGenericLifecycleObserver(object);
}
在lifecycleEventObserver内部,通过object[即传入的observer]来进行判断,如果是LifecycleEventObserver,则直接返回该observer,直接会回调实现类的onStateChanged()方法,上述实例有用到;如果observer没有实现lifecycleEventObserver,那么会返回ReflectiveGenericLifecycleObserver实例。
5.ReflectiveGenericLifecycleObserver
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
ReflectiveGenericLifecycleObserver实现了LifecycleEventObserver,构造方法内,通过ClassesInfoCache来获取CallbackInfo实例mInfo,在onStateChanged内通过mInfo.invokeCallbacks()来进行回调处理,CallbackInfo是ClassesInfoCache的内部类,一起看一下这两个类:
6.ClassInfoCache
CallbackInfo getInfo(Class<?> klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
先从Hashmap里面去获取,如果不存在的话,就执行createInfo()来进行创建,看一下createInfo()这个方法:
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
........//没有父类,直接跳过
.......//接口判断5
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;
......
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
........
}
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;
}
从上面可以看到,在执行createInfo()时,先创建了handlerToEvent来存储MethodReference、Lifecycle.Event键值对;
接下来通过getDeclaredMethods()来获取到class内部所有方法,然后来遍历方法是否有OnLifecycleEvent.class的注解,有的话,再判断方法的参数个数,根据参数个数来确定invoke()时的传参,最多有两个参数;
然后将method和callType封装成MethodReference(),通过verifyAndPutHandler()将MethodReference、Lifec5ycle.Event存储到handlerToEvent内;
最后创建CallbackInfo(),传入参数handlerToEvent,将info存入mCallbackMap内。
7.ClassInfoCache$CallbackInfo
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);
}
}
}
}
通过以上可以看到,在创建CallbackInfo时,将Map<MethodReference, Lifecycle.Event>改为了Map<Lifecycle.Event, List<MethodReference>>,根据Event来获取到对应的MethodReference列表,在前面的ReflectiveGenericLifecycleObserver讲到,在调用onStateChanged()时,会调用到CallbackInfo的invokeCallbacks()方法,以上可以看到,会最终调用到MethodReference的invokeCallback()方法,一起看一下:
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) {
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;
}
}
}
......
}
MethodReference内部会存储着Method及callType,在invokeCallback()内部直接通过反射mMethod.invoke(target)直接回调本地自定义LifecycleObserver内部对应的方法了。
以上就是对Lifecycle生命周期注册及通知的整个流程。
五.总结
最后用一张流程图总结一下:
实现了ComponentActivity的子类在onCreate()时会调用ReportFragment的injectIfNeededIn(this),然后通过getLifecycle()获取到LifecycleRegistry实例,调用实例的addObserver(xx)将本地的observer注册进去就建立了监听;
接下来当Activity的生命周期发生变化后,会反映到ReportFragment的生命周期,来一步一步的进行调用最终通知到本地的observer进行处理。