官网地址:https://developer.android.google.cn/topic/libraries/architecture/lifecycle
首先看一下官网的介绍:Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments.
即:支持生命周期的组件执行动作以响应另一个组件(如activities和fragments)生命周期状态的更改。
先通过一个例子看一哈:
dependencies {
// 低版本SDK使用compile
implementation 'android.arch.lifecycle:extensions:1.1.1'
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
}
自定义 LifecycleObserver
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun connectListener() {
Log.i("sss","Event.ON_RESUME")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun disconnectListener() {
Log.i("sss","Event.ON_PAUSE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun createListener() {
Log.i("sss","Event.ON_CREATE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun destroyListener() {
Log.i("sss","Event.ON_DESTROY")
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun anyListener() {
Log.i("sss","Event.ON_ANY")
}
}
在Activity中注册(在Android Support Library 26.1.0 及其之后已经activity 和 fragment 已经默认实现了LifecycleOwner。).
class MyActivity : AppCompatActivity() {
private var mLifecycleRegistry: LifecycleRegistry? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
val myLifeCycle = MyObserver()
// 26 之前的可以使用这种方式
// mLifecycleRegistry = LifecycleRegistry(this)
// mLifecycleRegistry!!.markState(Lifecycle.State.CREATED)
// mLifecycleRegistry!!.addObserver(myLifeCycle)
// myLifeCycle.disconnectListener()
// 26之后这样注册完毕.
this.getLifecycle().addObserver(myLifeCycle)
mybtn1.setOnClickListener {
finish()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:orientation="vertical">
<Button
android:id="@+id/mybtn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="关闭页面"
android:textSize="16dp"
android:textColor="@color/colorPrimary"
android:background="#ffffff" />
</LinearLayout>
根据运行结果分析看一下源码中的Lifecycle.Event的几种状态.
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
* {@link lifecycleowner}的oncreate事件的常量。
/
ON_CREATE,
/*
* Constant for onStart event of the {@link LifecycleOwner}.
* {@link lifecycleowner}的onstart事件的常量。
/
ON_START,
/*
* Constant for onResume event of the {@link LifecycleOwner}.
* {@link LifecycleOwner}的onResume事件的常量。
/
ON_RESUME,
/*
* Constant for onPause event of the {@link LifecycleOwner}.
* {@link lifecycleowner}的onpause事件的常量。
/
ON_PAUSE,
/*
* Constant for onStop event of the {@link LifecycleOwner}.
* {@link lifecycleowner}的onstop事件的常量。
/
ON_STOP,
/*
* Constant for onDestroy event of the {@link LifecycleOwner}.
* {@link LifecycleOwner}的onDestroy事件的常量。
/
ON_DESTROY,
/*
* An {@link Event Event} constant that can be used to match all events.
* 可用于匹配所有事件的{@link event event}常量。
*/
ON_ANY
原理分析
首先看一下SupportActivity
@RestrictTo({Scope.LIBRARY_GROUP})
public class SupportActivity extends Activity implements LifecycleOwner, Component {
private SimpleArrayMap<Class<? extends SupportActivity.ExtraData>, SupportActivity.ExtraData> mExtraDataMap = new SimpleArrayMap();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public SupportActivity() {
}
@RestrictTo({Scope.LIBRARY_GROUP})
public void putExtraData(SupportActivity.ExtraData extraData) {
this.mExtraDataMap.put(extraData.getClass(), extraData);
}
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
protected void onSaveInstanceState(Bundle outState) {
this.mLifecycleRegistry.markState(State.CREATED);
super.onSaveInstanceState(outState);
}
@RestrictTo({Scope.LIBRARY_GROUP})
public <T extends SupportActivity.ExtraData> T getExtraData(Class<T> extraDataClass) {
return (SupportActivity.ExtraData)this.mExtraDataMap.get(extraDataClass);
}
public Lifecycle getLifecycle() {
return this.mLifecycleRegistry;
}
@RestrictTo({Scope.LIBRARY_GROUP})
public boolean superDispatchKeyEvent(KeyEvent event) {
return super.dispatchKeyEvent(event);
}
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
View decor = this.getWindow().getDecorView();
return decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event) ? true : super.dispatchKeyShortcutEvent(event);
}
public boolean dispatchKeyEvent(KeyEvent event) {
View decor = this.getWindow().getDecorView();
return decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event) ? true : KeyEventDispatcher.dispatchKeyEvent(this, decor, this, event);
}
@RestrictTo({Scope.LIBRARY_GROUP})
public static class ExtraData {
public ExtraData() {
}
}
}
通过LifecycleRegistry,一个 Lifecycle 的实现类。通过markState方法在onSaveInstanceState把 Lifecycle 状态标记为Lifecycle.State.CREATED
然后通过 ReportFragment.injectIfNeededIn(this)注册其他事件,看一下源码:
/**
* Internal class that dispatches initialization events.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@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);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
通过dispatch()方法中把相关事件注册:
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);
}
}
}
通知观察者
首先看LifecycleRegistry中的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) {
// it is null we should be destroyed. Fallback quickly
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();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
把observer维护到ObserverWithState然后装到 map 中,原理类似于livedata
然后在handleLifecycleEvent方法遍历map 通知 observer
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
然后通过sync()的backwardPass()和forwardPass()处理相关事件:
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();
}
}
}
循环所有保存的观察者,然后调用ObserverWithState的dispatchEvent
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
总结:
整个分析过程中涉及到的类和接口如下:
SupportActivity :持有LifecycleRegistry并负责注入ReportFragment
LifecycleOwner :标示被观察者
ReportFragment : 传递生命周期事件讯息,为出发点
LifecycleRegistry : 持有观察者、被观察者等信息
Event : 标示观察者事件触发时机
ObserverWithState : 持有state和适配类的信息
Lifecycing : 适配观察者,生成适配类,获取合适的GenericLifecycleObserver
GeneratedAdapter: 标示适配类,以供调用
GenericLifecycleObserver :传递生命周期事件讯息,中转点
State : 标示被观察者生命周期阶段