Android Jetpack 之 Lifecycle
前言
在日常的開發中,我們通常需要在 Activity / Fragment 的生命週期方法中進行一些繁重的操作,這樣使程式碼看起來十分臃腫。Lifecycle 的引入主要是用來管理和響應 Activity / Fragment 的生命週期的變化,幫助我們編寫出更易於組織且通常更加輕量級的程式碼,讓程式碼變得更易於維護。
Lifecycle 是一個類,它持有 Activity / Fragment 生命週期狀態的資訊,並允許其它物件觀察此狀態。
Lifecycle 使用
場景:讓 MVP 中的 Presenter 觀察 Activity 的 onCreate 和 onDestroy 狀態。
- Presenter 繼承 LifecycleObserver 介面
interface IPresenter : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate(owner: LifecycleOwner) @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy(owner: LifecycleOwner) @OnLifecycleEvent(Lifecycle.Event.ON_ANY) // ON_ANY 註解能觀察到其它所有的生命週期方法 fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) }
class MyPresenter : IPresenter { override fun onCreate(owner: LifecycleOwner) { Log.e(javaClass.simpleName, "onCreate") } override fun onDestroy(owner: LifecycleOwner) { Log.e(javaClass.simpleName, "onDestroy") } override fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) { // Log.e(javaClass.simpleName, "onLifecycleChanged") } }
- 在 Activity 中新增 LifecycleObserver
class MyLifecycleActivity : AppCompatActivity() {
private lateinit var myPresenter: MyPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_lifecycle)
Log.e(javaClass.simpleName, "onCreate")
myPresenter = MyPresenter()
lifecycle.addObserver(myPresenter) // 新增 LifecycleObserver
}
override fun onDestroy() {
Log.e(javaClass.simpleName, "onDestroy")
super.onDestroy()
}
}
啟動 Activity 會列印:
MyLifecycleActivity: onCreate
MyPresenter: onCreate
finish Activity 會列印:
MyPresenter: onDestroy
MyLifecycleActivity: onDestroy
以上 Presenter 物件只觀察了 Activity 的 onCreate 方法和 onDestroy 方法,我們還可以觀察其它的生命週期方法。在 Lifecycle 內部有個列舉類 Event , 它包含了 LifecycleObserver 能夠觀察到的所有生命週期方法,只需要新增上相應的註解即可。
enum class Event {
/**
* Constant for onCreate event of the [LifecycleOwner].
*/
ON_CREATE,
/**
* Constant for onStart event of the [LifecycleOwner].
*/
ON_START,
/**
* Constant for onResume event of the [LifecycleOwner].
*/
ON_RESUME,
/**
* Constant for onPause event of the [LifecycleOwner].
*/
ON_PAUSE,
/**
* Constant for onStop event of the [LifecycleOwner].
*/
ON_STOP,
/**
* Constant for onDestroy event of the [LifecycleOwner].
*/
ON_DESTROY,
/**
* An [Event] constant that can be used to match all events.
*/
ON_ANY
}
Lifecycle 內部還有代表了各個生命週期所處狀態的列舉類 State
enum class State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an [android.app.Activity], this state is reached
* before Activity's [onDestroy] call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an [android.app.Activity], this is
* the state when it is constructed but has not received
* [onCreate] yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an [android.app.Activity], this state
* is reached in two cases:
*
* after [onCreate] call;
* before [onStop] call.
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an [android.app.Activity], this state
* is reached in two cases:
*
* after [onStart] call;
* before [onPause] call.
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an [android.app.Activity], this state
* is reached after [onResume] is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given `state`.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given `state`
*/
fun isAtLeast(state: State): Boolean {
return compareTo(state) >= 0
}
}
在一般開發中,當 Activity 擁有多個 Presenter 並需要在各個生命週期做一些特殊邏輯時,程式碼可能是:
override fun onStop() {
presenter1.onStop()
presenter2.onStop()
presenter3.onStop()
super.onStop()
}
override fun onDestroy() {
presenter1.onDestroy()
presenter2.onDestroy()
presenter3.onDestroy()
super.onDestroy()
}
這樣會使 Activity 的程式碼變得很臃腫。
如果用 Lifecycle , 只需將持有 Lifecycle 物件的 Activity 的生命週期的響應分發到各個 LifecycleObserver 觀察者中即可。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_lifecycle)
lifecycle.addObserver(presenter1) // 新增 LifecycleObserver
lifecycle.addObserver(presenter2) // 新增 LifecycleObserver
lifecycle.addObserver(presenter3) // 新增 LifecycleObserver
}
基本原理
幾個概念
-
LifecycleObserver 介面
Lifecycle 觀察者。實現了該介面的類,被 LifecycleOwner 類的 addObserver 方法註冊後,通過註解的方式即可觀察到 LifecycleOwner 的生命週期方法。
-
LifecycleOwner 介面
Lifecycle 持有者。實現了該介面的類持有生命週期(Lifecycle 物件),該介面生命週期(Lifecycle 物件)的改變會被其註冊的觀察者 LifecycleObserver 觀察到並觸發其對應的事件。
-
Lifecycle 類
生命週期。和 LifecycleOwner 不同,LifecycleOwner 通過 getLifecycle() 方法獲取到內部的 Lifecycle 物件。
-
State
當前生命週期所處狀態。Lifecycle 將 Activity 的生命週期函式對應成 State .
-
Event
當前生命週期改變對應的事件。State 變化將觸發 Event 事件,從而被已註冊的 LifecycleObserver 接收。
實現原理
LifecycleOwner
AppCompatActivity 的父類 SupportActivity
和 Fragment
一樣,實現了 LifecycleOwner 介面,因此它們都擁有 Lifecycle 物件。
public class SupportActivity extends Activity implements LifecycleOwner, Component {
// ...
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return this.mLifecycleRegistry;
}
// ...
}
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
從原始碼可知 getLifecycle() 方法返回的是 LifecycleRegistry
物件,而 LifecycleRegistry 是 Lifecycle 的子類,所有對LifecycleObserver 的操作都是由 LifecycleRegistry 完成的。
LifecycleRegistry
生命週期登記處。作為 Lifecycle 的子類,它的作用是新增觀察者、響應生命週期事件和分發生命週期事件。
public class LifecycleRegistry extends Lifecycle {
// LifecycleObserver Map , 每一個 Observer 都有一個 State
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
// 當前的狀態
private State mState;
// Lifecycle 持有者,如繼承了 LifecycleOwner 的 SupportActivity
private final WeakReference<LifecycleOwner> mLifecycleOwner;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* 新增 LifecycleObserver 觀察者,並將之前的狀態分發給這個 Observer , 例如我們在 onResume 之後註冊這個 Observer ,
* 該 Observer 依然能收到 ON_CREATE 事件
*/
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
// ...
// 例如:Observer 初始狀態是 INITIALIZED , 當前狀態是 RESUMED , 需要將 INITIALIZED 到 RESUMED 之間的
// 所有事件分發給 Observer
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
// ...
}
/**
* 處理生命週期事件
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
/**
* 改變狀態
*/
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
// ...
sync();
// ...
}
/**
* 同步 Observer 狀態,並分發事件
*/
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;
// State中,狀態值是從 DESTROYED - INITIALIZED - CREATED - STARTED - RESUMED 增大
// 如果當前狀態值 < Observer 狀態值,需要通知 Observer 減小狀態值,直到等於當前狀態值
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// 如果當前狀態值 > Observer 狀態值,需要通知 Observer 增大狀態值,直到等於當前狀態值
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
/**
* 向前傳遞事件。
* 增加 Observer 的狀態值,直到狀態值等於當前狀態值
*/
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();
}
}
}
/**
* 向後傳遞事件。
* 減小 Observer 的狀態值,直到狀態值等於當前狀態值
*/
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();
}
}
}
}
根據上面的分析,我們知道 LifecycleRegistry 才是真正替 Lifecycle 去埋頭幹粗活的類!
接下來繼續來看看實現了 LifecycleOwner 介面的 SupportActivity 類是如何將事件分發給 LifecycleRegistry 的。
public class SupportActivity extends Activity implements LifecycleOwner, Component {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
注意到 SupportActivity 的 onCreate() 方法裡面有行 ReportFragment.injectIfNeededIn(this)
程式碼,再進入 ReportFragment 類分析。
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) {
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);
}
}
}
}
不難看出這是一個沒有 UI 的後臺 Fragment , 一般可以為 Activity 提供一些後臺行為。在 ReportFragment 的各個生命週期中都呼叫了 LifecycleRegistry.handleLifecycleEvent() 方法來分發生命週期事件。
為什麼不直接在 SupportActivity 的生命週期函式中給 Lifecycle 分發生命週期事件,而是要加一個 Fragment 呢?
在 ReportFragment 的 injectIfNeededIn() 方法中找到答案:
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();
}
}
有兩個原因:為了能讓 ProcessLifecycleOwner 正確地工作;②、並非所有的 Activity 都是繼承來自 support 包的 FragmentActivity 類的。因此封裝一個同樣具有生命週期的後臺 Fragment 來給 Lifecycle 分發生命週期事件。
另一方面,假如我們不繼承自 SupportActivity , 那 Lifecycle 是如何通過 ReportFragment 分發生命週期事件呢?
滑鼠停在 ReportFragment 類,同時按下 Ctrl + Shift + Alt + F7
在 Project and Libraries 的範圍下搜尋 ReportFragment 被引用的地方。我們發現還有 LifecycleDispatcher 和 ProcessLifecycleOwner 兩個類有使用到 ReportFragment .
LifecycleDispatcher
生命週期分發者。
class LifecycleDispatcher {
// ...
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
// 通過註冊 Application.registerActivityLifecycleCallbacks 來獲取 Activity 的生命週期回撥
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
private final FragmentCallback mFragmentCallback;
DispatcherActivityCallback() {
mFragmentCallback = new FragmentCallback();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
// 給每個 Activity 新增 ReportFragment
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
}
/**
* 通過遞迴形式給所有子 Fragment 設定 State
*/
private static void markState(FragmentManager manager, State state) {
Collection<Fragment> fragments = manager.getFragments();
if (fragments == null) {
return;
}
for (Fragment fragment : fragments) {
if (fragment == null) {
continue;
}
markStateIn(fragment, state);
if (fragment.isAdded()) {
// 遞迴
markState(fragment.getChildFragmentManager(), state);
}
}
}
private static void markStateIn(Object object, State state) {
if (object instanceof LifecycleRegistryOwner) {
LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
registry.markState(state);
}
}
/**
* 將某 Activity 及其所有子 Fragment 的 State 設定為某狀態
*/
private static void markState(FragmentActivity activity, State state) {
markStateIn(activity, state);
markState(activity.getSupportFragmentManager(), state);
}
// ...
}
從原始碼可知,LifecycleDispatcher 是通過註冊 Application.registerActivityLifecycleCallbacks 來監聽 Activity 的生命週期回撥的。
- 在 onActivityCreated 中新增 ReportFragment , 將 Activity 的生命週期交給 ReportFragment 去分發給 LifecycleRegistry ;
- 在 onActivityStopped() 以及 onActivitySaveInstanceState() 中,將 Activity 及其所有子 Fragment 的 State 置為 CREATED .
ProcessLifecycleOwner
為整個 App 程序提供生命週期的類。
public class ProcessLifecycleOwner implements LifecycleOwner {
static final long TIMEOUT_MS = 700; //mls
// ...
static void init(Context context) {
sInstance.attach(context);
}
private ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
}
從原始碼可知:
- ProcessLifecycleOwner 是用來監聽 Application 生命週期的,它只會分發一次 ON_CREATE 事件,並不會分發 ON_DESTROY 事件;
- ProcessLifecycleOwner 在 Activity 的 onResume 中呼叫 Handle.postDelayed() , 在 onPause 中呼叫了 mHandler.removeCallbacks(mDelayedPauseRunnable) , 是為了處理 Activity 重建時比如橫豎螢幕切換時,不會發送事件;
- ProcessLifecycleOwner 一般用來判斷應用是在前臺還是後臺,但由於使用了 Handle.postDelayed() , TIMEOUT_MS = 700,因此這個判斷不是即時的,有 700ms 的延遲;
- ProcessLifecycleOwner 與 LifecycleDispatcher 一樣,都是通過註冊 Application.registerActivityLifecycleCallbacks 來監聽 Activity 的生命週期回撥,來給每個 Activity 新增 ReportFragment 的。
最後,通過點選 init() 方法,我們發現 LifecycleDispatcher 和 ProcessLifecycleOwner 都是在 ProcessLifecycleOwnerInitializer 類下完成初始化的,而 ProcessLifecycleOwnerInitializer 是一個 ContentProvider .
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
// ...
}
Lifecycle 會自動在我們的 AndroidManifest.xml 中新增以下程式碼用於初始化 ProcessLifecycleOwner 與 LifecycleDispatcher , 這樣就不需要我們在 Application 中寫程式碼來初始化了。
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
// ...
<provider
android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="me.baron.achitecturelearning.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
</manifest>
Lifecycle 的最佳實踐
- 保持 Activity / Fragment 儘可能的精簡,它們不應該試圖去獲取它們所需的資料,要用 ViewModel 來獲取,並觀察 LiveData 物件將資料變化反映到檢視中;
- 嘗試編寫資料驅動(data-driven)的 UI , 即 UI 控制器的責任是在資料改變時更新檢視或者將使用者的操作通知給 ViewModel ;
- 將資料邏輯放到 ViewModel 類中,ViewModel 應該作為 UI 控制器和應用程式其它部分的連線服務。注意:不是由 ViewModel 負責獲取資料(例如:從網路獲取)。相反,ViewModel 呼叫相應的元件獲取資料,然後將資料獲取結果提供給 UI 控制器;
- 使用 Data Binding 來保持檢視和 UI 控制器之間的接口乾淨。這樣可以讓檢視更具宣告性,並且儘可能減少在 Activity 和 Fragment 中編寫更新程式碼。如果你喜歡在 Java 中執行該操作,請使用像 Butter Knife 這樣的庫來避免使用樣板程式碼並進行更好的抽象化;
- 如果 UI 很複雜,可以考慮建立一個 Presenter 類來處理 UI 的修改。雖然通常這樣做不是必要的,但可能會讓 UI 更容易測試;
- 不要在 ViewModel 中引用 View 或者 Activity 的 context . 因為如果 ViewModel 存活的比 Activity 時間長(在配置更改的情況下),Activity 將會被洩漏並且無法被正確的回收。
參考資料: