- 接口LifecycleOwner:生命周期持有者,代码如下:
其中google提供了接口LifecycleRegistryOwner继承了LifecycleOwner
具有生命周期的Activity、Fragment应该实现LifecycleRegistry并重写getLifecycle()方法。
抽象类Lifecycle主要具有添加观察者addObserver()、移除观察者removeObserver()功能
抽象类LifecycleRegister继承Lifecycle,重写了addObserver()、removeObserver(),除此之外实现将Lifecycle.Event和State之间的转换,并且状态发生变化时,通知观察者。
一般使用Activity、Fragment继承LifecycleRegistryOwner重写getLifecyle(),方法示例如下:
需要针对生命周期做出变化的类实现LifecycleObserver也就是观察者,并通过LifecycleRegistry的addObserver()方法将观察者添加到LifecycleRegistry中,其中红框部分稍后分析,这里仅以Activity为例来分析Lifecycle的运作过程。启动Activity调用栈如下所示:
可以看到Activity启动时,在ActivityThread类中installProvider方法中调用了ContentProvider的attchInfo方法,进而调用了LifecycleRuntimeTrojanProvider类的onCreate()方法,该方法如下所示
跟进LifecycleDispatcher
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}复制代码
init方法只是将DispatherActivityCallback添加到Application存储的map中去,继续查看DispatcherActivityCallBack类
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);
}
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);
}
}
}复制代码
经过断点试验发现当ThreadActivity执行performCreate方法时会调用DispatcherActivityCallback的onActivityCreated方法,该方法中会调用ReportFragment.injectIfNeedIn(activity),其中该activity即为实现了LifecycleRegistryOwner的对象,继续更近ReportFragment代码如下:
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();
}
}复制代码
从代码可以看出相当于在activity中添加了一个没有任何内容的Fragment,该Fragment用来监听activity生命周期的变化并通知观察者,利用Fragment应该是是因为Fragment的onCreate()、onStart()、onResume()方法均在其所在的Activity的相应的onCreate()、onStart()、onResume()方法之后执行,但是Fragment的onPause()、onStop()、onDestroy()均在所在Activit相应的onPause()、onStop()、onDestroy()之前执行,这一点儿很重要!
当执行完毕Activity中的onCreate方法后,会执行ReportFragment方法中的onAcitivityCreate方法
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}复制代码
其中dispatch方法如下所示
private void dispatch(Lifecycle.Event event) {
if (getActivity() instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
}
}复制代码
这里个getActivity就是实现了第三张图中实现LifecycleRegistryOwner的Activity,此处也应该注意被监听生命周期变化的Activity应该继承的是LifecycleRegisterOwner类,而不应该是LifecycleOwner。继续跟进handleLifecycleEvent方法
public void handleLifecycleEvent(Lifecycle.Event event) {
if (mLastEvent == event) {
return;
}
mLastEvent = event;
mState = getStateAfter(event);
for (Map.Entry entry : mObserverSet) {
entry.getValue().sync();
}
}复制代码
只要mLastEvent!=event就会执行for循环,其中mObserverSet中的元素是在addObserver的时候添加的,如下所示
@Override
public void addObserver(LifecycleObserver observer) {
ObserverWithState observerWithState = new ObserverWithState(observer);
mObserverSet.putIfAbsent(observer, observerWithState);
observerWithState.sync();
}复制代码
其中ObserverWithState对象对observer进行了封装,
ObserverWithState(LifecycleObserver observer) {
mCallback = Lifecycling.getCallback(observer);
}复制代码
ObserverWithState构造函数中调用了Lifecycleing.getCallback(observer)查看该方法(这里不再贴代码)只是根据observer所在包名和类名通过反射构建出了一个“className”+"_LifecycleAdapter的类并调用该类的构造函数将observer作为参数传递给该类的实例,例如自己的demo中名为CustomLifecycleObser_LifeAdapter,该类在app/build/generated/source/apt/debug下,查看该类如下
public class CustomLifecycleObserver_LifecycleAdapter implements GenericLifecycleObserver {
final CustomLifecycleObserver mReceiver;
CustomLifecycleObserver_LifecycleAdapter(CustomLifecycleObserver receiver) {
this.mReceiver = receiver;
}
@Override
public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_CREATE) {
mReceiver.onCreate(owner);
}
if (event == Lifecycle.Event.ON_START) {
mReceiver.onStart(owner);
}
if (event == Lifecycle.Event.ON_RESUME) {
mReceiver.onResume(owner);
}
if (event == Lifecycle.Event.ON_STOP) {
mReceiver.onStop(owner);
}
if (event == Lifecycle.Event.ON_PAUSE) {
mReceiver.onPause(owner);
}
if (event == Lifecycle.Event.ON_DESTROY) {
mReceiver.onDestroy(owner);
}
mReceiver.onAny(owner,event);
}
public Object getReceiver() {
return mReceiver;
}
}复制代码
注解处理器apt生成该类时会生成一个onStateChanged方法,并根据event调用observer中相应的方法,这些方法是observer中被onLifecycleEvent注解的方法,那onStateChanged方法在哪里被调用呢,例如上面的Activity的onCreate方法执行后会调用onActivityCreated方法,然后调用handleLifecycleEvent方法,该方法遍历mObserverSet后调用sync方法,该方法如下所示
void sync() {
if (mState == DESTROYED && mObserverCurrentState == INITIALIZED) {
mObserverCurrentState = DESTROYED;
}
while (mObserverCurrentState != mState) {
Event event = mObserverCurrentState.isAtLeast(mState)
? downEvent(mObserverCurrentState) : upEvent(mObserverCurrentState);
mObserverCurrentState = getStateAfter(event);
mCallback.onStateChanged(mLifecycleOwner, event);
}
}复制代码
当mState不等于mObserverCurrentState的时候就会进行两种状态的比较,其中返回的Event其实就是mObserverCurrentState过渡到mState时所需的Event详见头图,例如mObserverCurrentState是INITIALIZED,而mState是CREATED的时候,这个时候然需要经过ON_CREATE事件后,mObserverCurrentState才可以过度到mState的状态,进而更新mObserverState对应的状态为mState,然后调用“className”+"_LifecycleAdapter的onStateChange方法,进而调用到观察者中相应的方法。
再说红色方框中为啥要调用markState方法,因为Activity的onCreate方法要比Fragment的早,如果不手动调用的话mObserverCurrentState和mState都是INITIALIZED,进而不会执行
mCallBack.onStateChanged方法。