1 简介和简单使用
1.1 简介
Lifecycle是Jetpack中一个生命周期感知型组件,可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。
该组件通过感知Activity 和 Fragment的生命周期事件,在内部维护一个状态,该状态又可以转换成生命周期事件。主要作用就是进行系统组件的生命周期和普通组件的解耦,可以使得在正确的生命周期下做正确的操作,即使释放资源,减少内存泄漏。有助于写出更有条理且更精简的代码。
1.2 简单使用
按需引入依赖。
dependencies {
val lifecycle_version = "2.5.0-alpha06"
val arch_version = "2.1.0"
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
// ViewModel utilities for Compose
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
// Lifecycles only (without ViewModel or LiveData)
implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version")
// Saved state module for ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
// Annotation processor
kapt("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-ktx:$lifecycle_version")
// optional - Test helpers for LiveData
testImplementation("androidx.arch.core:core-testing:$arch_version")
}
创建MyServiceObserver,实现LifecycleObserver接口,模拟某个服务的使用。
class MyServiceObserver : LifecycleObserver {
private val TAG = "MyServiceObserver"
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() = Log.d(TAG, "onCreate 服务启动...")
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() = Log.d(TAG, "onStart 服务连接...")
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() = Log.d(TAG, "onResume 服务运行...")
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() = Log.d(TAG, "onPause 服务暂停...")
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() = Log.d(TAG, "onStop 服务断开...")
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() = Log.d(TAG, "onDestroy 服务销毁...")
}
在Activity中使用lifecycle.addObserver(MyServiceObserver())来绑定观察者和被观察者,观察者就是MyServiceObserver,被观察者就是LifecycleActivity。
class LifecycleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lifecycle)
//在Activity中添加观察者
lifecycle.addObserver(MyServiceObserver())
}
}
2 源码分析
2.1 观察者中的方法执行原理
首先,在业务层LifecycleActivity中添加一个自定义Observer,这个自定义Observer实现了LifecycleObserver接口。
//在业务层Activity中添加观察者
lifecycle.addObserver(MyServiceObserver())
LifecycleActivity最终继承的是ComponentActivity,ComponentActivity实现了LifecycleOwner接口,所以上边的lifecycle是从ComponentActivity中获取的。
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
addObserver就是Lifecycle中的抽象方法。
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
LifecycleRegistry继承了Lifecycle,实现了addObserver方法。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//实例化一个状态机,观察者和被观察者共维护一个状态机中的状态
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
...
}
ObserverWithState是LifecycleRegistry中的一个静态内部类,在这里会产生一个LifecycleEventObserver。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//根据观察者和状态机初始状态产生一个LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//调用ReflectiveGenericLifecycleObserver的onStateChanged方法,
//onStateChanged方法中会使用反射
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
LifecycleEventObserver的实例化对象是它的实现类ReflectiveGenericLifecycleObserver。
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...
return new ReflectiveGenericLifecycleObserver(object);
}
在ReflectiveGenericLifecycleObserver中,会传入业务层添加的观察者,通过反射去执行观察者中的方法。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//这里做了一个Map缓存,提高了一些性能。
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//通过反射,去执行观察者中的方法。
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
2.2 状态机和状态维护原理
在ComponentActivity的onCreate方法中,绑定了一个ReportFragment。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
ReportFragment.injectIfNeededIn(this);
...
}
ReportFragment是Lifecycle库里一个空白不带UI的Fragment,它和Glide原理一样,附着于Activity,然后监听Fragment的生命周期,然后去同步状态机的状态。
这里不直接在Activity中监听生命周期,是因为用Fragment独立出来之后,可以附着于任何Activity,而不仅仅是CompatActivity,方便扩展。
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
//API29开始,使用ActivityLifecycleCallbacks,
//在它的实现类ActivityLifecycleCallbacks中去分发各个生命周期的事件
LifecycleCallbacks.registerIn(activity);
}
//API29以前,在ReportFragment的生命周期回调方法中中去分发事件
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();
}
}
在这里谷歌做了一个高版本兼容,使用ActivityLifecycleCallbacks,猜测Google可能想慢慢废弃空白Fragment这种做法,后边全部用ActivityLifecycleCallbacks。
API>=29
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}
...
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
//调用dispatch(Activity activity, Lifecycle.Event event)
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
...
}
API<29
public class ReportFragment extends android.app.Fragment {
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
//调用dispatch(Lifecycle.Event event)
dispatch(Lifecycle.Event.ON_CREATE);
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
//调用dispatch(Activity activity, Lifecycle.Event event)
dispatch(getActivity(), event);
}
}
}
可以看到,不管是API>=29还是小于29,最终都会调用ReportFragment的dispatch(Activity activity, Lifecycle.Event event)方法。
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
//由于ComponentActivity实现了LifecycleOwner接口,所以会走到这里
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
接着调用了LifecycleRegistry的handleLifecycleEvent方法。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
//获取最新的状态,然后对齐。
moveToState(event.getTargetState());
}
这里首先通过Lifecycle的getTargetState方法获取最新的状态,这就是状态机的核心,根据Activity的声明周期事件驱动获取到状态机的状态。本文后边会进行详细图解。
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
然后调用moveToState进行了状态对齐。把Activity的生命周期事件转换成对应的状态机状态。
private void moveToState(State next) {
...
sync();
...
}
sync方法用来同步状态,里面对当前的状态和新旧状态枚举值进行了比较。
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
while (!isSynced()) {
mNewEventOccurred = false;
//当前状态比旧状态的值小,状态机的状态需要回退
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//状态回退
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
//当前状态比旧状态值大,状态机的状态需要前进
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//状态前进
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
状态前进。
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//前进阶段 调用Event.upFrom(State state)获取到对应的事件
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
//分发事件
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
状态后退。
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
//后退阶段 调用Event.downFrom(State state)获取到对应的事件
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
//分发事件
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
public static Event downFrom(@NonNull State state) {
switch (state) {
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
default:
return null;
}
}
状态同步之后,调用ObserverWithState的dispatchEvent方法,进行事件分发处理,这样就和本文2.1中的最后一部分关联起来了。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//根据观察者和状态机初始状态产生一个LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//调用ReflectiveGenericLifecycleObserver的onStateChanged方法,
//onStateChanged方法中会使用反射
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
最后调用ReflectiveGenericLifecycleObserver的onStateChanged方法,在onStateChanged方法中调用invokeCallbacks使用反射执行观察者中的方法。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//这里做了一个Map缓存,提高了一些性能。
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//通过反射,去执行观察者中的方法。
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
至此,已经完成了整个Lifecycle的原理分析。
3 原理图解
3.1 状态机原理图解
Activity的生命周期就是事件,事件去驱动状态机生成对应的状态,然后状态机再根据状态计算出对应的生命周期。状态机的作用是提供给其他框架使用,比如LiveData、VideModel等等。
对应的核心代码:
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
3.2 Lifecycle原理流程图
这个流程图是对上边源码分析的一个归纳,分析源码的同时结合流程图能更加便于理解和记忆。