​官方文档连接​

一、Lifecycle 简介

Google 最新推荐的 Lifecycle 架构是什么呢,简单来说,就是可以让你自己的类拥有像 activity 或 fragment 一样生命周期的功能。
为什么要这样呢?直接利用 activity 或 fragment 不行吗?当然可以,但Lifecycle肯定是解决了某些痛点的。
比如:我们现在要实现定位回调的功能,通常我们这样做:

class MyLocationListener {
public MyLocationListener(Context context, Callback callback) {
// ...
}

void start() {
// connect to system location service
}

void stop() {
// disconnect from system location service
}
}

class MyActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;

@Override
public void onCreate(...) {
myLocationListener = new MyLocationListener(this, (location) -> {
// update UI
});
}

@Override
public void onStart() {
super.onStart();
myLocationListener.start();
// manage other components that need to respond
// to the activity lifecycle
}

@Override
public void onStop() {
super.onStop();
myLocationListener.stop();
// manage other components that need to respond
// to the activity lifecycle
}
}

看起来似乎是很好,但在实际开发过程中还是要考虑很多东西的。随着业务的复杂 生命周期方法会变的臃肿难以维护。而且某些耗时的异步操作,也很难保证它会规规矩矩的按生命周期顺序执行。
所以,今天的主角就出现了。继承Lifecycle 的组件将生命周期脱离出 activity 而转到自己身上完美的解决了以上问题。

二、Lifecycle 使用

1、添加观察者

这里有两种方式:java7的方式和 java8,java7为通过注解的方式,而 java8不需要注解。官方推荐是 java8,理由是随着 android java8的普及要逐渐废弃注解的方式。
java7:

public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener() {
...
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener() {
...
}
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());

直接实现LifecycleObserver,然后通过注解即可生命周期实现回调。
java8:

class TestObserver implements DefaultLifecycleObserver {
@Override
public void onCreate(LifecycleOwner owner) {
// your code
}
}

实现的是DefaultLifecycleObserver(LifecycleObserver的子类),然后重写其生命周期方法即可。
最后同过LifecycleOwner,添加观察。什么是LifecycleOwner往下看

2、LifecycleOwner

LifecycleOwner是只有一个方法getLifecycle()​的接口,是让拥有生命周期的东西实现比如(activity)用来获取Lifecycle。(大白话)
在Android Support Library 26.1.0 及其之后已经activity 和 fragment 已经默认实现了LifecycleOwner。
所以在 activity 里我们可以直接:

getLifecycle().addObserver(new MyObserver());

ok 这样我们的MyObserver就会感知 activity 的生命周期了。

三、原理分析

1、Lifecycle 如何感知 activity 或 fragment 生命周期

既然activity 和 fragment 已经实现了 Lifecycle 架构。就先来看看如何感知的。
首先找到 activity 实现LifecycleOwner的地方SupportActivity:

public class SupportActivity extends Activity implements LifecycleOwner {
/**
* Storage for {@link ExtraData} instances.
*
* <p>Note that these objects are not retained across configuration changes</p>
*/
private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
new SimpleArrayMap<>();

private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

/**
* Store an instance of {@link ExtraData} for later retrieval by class name
* via {@link #getExtraData}.
*
* <p>Note that these objects are not retained across configuration changes</p>
*
* @see #getExtraData
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public void putExtraData(ExtraData extraData) {
mExtraDataMap.put(extraData.getClass(), extraData);
}

@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}

@CallSuper
@Override
protected void onSaveInstanceState(Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}

/**
* Retrieves a previously set {@link ExtraData} by class name.
*
* @see #putExtraData
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
return (T) mExtraDataMap.get(extraDataClass);
}

@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}

/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public static class ExtraData {
}
}

很简单,出现了一个LifecycleRegistry,是 Lifecycle 的一个实现类。通过markState方法在onSaveInstanceState把 Lifecycle 状态标记为Lifecycle.State.CREATED。
然后,就没有然后了,我原想着 会在 Activity 生命周期方法里改变Lifecycle的各种状态,然后一路寻找到笑容逐渐缺失,也没找到。卡了好大一阵后 我忽然发现 onCreate 方法里有个ReportFragment,点进去看了下才发现了新世界。

public class ReportFragment extends Fragment {
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();
}
}
……
@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);
}
}
}
}

原来 Google 是利用 fragment 的特性,绑定了一个 fragment 然后在其生命周期方法中调用了
LifecycleRegistry的handleLifecycleEvent,此方法便是通知观察者的地方。

另外需注意 Lifecycle.State.CREATED状态,在 FragmentActivity 中 也有递归的调用:

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
……
}
private static void markState(FragmentManager manager, Lifecycle.State state) {
Collection<Fragment> fragments = manager.getFragments();
for (Fragment fragment : fragments) {
if (fragment == null) {
continue;
}
fragment.mLifecycleRegistry.markState(state);
markState(fragment.getChildFragmentManager(), state);
}
}

Lifecycle 会在 自身构造方法中把自己标记为INITIALIZED

public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}

2、如何通知观察者

先看addObserver

private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();

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--;
}

感觉跟 livedata 那一套差不多,把observer维护到ObserverWithState然后装到 map 里。

然后通过handleLifecycleEvent方法最终遍历map 通知 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;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}

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;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}

调用了forwardPass或backwardPass随便看一个:

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;
}
}

还有比较重要的一点,ObserverWithState并不是简单的保存 observer 而是通过Lifecycling.getCallback(observer):

static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}

if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}

final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
return new ReflectiveGenericLifecycleObserver(object);
}

从而做到了,区分不同 observer 类型(比如前面提到的 java7与java8不同)。

四、总结

SupportActivity 实现了LifecycleOwner并通过 ReportFragment生命周期实现Lifecycle 生命周期的感知。

还是有点费解的地方,后来发现还有一种通过 ContentProvider (具体是这个ProcessLifecycleOwnerInitializer)然后用一个LifecycleDispatcher也同样实现了一套ReportFragment那些逻辑。初步猜测是为了不继承 SupportActivity 的 Activity 使用?还不太确定。