Lifecycle是什么
学习Lifecycle首先要明白,Lifecycle 是什么?
Lifecycle用于管理Activity和Fragment的生命周期,能够帮助开发者轻松的应对Activity/Fragment的生命周期变化问题,帮助开发者生成更易于维护的轻量级代码。并且Lifecycle是LiveData和ViewModel的基础。
为什么要用Lifecycle
首先来说,在开发中,很多时候不可避免的需要处理与Activity或者Fragment的生命周期相关的代码。那么在Lifecycle之前,大部分情况下的处理方式是这样的:
internal class MyLocationListener(
private val context: Context,
private val callback: (Location) -> Unit
) {
fun start() {
// connect to system location service
}
fun stop() {
// disconnect from system location service
}
}
class MyActivity : AppCompatActivity() {
private lateinit var myLocationListener: MyLocationListener
override fun onCreate(...) {
myLocationListener = MyLocationListener(this) { location ->
// update UI
}
}
public override fun onStart() {
super.onStart()
myLocationListener.start()
// manage other components that need to respond
// to the activity lifecycle
}
public override fun onStop() {
super.onStop()
myLocationListener.stop()
// manage other components that need to respond
// to the activity lifecycle
}
}
虽然这个示例看起来还不错,但是在实际的开发中,可能会需要进行过多的调用来管理UI和其他的组件用来响应当前的生命周期状态,这就需要在生命周期的方法中放置大量的代码,导致难以维护。而且还有一个问题是,不能保证组件在Activity或Fragment停止之前就已启动。如果我们需要执行长时间运行的操作(例如onStart()中的某些配置检查),这可能会导致onStop()方法在onStart()之前完成,从而使组件的生存期超过了所需的生存期。
因此,为了更好的解决这些问题,出现了Lifecycle
怎么用Lifecycle
- 首先看一下官方给的代码示例:
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun connectListener() {
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun disconnectListener() {
...
}
}
myLifecycleOwner.getLifecycle().addObserver(MyObserver())
从这段代码来看,我们需要先定义一个类实现 LifecycleObserver 接口,然后一个实现了LifecycleOwner接口的myLifecycleOwner对象调用getLifecycle().addObserver(MyObserver())。只看这点代码好像看不出来个啥。
- 在Activity中使用
class MainActivity : AppCompatActivity() {
val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreate")
lifecycle.addObserver(MyObserver())
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
}
inner class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.d(TAG, "Lifecycle call onCreate")
Log.d(TAG, lifecycle.currentState.name)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.d(TAG, "Lifecycle call onStart")
Log.d(TAG, lifecycle.currentState.name)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.d(TAG, "Lifecycle call onResume")
Log.d(TAG, lifecycle.currentState.name)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.d(TAG, "Lifecycle call onPause")
Log.d(TAG, lifecycle.currentState.name)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.d(TAG, "Lifecycle call onStop")
Log.d(TAG, lifecycle.currentState.name)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.d(TAG, "Lifecycle call onDestroy")
Log.d(TAG, lifecycle.currentState.name)
}
}
}
因为在Android Support Library 26.1.0 及其之后的版本,Activity和Fragment已经默认实现了LifecycleOwner接口,所以可以直接使用getLifecycle方法获取Lifecycle对象,这样MyObserver就可以观察MainActivity的生命周期变化了,LifecycleOwner可以理解为被观察者,MainActivity默认实现了LifecycleOwner接口,也就是说MainActivity是被观察者。
运行日志如下:
D/MainActivity: onCreate
D/MainActivity: Lifecycle call onCreate
D/MainActivity: CREATED
D/MainActivity: onStart
D/MainActivity: Lifecycle call onStart
D/MainActivity: STARTED
D/MainActivity: onResume
D/MainActivity: Lifecycle call onResume
D/MainActivity: RESUMED
D/MainActivity: Lifecycle call onPause
D/MainActivity: STARTED
D/MainActivity: onPause
D/MainActivity: Lifecycle call onStop
D/MainActivity: CREATED
D/MainActivity: onStop
D/MainActivity: Lifecycle call onDestroy
D/MainActivity: DESTROYED
D/MainActivity: onDestroy
- 如果是在mvp中希望present可以监控到Activity或者Fragment的生命周期状态的话,可以让presenter实现LifecycleObserver接口,然后在Activity或者Fragment中对其进行注册。
Lifecycle的实现原理
1. Lifecycle中的Event和State
Lifecycle中定义了Event:表示生命周期事件, State:表示当前状态。
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
Event和State的关系如下图:
这个图也可以和上边的Log日志进行一下比对。
2. Lifecycle如何感知Activity或者Fragment的生命周期的
首先上边的例子中的MainActivity继承了AppCompatActivity,而AppCompatActivity继承了FragmentActivity。在Android 8.0时,FragmentActivity继承自SupportActivity,而在Android 9.0,FragmentActivity继承自ComponentActivity 。我这边用的是ComponentActivity。上代码:
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
@SuppressWarnings("deprecation")
private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
new SimpleArrayMap<>();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@SuppressWarnings("deprecation")
@RestrictTo(LIBRARY_GROUP_PREFIX)
@Deprecated
public void putExtraData(ExtraData extraData) {
mExtraDataMap.put(extraData.getClass(), extraData);
}
@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
@RestrictTo(LIBRARY_GROUP_PREFIX)
@SuppressWarnings({"unchecked", "deprecation"})
@Deprecated
public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
return (T) mExtraDataMap.get(extraDataClass);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@RestrictTo(LIBRARY_GROUP_PREFIX)
@Override
public boolean superDispatchKeyEvent(KeyEvent event) {
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
View decor = getWindow().getDecorView();
if (decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event)) {
return true;
}
return super.dispatchKeyShortcutEvent(event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
View decor = getWindow().getDecorView();
if (decor != null && KeyEventDispatcher.dispatchBeforeHierarchy(decor, event)) {
return true;
}
return KeyEventDispatcher.dispatchKeyEvent(this, decor, this, event);
}
@SuppressWarnings("DeprecatedIsStillUsed")
@RestrictTo(LIBRARY_GROUP_PREFIX)
@Deprecated
public static class ExtraData {
}
}
从这个类中,我们没有看到我们所想要看到的在每个生命周期中对State的改变。但是在onCreate()中,我们看到了ReportFragment.injectIfNeededIn(this);我们再看一下ReportFragment。代码如下:
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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();
}
}
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);
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的方法,对Lifecycler.Event进行了分发。
在dispatch方法中,调用了LifecycleRegistry中的handleLifecycleEvent方法。方法代码:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
getStateAfter(Event event) 获取事件后的状态。可以配合着上边的Event和State的关系图来看。代码:
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);
}
moveToState(State state)中主要是sync()方法,代码如下:
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
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;
}
在这个方法中,对当前的状态mState和mObserverMap中的eldest和newest的状态进行了对比,来判断是往前走还是往后退,比如由STARTED到RESUMED是状态向前(forward),反过来就是状态向后(backward)。向前还是向后的代码大同小异,这里以backward为例。
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
可以看到, backwardPass() 方法调用 downEvent 获取往回退的目标 Event。
举个例子:在 RESUMED 状态,我们按了 home,这个时候就是 RESUMED 的状态变到 STARTED 的状态,对应的 Event 是 ON_PAUSE,这个就是 backwardPass() 的逻辑了。
然后我们看到了observer.dispatchEvent(lifecycleOwner, event)。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
其中的Lifecycling.lifecycleEventObserver(observer);代码:
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) 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);
}
通过走断点,返回的是ReflectiveGenericLifecycleObserver,我们直接查看ReflectiveGenericLifecycleObserver中的onStateChanged()方法:
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
在看CallBackInfo相关的代码
CallbackInfo getInfo(Class klass) {
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);
return existing;
}
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
// 不断的遍历各个方法,获取方法上的名为OnLifecycleEvent的注解,这个注解正是实现LifecycleObserver接口时用到的。
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
//获取该注解的值,也就是在@OnLifecycleEvent中定义的事件。
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
//新建了一个MethodReference,其内部包括了使用了该注解的方法。
MethodReference methodReference = new MethodReference(callType, method);
//用于将MethodReference和对应的Event存在类型为Map<MethodReference, Lifecycle.Event> 的handlerToEvent中。
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
//新建CallbackInfo,并将handlerToEvent传进去。
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
@SuppressWarnings("WeakerAccess")
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
//将handlerToEvent进行数据类型转换,转化为一个HashMap,key的值为事件,value的值为MethodReference。
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
//调用MethodReference的invokeCallback方法。
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
static class MethodReference {
final int mCallType;
final Method mMethod;
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
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);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MethodReference that = (MethodReference) o;
return mCallType == that.mCallType && mMethod.getName().equals(that.mMethod.getName());
}
@Override
public int hashCode() {
return 31 * mCallType + mMethod.getName().hashCode();
}
}
MethodReference类中有两个变量,一个是callType,它代表调用方法的类型,另一个是Method,它代表方法,不管是哪种callType都会通过invoke对方法进行反射。
简单来说,实现LifecycleObserver接口的类中,注解修饰的方法和事件会被保存起来,通过反射对事件的对应方法进行调用。
3. 参考与推荐
http://liuwangshu.cn/application/jetpack/3-lifecycle-theory.html
https://juejin.im/post/5cd81634e51d453af7192b87
https://developer.android.google.cn/topic/libraries/architecture/lifecycle