在平常的開發中,咱們一般須要在 Activity / Fragment 的生命週期方法中進行一些繁重的操做,這樣使代碼看起來十分臃腫。Lifecycle 的引入主要是用來管理和響應 Activity / Fragment 的生命週期的變化,幫助咱們編寫出更易於組織且一般更加輕量級的代碼,讓代碼變得更易於維護。java
Lifecycle 是一個類,它持有 Activity / Fragment 生命週期狀態的信息,並容許其它對象觀察此狀態。android
添加相關依賴git
場景:讓 MVP 中的 Presenter 觀察 Activity 的 onCreate 和 onDestroy 狀態。github
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")
}
}
複製代碼
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 會打印:segmentfault
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 內部還有表明了各個生命週期所處狀態的枚舉類 Stateapp
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 並須要在各個生命週期作一些特殊邏輯時,代碼多是:ide
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 接收。
實現原理
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 完成的。
生命週期登記處。做爲 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 類分析。
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 .
生命週期分發者。
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 的生命週期回調的。
爲整個 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();
}
});
}
}
複製代碼
從源碼可知:
最後,經過點擊 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>
複製代碼
參考資料: