PS:原文首发于微信公众号:躬行之(jzman-blog)
Lifecycle-Aware 组件是 Android Jetpack 的一部分,该组件可以感知 Activity 和 Fragment 的生命周期状态的改变,有利于生成更易组织、更轻量化、更易于维护的代码,常用的开发方式就是在组件的对应的生命周期方法中处理相关业务逻辑,这种方式会导致不良代码的产生以及 bug 的增加,如果使用生命周期组件则可将依赖组件的代码移除生命周期并移入组件本身。
Lifecycle 是一个持有组件生命周期状态信息的抽象类,其直接子类是 LifecycleRegistry,Activity 和 Fragment 都间接实现了 LifecycleOwner 接口,且提供了对应的 getLifecycle 方法获取 Lifecycle 对象,获取到的也就是 LifecycleRegistry 对象,下面是 Lifecycle 的生命周期对应状态图:
图示中主要有两点:Event(事件)和 Status(状态)。
如果开发环境是 Java1.7 ,可以使用注解的方式来监听生命周期变化,参考如下:
/**
* Powered by jzman.
* Created on 2018/12/8 0008.
*/
public class LifeCycleListener implements LifecycleObserver {
private static final String TAG = LifeCycleListener.class.getSimpleName();
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private void onCreate(LifecycleOwner owner) {
Log.i(TAG,"--onCreate-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onStart(LifecycleOwner owner) {
Log.i(TAG,"--onStart-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private void onResume(LifecycleOwner owner) {
Log.i(TAG,"--onResume-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private void onPause(LifecycleOwner owner) {
Log.i(TAG,"--onPause-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onStop(LifecycleOwner owner) {
Log.i(TAG,"--onStop-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void onDestroy(LifecycleOwner owner) {
Log.i(TAG,"--onDestroy-->");
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
private void onAny(LifecycleOwner owner, Lifecycle.Event event) {
//onAny方法可以添加第二个参数,用来获取当前生命周期
//任何生命周期状态发生变化都会触发
Log.i(TAG,"--onAny-->"+event.name());
}
}
如果开发环境是 Java1.8 ,推荐使用以实现 DefaultLifecycleObserver 接口的方式来监听生命周期的变化,首先在对应 module 的 build.gradle 文件文件中引入:
implementation "android.arch.lifecycle:common-java8:1.1.1"
然后,创建生命周期监听器如下:
/**
* Powered by jzman.
* Created on 2018/12/10 0010.
*/
public class LifeCycleListener1 implements DefaultLifecycleObserver {
private static final String TAG = LifeCycleListener.class.getSimpleName();
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onCreate-->");
}
@Override
public void onStart(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onStart-->");
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onResume-->");
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onPause-->");
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onStop-->");
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
Log.i(TAG,"--onDestroy-->");
}
}
最后,在对应的 Activity 或 Fragment 中注册该监听器,参考如下:
LifeCycleListener mLifeCycleListener = new LifeCycleListener();
getLifecycle().addObserver(mLifeCycleListener);
以 LifeCycleListener 为例 Lifecycle 监听 Activity 生命周期运行日志如下:
//打开Activity
--onCreate-->
--onAny-->ON_CREATE
--onStart-->
--onAny-->ON_START
--onResume-->
--onAny-->ON_RESUME
//退出Activity
--onPause-->
--onAny-->ON_PAUSE
--onStop-->
--onAny-->ON_STOP
--onDestroy-->
--onAny-->ON_DESTROY
LifecycleOwner 是一个接口,表示实现该接口的类具有生命周期,如所有继承自 AppCompatActivity 的 Activity 都间接实现了 LifecycleOwner 接口,源码中是 ComponentActivity 实现了该接口, 实际开发中可实现 LifecycleOwner 接口将原先 Activity 或 Fragment 生命周期中执行的业务移到组件本身。
从上文中可知使用 getLifecycle() 获取到是 Lifecycle 的具体实现类 LifecycleRegistry 对象,然后使用 addObserver 添加 LifecycleObserver 对象,也就是添加要通知的观察者,之后才能够在 Activity 或 Fragment 生命周期发生变化时观察者才会被通知,那么 Activity 的生命周期是如何被感知呢。
在 ComponentActivity 中添加了一个无界面的 Fragment 用来感知 Activity 的生命周期,源码如下:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
//在Activity中添加一个Fragment
ReportFragment.injectIfNeededIn(this);
}
injectIfNeededIn 方法会创建一个名称为 ReportFragment 的 Fragment,当每创建一个 Activity 的时候,该 Fragment 就会被添加到对应的 Activity 中,ReportFragment 源码如下:
public class ReportFragment extends Fragment {
// 创建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();
}
}
//...
// Activity 初始化监听器,监听Activity的生命周期状态
private ActivityInitializationListener mProcessListener;
// Activity生命周期状态分发
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) {
// 查案源码LifecycleRegistryOwner已被废弃,留着应该是为了兼容
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
// 获取Activity中的Lifecycle
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
// 分发Activity生命周期状态
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
// Activity初始化监听器
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
可见在 ReportFragment 对应的生命周期方法里面进行对应生命周期状态的分发,分发过程对应 dispatch 方法,里面调用了 handleLifecycleEvent 方法,该方法会在后文中介绍,其中对 Activity 对应的生命周期监听是在 ActivityInitializationListener 中完成的,查看该接口的实现类是换一个匿名内部类,位于 ProcessLifecycleOwner 中,源码如下:
public class ProcessLifecycleOwner implements LifecycleOwner {
// ...
private Handler mHandler;
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
private Runnable mDelayedPauseRunnable = new Runnable() {
@Override
public void run() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
// ActivityInitializationListener匿名实现类
private ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
// what?
// 为什么没有处理,不影响阅读源码
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
// 初始化,在哪初始化的?——>见后文
static void init(Context context) {
sInstance.attach(context);
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
// 无论ON_START还是ON_RESUME等,关键还是handleLifecycleEvent方法
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();
}
private void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
private void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
// 在没有Lifecycle组件之前,使用ActivityLifecycleCallbacks监听所有Activity的生命周期
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();
}
});
}
}
在没有Lifecycle组件之前,使用 ActivityLifecycleCallbacks 在 Application 注册来进行所有 Activity 生命周期的监听,这里同样使用了 ActivityLifecycleCallbacks,但是监听的对象变成了单个的 Activity,是不是感觉使用起来更灵活。
**备注:**上面有一个问题,ProcessLifecycleOwner是如何初始化的?答案在后面的一小节。
通过上面分析,最终的生命周期状态分发在 LifecycleRegistry 的 handleLifecycleEvent 方法中,其调用了 sync 方法,源码如下:
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 方法,源码如下:
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();
}
}
}
继续查看 dispatchEvent 方法
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
// 根据observer生成对应类型的GenericLifecycleObserver
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;
}
}
按照惯例,查看 GenericLifecycleObserver 的实现类,就可以知道在 onStateChanged 方法中分发的生命周期状态的流向,具体使用了哪个 GenericLifecycleObserver 的实现类取决于 getCallback 方法传入的 observer,getCallback 方法源码如下:
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
// 直接继承DefaultLifecycleObserver的方式
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
// 推测:如果在管理生命周期时,自定义的Observer继承自GenericLifecycleObserver
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
// 使用了注解处理器(Annotation Processor)
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);
}
如果是直接继承 DefaultLifecycleObserver 的方式,则会生成 FullLifecycleObserverAdapter ,在其实现的 onStatChanged 回调方法中会将最终的生命周期状态分发出去,也就回到了最初自己创建的 LifecycleListener1 中,这样就在 LifecycleListener1 中监听到了 Activity 的生命周期状态,看一下 FullLifecycleObserverAdapter 源码如下:
class FullLifecycleObserverAdapter implements GenericLifecycleObserver {
private final FullLifecycleObserver mObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
mObserver = observer;
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
//根据具体的Event回调到对应的生命周期方法中
switch (event) {
case ON_CREATE:
mObserver.onCreate(source);
break;
case ON_START:
mObserver.onStart(source);
break;
case ON_RESUME:
mObserver.onResume(source);
break;
case ON_PAUSE:
mObserver.onPause(source);
break;
case ON_STOP:
mObserver.onStop(source);
break;
case ON_DESTROY:
mObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
}
}
我们知道 Activity 中生命周期状态的监听使用到了 ActivityLifecycleCallbacks,而 ActivityLifecycleCallbacks 的注册是在 Application 中注册的,那么它是如何注册的,其注册是在 ProcessLifecycleOwner 的初始化中完成的,找到ProcessLifecycleOwner 的 init 的方法调用处是在 ProcessLifecycleOwnerInitializer 的 onCreate 方法中调用的,源码如下:
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
// 初始化ProcessLifecycleOwner
ProcessLifecycleOwner.init(getContext());
return true;
}
// ...
}
显然 ProcessLifecycleOwnerInitializer 是一个 ContentProvider,其 onCreate 方法中除了初始化 ProcessLifecycleOwner 之外,还先初始化了 LifecycleDispatcher,查看 LifecycleDispatcher 源码如下:
class LifecycleDispatcher {
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
// LifecycleDispatcher初始化
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
// 注册ActivityLifecycleCallbacks
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//在Activity中添加一个无界面的Fragment
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
}
private LifecycleDispatcher() {
}
}
结合之前的分析,这里注册的 ActivityLifecycleCallbacks 和 上文中注册的 ActivityLifecycleCallbacks 作用是完全不一样的,这里的是为了在 Activity 中添加一个无界面的 Fragment,而上文中的则是为了分发 Activity 的生命周期状态,可见为了保证在 Activity 中添加无界面的 Fragment,也就是 ReportFragment,前后添加两次,但是 injectIfNeededIn 方法只有在 ReportFragment 未添加的时候才会第二次添加。
前面知道 ProcessLifecycleOwnerInitializer 是一个 ContentProvider,当 ContentProvider 创建的时候也会随着对应进程的创建而启动,可以从 ActivityThread 的 main 方法开始查看 ContentProvider 的启动流程,顺便安利一个查看 Android 源代码的工具 AndroidXRef ,百度、Google 即可。