Lifecycle简介
一直以来,解藕都是软件开发永恒的话题。在Android开发中,解藕很大程度上表现为系统组件的生命周期与普通组件之间的解藕,因为普通组件在使用过程中需要依赖系统组件的的生命周期。
举个例子,我们经常需要在页面的onCreate()方法中对组件进行初始化,然后在onStop()中停止组件,或者在onDestory()方法中对进行进行销毁。事实上,这样的工作非常繁琐,会让页面和页面耦合度变高,但又不得不做,因为如果不即时的释放资源,有可能会导致内存泄露。例如,下面是一个在Activity的不同生命周期方法中监听调用的例子,代码如下。
public class MainActivity extends AppCompatActivity {
private MyListener myListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListener = new MyListener(MainActivity.this);
}
@Override
protected void onStart() {
super.onStart();
myListener.start();
}
@Override
protected void onStop() {
super.onStop();
myListener.stop();
}
}
class MyListener {
public MyListener(Context context) {
...
}
void start() {
...
}
void stop() {
...
}
}
虽然,代码看起来没什么问题,但在实际开发中可能会有多个组件在Activity的生命周期中进行回调,这样Activity的生命周期的方法中可能就需要编写大量的代码,这就使得它们难以维护。
我们希望在对组件进行管理不依赖页面的生命周期的回调方法,同时当页面生命周期发生改变时,也能够即时的收到通知。这在Android组件化和架构设计的时候表现的尤为明显。
那纠结什么是Lifecycle组件呢?总的来说,Lifecycle 就是具有生命周期感知能力的组件。简单的理解就是,当Activity/Fragment的生命周期产生变化时,Lifecycle组件会感应相应的生命周期变化,当然我们还可以通过使用Lifecycle组件来在自定义的类中管理Activity/fragment的生命周期。
目前,Lifecycle生命周期组件主要由Lifecycle、LifecycleOwner、LifecycleObserver三个对象构成。
- Lifecycle:是一个持有组件生命周期状态与事件(如Activity或Fragment)的信息的类。
- LifecycleOwner:Lifecycle的提供者,通过实现LifecycleOwner接口来访问Lifecycle生命周期对象。Fragment和FragmentActivity类实现了LifecycleOwner接口,它具有访问生命周期的getLifecycle方法,使用时需要在自己的类中实现LifecycleOwner。
- LifecycleObserver:Lifecycle观察者,可以使用LifecycleOwner类的addObserver()方法进行注册,被注册后LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。
Lifecycle使用
使用Lifecycle进行应用开发之前,需要先在app的build.gradle文件中添加如下依赖代码。
dependencies {
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
// Annotation processor
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// optional - helpers for implementing LifecycleOwner in a Service
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
// optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"
}
官网用的是AndroidX,因为使用AndroidX可能会产生一些迁移的问题,这里的例子就不使用AndroidX,使用lifecycleandroid.arch.lifecycle库即可,如下所示。
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
def lifecycle_version = "2.2.0"
// 包含ViewModel和LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// 仅仅包含ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
// 仅仅包含LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// 仅仅包含Lifecycles
implementation "android.arch.lifecycle:runtime:$lifecycle_version"
//noinspection LifecycleAnnotationProcessorWithJava8
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// 如果用Java8, 用于替代compiler
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
// 可选,ReactiveStreams对LiveData的支持
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
// 可选,LiveData的测试
testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
按照Lifecycle的使用流程,需要先定义观察者,并重写对应的生命周期,代码如下。
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(){
Log.d(TAG, "Lifecycle call onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(){
Log.d(TAG, "Lifecycle call onPause");
}
}
然后,我们在onCreate()方法中添加观察者,代码如下。
getLifecycle().addObserver(new MyObserver());
完整的代码如下所示。
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyObserver());
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
//自定义观察者
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(){
Log.d(TAG, "Lifecycle call onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(){
Log.d(TAG, "Lifecycle call onPause");
}
}
}
经过上面的处理后,MyObserver就可以观察MainActivity的生命周期变化了。在上面的示例中,LifecycleOwner可以理解为被观察者,MainActivity默认实现了LifecycleOwner接口,也就是说MainActivity是被观察者。运行上面的代码,得到如下的日志。
com.xzh.androidx D/MainActivity: MainActivity onResume
com.xzh.androidx D/MainActivity: Lifecycle call onResume
com.xzh.androidx D/MainActivity: Lifecycle call onPause
com.xzh.androidx D/MainActivity: MainActivity onPause
当然,在被观察者中进行注册时,我们还可以对代码进行拆解,写成下面的方式。
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private LifecycleRegistry registry;
private MyObserver myObserver = new MyObserver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
@Override
protected void onResume() {
super.onResume();
registry.setCurrentState(Lifecycle.State.RESUMED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return registry;
}
private void init() {
registry = new LifecycleRegistry(this);
registry.addObserver(myObserver);
}
... //省略MyObserver代码
}
在自定义的Activity或Fragment中实现LifeCycleOwner时,可以实现LifecycleRegistryOwner接口,如下所示。
public class MyFragment extends Fragment implements LifecycleRegistryOwner {
LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
@Override
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;
}
}
通过示例的分析可以发现,Android的Lifecycle组件需要先创建一个观察者,当组件生命周期发生变化时,通知观察者LifeCycle注解的方法做出响应。
Lifecycle源码分析
Lifecycle注册流程
Lifecycle使用两个枚举来跟踪其关联组件的生命周期状态,这两个枚举分别是Event和State。
- State:Lifecycle的生命周期所处的状态。
- Event:Lifecycle生命周期对应的事件,这些事件会映射到Activity和Fragment中的回调事件中。
打开lifecycle:common库下的Lifecycle类,
public abstract class Lifecycle {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@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两个枚举。并且,Event中的事件和Activity的生命周期几乎是对应的,除了ON_ANY,它可用于匹配所有事件。State与Event的生命周期关系的时序图如下图所示。
在Lifecycle抽象类中,enum枚举定义了所有State,各个状态都是按照固定的顺序来变化的,所以State具备了生命周期的概念。Lifecycle是抽象类,唯一的具体实现类为 LifecycleRegistry,源码如下。
public class LifecycleRegistry extends Lifecycle {
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
}
LifecycleRegistry将事件通知给所有观察者之前,存在一个同步的过程。这个同步的过程中,前面的观察者已经通知到了,后面的观察者还没被通知,于是所有观察者之间的状态就不一致了,各观察者状态之间便产生了差异,只有第一个观察者的状态等于最后一个观察者的状态,并且等于LifecycleRegistry中的当前状态mState,才说明状态同步整个完成了。
加下来,我们来看一下Lifecycle的注册流程,addObserver() 方法是注册观察者的入口,源码如下。
@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);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == 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(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// 重新计算状态,用于循环退出条件:直到observer的状态从INITIALIZED的状态递进到当前LifecyleOwner的状态
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
sync();
}
mAddingObserverCounter--;
}
在上面的源码中,代码的来前几行是将 state与observer 包装成ObserverWithState类型,state 的初始值为 INITIALIZED ,然后存入集合,如果observer之前已经存在的话,就认定重复添加,直接返回。当添加的observer为新的时候,执行循环流程。接着判断了一下isReentrance的值,表示是否重入,即是否需要同时执行添加addObserver()的流程或者同时有其他Event事件正在分发。然后,在while循环中,执行事件的分发逻辑。while循环中有两个比较重要的方法:dispatchEvent()
和 upEvent()
。
首先,我们来看一下dispatchEvent()
方法的源码,如下所示。
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);
// observer的回调函数
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
然后再调用了 observer的回调方法onStateChanged()更新组件的状态mState。
通知观察者
前面我们分析了Lifecycle的注册观察者的流程,接下来我们看一下Lifecycle又是如何通知Activity或Fragment的生命周期改变的呢?在Android 8.0时,FragmentActivity继承自SupportActivity,而在Android 9.0,FragmentActivity继承自ComponentActivity 。SupportActivity和ComponentActivity的代码区别不大,以ComponentActivity来说,源码如下。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
... //省略其他代码
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);
}
}
... //省略其他代码
}
接下来,我们看一下ReportFragment的源码。
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
dispatch(Lifecycle.Event.ON_START);
}
... //省略其他代码
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 通过注入一个没有UI的 ReportFragment ,然后在 ReportFragment的的生命周期回调中调用dispathch() 方法分发生命周期状态的改变。因为Fragment依赖于创建它的Activity,所以Fragment的生命周期和Activity生命周期同步,这样就间接实现了 Lifecycle 监听Activity生命周期的功能。接下来,看一下是dispatch()方法是如何分发Event的,源码如下。
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);
}
}
}
可以发现,在调用getActivity()方法后向上转型强制转换为LifecycleOwner,然后调用了LifecycleRegistry类的handleLifecycleEvent()方法,然后逻辑又回到了LifecycleRegistry类中,进而将事件Event分发交由LifecycleRegistry进行处理。其中,handleLifecycleEvent(event)的实现如下所示。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
// 将 mState 更新为当前的 State
mState = next;
...
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
更新了mState的值之后,就调用sync()方法,sync()方法就是根据 mState 的改变做出同步操作,并执行分发事件,sync()方法的源码如下。
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
// 判断是否需要同步,没有同步则一直进行
while (!isSynced()) {
mNewEventOccurred = false;
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;
}
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;
}
首先,通过调用isSynced() 方法来判断是否需要同步。isSynced()方法比较简单,主要通过比较第一个observer和最后一个observer,他们的 mState 值是否相等,相等的话则说明同步完毕,不相等的话继续同步,直到相等为止。
同时,sync()方法中会根据当前状态和mObserverMap中的eldest和newest的状态做对比 ,判断当前状态是向前还是向后,以向后为例。
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();//1
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));//2
popParentState();
}
}
}
forwardPass()方法最核心的就是获取ObserverWithState状态,ObserverWithState的代码如下。
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);//1
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
ObserverWithState类包括了State和GenericLifecycleObserver成员变量,GenericLifecycleObserver是一个接口,它继承了LifecycleObserver接口。
ReflectiveGenericLifecycleObserver和CompositeGeneratedAdaptersObserver是GenericLifecycleObserver的实现类,这里主要查看ReflectiveGenericLifecycleObserver的onStateChanged方法是如何实现的,源码如下。
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);//1
}
}
onStateChanged()方法会调用CallbackInfo的invokeCallbacks()方法,这里会用到CallbackInfo类,代码如下。
static class CallbackInfo {
final Map<Lifecycle.Event, List>> 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()) {//1
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);//2
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);//1
}
}
}
在CallbackInfo代码中,首先使用循环将handlerToEvent进行数据类型转换,转化为一个HashMap,key的值为事件,value的值为MethodReference。而invokeMethodsForEvent()方法会传入mEventToHandlers.get(event),也就是事件对应的MethodReference的集合。然后,invokeMethodsForEvent方法中会遍历MethodReference的集合,调用MethodReference的invokeCallback方法。其中,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) {
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);
}
}
...
}
MethodReference类中有两个变量,一个是callType,它代表调用方法的类型,另一个是Method,它代表方法,并最终通过invoke对方法进行反射,通过反射对事件的对应方法进行调用。