1 簡(jiǎn)介和簡(jiǎn)單使用
1.1 簡(jiǎn)介
Lifecycle是Jetpack中一個(gè)生命周期感知型組件载城,可執(zhí)行操作來(lái)響應(yīng)另一個(gè)組件(如 Activity 和 Fragment)的生命周期狀態(tài)的變化冤狡。
該組件通過(guò)感知Activity 和 Fragment的生命周期事件,在內(nèi)部維護(hù)一個(gè)狀態(tài)宋列,該狀態(tài)又可以轉(zhuǎn)換成生命周期事件薇缅。主要作用就是進(jìn)行系統(tǒng)組件的生命周期和普通組件的解耦丘侠,可以使得在正確的生命周期下做正確的操作徒欣,即使釋放資源,減少內(nèi)存泄漏蜗字。有助于寫(xiě)出更有條理且更精簡(jiǎn)的代碼帚称。
官網(wǎng):https://developer.android.google.cn/jetpack/androidx/releases/lifecycle
1.2 簡(jiǎn)單使用
按需引入依賴官研。
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")
}
創(chuàng)建MyServiceObserver,實(shí)現(xiàn)LifecycleObserver接口闯睹,模擬某個(gè)服務(wù)的使用戏羽。
class MyServiceObserver : LifecycleObserver {
private val TAG = "MyServiceObserver"
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() = Log.d(TAG, "onCreate 服務(wù)啟動(dòng)...")
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() = Log.d(TAG, "onStart 服務(wù)連接...")
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() = Log.d(TAG, "onResume 服務(wù)運(yùn)行...")
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() = Log.d(TAG, "onPause 服務(wù)暫停...")
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() = Log.d(TAG, "onStop 服務(wù)斷開(kāi)...")
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() = Log.d(TAG, "onDestroy 服務(wù)銷毀...")
}
在Activity中使用lifecycle.addObserver(MyServiceObserver())來(lái)綁定觀察者和被觀察者,觀察者就是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 觀察者中的方法執(zhí)行原理
首先,在業(yè)務(wù)層LifecycleActivity中添加一個(gè)自定義Observer孩锡,這個(gè)自定義Observer實(shí)現(xiàn)了LifecycleObserver接口酷宵。
//在業(yè)務(wù)層Activity中添加觀察者
lifecycle.addObserver(MyServiceObserver())
LifecycleActivity最終繼承的是ComponentActivity,ComponentActivity實(shí)現(xiàn)了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荣挨,實(shí)現(xiàn)了addObserver方法男韧。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//實(shí)例化一個(gè)狀態(tài)機(jī),觀察者和被觀察者共維護(hù)一個(gè)狀態(tài)機(jī)中的狀態(tài)
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
...
}
ObserverWithState是LifecycleRegistry中的一個(gè)靜態(tài)內(nèi)部類默垄,在這里會(huì)產(chǎn)生一個(gè)LifecycleEventObserver此虑。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//根據(jù)觀察者和狀態(tài)機(jī)初始狀態(tài)產(chǎn)生一個(gè)LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//調(diào)用ReflectiveGenericLifecycleObserver的onStateChanged方法,
//onStateChanged方法中會(huì)使用反射
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
LifecycleEventObserver的實(shí)例化對(duì)象是它的實(shí)現(xiàn)類ReflectiveGenericLifecycleObserver口锭。
static LifecycleEventObserver lifecycleEventObserver(Object object) {
...
return new ReflectiveGenericLifecycleObserver(object);
}
在ReflectiveGenericLifecycleObserver中朦前,會(huì)傳入業(yè)務(wù)層添加的觀察者,通過(guò)反射去執(zhí)行觀察者中的方法鹃操。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//這里做了一個(gè)Map緩存韭寸,提高了一些性能。
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//通過(guò)反射荆隘,去執(zhí)行觀察者中的方法恩伺。
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
2.2 狀態(tài)機(jī)和狀態(tài)維護(hù)原理
在ComponentActivity的onCreate方法中,綁定了一個(gè)ReportFragment臭胜。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
ReportFragment.injectIfNeededIn(this);
...
}
ReportFragment是Lifecycle庫(kù)里一個(gè)空白不帶UI的Fragment,它和Glide原理一樣癞尚,附著于Activity耸三,然后監(jiān)聽(tīng)Fragment的生命周期,然后去同步狀態(tài)機(jī)的狀態(tài)浇揩。
這里不直接在Activity中監(jiān)聽(tīng)生命周期仪壮,是因?yàn)橛肍ragment獨(dú)立出來(lái)之后,可以附著于任何Activity胳徽,而不僅僅是CompatActivity积锅,方便擴(kuò)展爽彤。
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
//API29開(kāi)始,使用ActivityLifecycleCallbacks缚陷,
//在它的實(shí)現(xiàn)類ActivityLifecycleCallbacks中去分發(fā)各個(gè)生命周期的事件
LifecycleCallbacks.registerIn(activity);
}
//API29以前适篙,在ReportFragment的生命周期回調(diào)方法中中去分發(fā)事件
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();
}
}
在這里谷歌做了一個(gè)高版本兼容,使用ActivityLifecycleCallbacks箫爷,猜測(cè)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) {
//調(diào)用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);
//調(diào)用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
//調(diào)用dispatch(Activity activity, Lifecycle.Event event)
dispatch(getActivity(), event);
}
}
}
可以看到虎锚,不管是API>=29還是小于29硫痰,最終都會(huì)調(diào)用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實(shí)現(xiàn)了LifecycleOwner接口窜护,所以會(huì)走到這里
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
接著調(diào)用了LifecycleRegistry的handleLifecycleEvent方法效斑。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
//獲取最新的狀態(tài),然后對(duì)齊柱徙。
moveToState(event.getTargetState());
}
這里首先通過(guò)Lifecycle的getTargetState方法獲取最新的狀態(tài)缓屠,這就是狀態(tài)機(jī)的核心,根據(jù)Activity的聲明周期事件驅(qū)動(dòng)獲取到狀態(tài)機(jī)的狀態(tài)坐搔。本文后邊會(huì)進(jìn)行詳細(xì)圖解藏研。
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");
}
然后調(diào)用moveToState進(jìn)行了狀態(tài)對(duì)齊。把Activity的生命周期事件轉(zhuǎn)換成對(duì)應(yīng)的狀態(tài)機(jī)狀態(tài)概行。
private void moveToState(State next) {
...
sync();
...
}
sync方法用來(lái)同步狀態(tài)蠢挡,里面對(duì)當(dāng)前的狀態(tài)和新舊狀態(tài)枚舉值進(jìn)行了比較。
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;
//當(dāng)前狀態(tài)比舊狀態(tài)的值小凳忙,狀態(tài)機(jī)的狀態(tài)需要回退
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//狀態(tài)回退
backwardPass(lifecycleOwner);
}
Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
//當(dāng)前狀態(tài)比舊狀態(tài)值大业踏,狀態(tài)機(jī)的狀態(tài)需要前進(jìn)
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//狀態(tài)前進(jìn)
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
狀態(tài)前進(jìn)。
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);
//前進(jìn)階段 調(diào)用Event.upFrom(State state)獲取到對(duì)應(yīng)的事件
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
//分發(fā)事件
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;
}
}
狀態(tài)后退涧卵。
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()))) {
//后退階段 調(diào)用Event.downFrom(State state)獲取到對(duì)應(yīng)的事件
Event event = Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
//分發(fā)事件
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;
}
}
狀態(tài)同步之后勤家,調(diào)用ObserverWithState的dispatchEvent方法,進(jìn)行事件分發(fā)處理柳恐,這樣就和本文2.1中的最后一部分關(guān)聯(lián)起來(lái)了伐脖。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//根據(jù)觀察者和狀態(tài)機(jī)初始狀態(tài)產(chǎn)生一個(gè)LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//調(diào)用ReflectiveGenericLifecycleObserver的onStateChanged方法,
//onStateChanged方法中會(huì)使用反射
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
最后調(diào)用ReflectiveGenericLifecycleObserver的onStateChanged方法乐设,在onStateChanged方法中調(diào)用invokeCallbacks使用反射執(zhí)行觀察者中的方法讼庇。
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
//這里做了一個(gè)Map緩存,提高了一些性能近尚。
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//通過(guò)反射蠕啄,去執(zhí)行觀察者中的方法。
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
至此,已經(jīng)完成了整個(gè)Lifecycle的原理分析歼跟。
3 原理圖解
3.1 狀態(tài)機(jī)原理圖解
Activity的生命周期就是事件和媳,事件去驅(qū)動(dòng)狀態(tài)機(jī)生成對(duì)應(yīng)的狀態(tài),然后狀態(tài)機(jī)再根據(jù)狀態(tài)計(jì)算出對(duì)應(yīng)的生命周期哈街。狀態(tài)機(jī)的作用是提供給其他框架使用留瞳,比如LiveData、VideModel等等叹卷。
對(duì)應(yīng)的核心代碼:
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原理流程圖
這個(gè)流程圖是對(duì)上邊源碼分析的一個(gè)歸納撼港,分析源碼的同時(shí)結(jié)合流程圖能更加便于理解和記憶。
關(guān)注木水小站 (zhangmushui.cn)和微信公眾號(hào)【木水Code】骤竹,及時(shí)獲取更多最新文章帝牡。