使用起来相当简单,Activity是我们的被观察者
public class MainActivity1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 添加观察者
getLifecycle().addObserver(new ObserveClass());
}
}
观察者类:
public class ObserveClass implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateX(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStartX(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestory(LifecycleOwner owner) {
// activity生命周期回调
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner) {
// activity生命周期回调
}
}
一般越是使用起来很简单的东西,内部越是做了很多复杂的逻辑,我们接下来分析一下
lifecycle的目的是监听Activity的生命周期,要实现就是下面简单的一句话,当然前提是要有一个观察者类实现LifecycleObserver接口
getLifecycle().addObserver(LifecycleObserver observer);
我们分析一下源码,看看addobserver添加一个观察者时候发生了什么事情?
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
// 状态信息
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 实现了LifecycleObserver的观察者,此时和状态一起包装了起来
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 观察者以自己为键,和statefulObserver包装类一起存到了mObserverMap中,
// mObserverMap是FastSafeIterableMap里,这个类是一个自定义列表,用于保存观察者并可在遍历期间处理 // 删除和添加。
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--;
}
这里就是将观察者和初始状态一起包装一下放到了一个hashMap中,这里先记住一下。
既然是监听Activity的生命周期,那么Activity的onCreate,OnResume等方式运行的时候,Lifecycle肯定做了一些事情,Activity一启动,肯定执行了onCreate方法,那么我们先从入口Activity的超类ComponentActivity的onCreate方法中看一看。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
// ReportFragment注入进来
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
分析源码得知这里有一个ReportFragment被注入了进来,那么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();
}
}
这里我们发现injectIfNeededIn中会创建一个ReportFragment,是一个没有UI的空的fragment,原来onCreate方法中会添加一个空的没有UI界面的fragment到界面上来,那么添加ReportFragment有什么用呢,我们看一下ReportFragment
@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);
}
我们发现ReportFragment的一些主要生命周期方法上都进行了dispatch分发生命周期,到这里应该大概能明白Lifecycle是通过往界面上添加一个空的fragment来实现生命周期的监听。那么具体dispatch分发的原理是什么呢?
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
// 获得Lifecycle.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;
}
getStateAfter获取下一个状态是分析用户的行为习惯设计出以下代码,比如stop的下一个状态肯定是CREATED,pause暂停了的下一个状态肯定是STARTED,这里的所指的状态是Lifecycle中的枚举State,一共有五种DESTROYED/INITIALIZED/CREATED/STARTED/RESUMED
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
sync方法,此处同步我们的观察者和被观察这生命周期的状态,这里的状态是Lifecycle中的枚举State,这里借用官网的一张state状态的图片可以方便理解,当我们的观察者在被观察者的任意生命周期介入时,系统会通过一下逻辑使得观察者的状态和被观察者的状态同步,同步使用了while循环进行遍历,将之前错过的状态的事件都分发掉
private void sync() {
// ... 略
while (!isSynced()) {
// ... 略
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
// 向后
backwardPass(lifecycleOwner);
}
// ... 略
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
// 向前
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
// 向前
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
// 外层循环取出所有的观察者
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
// 内层循环针对观察者的state,upEvent方法得到事件后,进行分发,一直循环分发到state状 // 态和被观察者activity的状态同步
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
接下来顺着这条线看下去dispatchEvent > ReflectiveGenericLifecycleObserver的onStateChanged > ClassesInfoCache的invokeCallbacks > ClassesInfoCache的 invokeMethodsForEvent > ClassesInfoCache的 invokeCallback,到这里就停,不用继续看下去了,这里我们发现是利用反射执行观察者中被注解标志的生命周期方法
// 利用反射执行ReportFragment中的被注解标注的方法
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
以上大概分析出来了lifecyle实现监听activity的原理,其实就是搞了一个空的fragment,将空fragment的生命周期回调出去,然后用反射器加载这些回调方法,希望以上的总结能对一些人有一丝借鉴,总结不好或者错误的地方欢迎指出