大家好,我是Lifecycle,我是一个生命周期感知型组件,可执行操作来响应另一个组件(如 activity 和 fragment)的生命周期状态的变化。有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。
一、使用Lifecycle的优势
想必通过上面的介绍,你应该认识我啦~,但是现在也许你有个疑问,就是:我使用你能有什么优势呢?
如果在不使用我的前提下,想在Activity/Fragment 中感知生命周期变化,一种常见的模式是在 activity 和 fragment 的生命周期方法中实现依赖组件的操作。但是,这种模式会导致代码条理性很差而且会扩散错误。列如这样:
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
}
}
虽然此示例看起来没问题,但在真实的应用中,为了响应生命周期的当前状态,将会进行过多的调用来管理界面和其他组件。管理多个组件会在生命周期方法(如 onStart() 和 onStop())中包含大量代码,这使得它们难以维护。
此外,无法保证组件会在 activity 或 fragment 停止之前启动。在我们需要执行长时间运行的操作(如 onStart() 中的某种配置检查)时尤其如此。这可能会导致出现一种竞态条件,在这种条件下,onStop() 方法会在 onStart() 之前结束,这使得组件留存的时间比所需的时间要长。
但是如果使用我来监听Activity / Fragment生命周期的变化,将是一件非常简单可靠的事。
二、Lifecycle的使用
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
class LifecycleObserver implements DefaultLifecycleObserver {
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onCreate");
}
@Override
public void onStart(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onStart");
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onResume");
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onPause");
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onStop");
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
Log.d(TAG, "LifecycleObserver ->onDestroy");
}
}
private LifecycleObserver lifecycleObserver = new LifecycleObserver();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(lifecycleObserver);
}
}
三、Lifecycle的原理
了解了如何使用,是否好奇我是如何做到感知Activity / Fragment生命周期变化的呢?下面带大家来更深一步的了解我,看了我如果使用,可以发现,示例中是创建了一个LifecycleObserver并继承了DefaultLifecycleObserver,然后通过getLifecycle().addObserver(lifecycleObserver)注册,这样就可以感知生命周期变化了~
下面让我们从这个问题开始切入:
1.这个getLifecycle()方法返回的是什么? 将自定义的Observer注册后,onCreate() / onStart() / onResume() / onPause() / onStop() / onDestroy() 是如何被回调的呢?
/**
* androidx.activity.ComponentActivity.java部分代码
*/
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
//由此得知该方法返回的是一个LifecycleRegistry对象
return mLifecycleRegistry;
}
让我们来看一下LifecycleRegistry.java中的addObserver()方法干了什么?
/**
* LifecycleRegistry.java部分代码
*/
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
Lifecycle.State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
LifecycleRegistry.ObserverWithState statefulObserver = new LifecycleRegistry.ObserverWithState(observer, initialState);
LifecycleRegistry.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;
Lifecycle.State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
final Lifecycle.Event event = Lifecycle.Event.upFrom(statefulObserver.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
//这里是重点,让我们看一下dispatchEvent()方法干了啥~
statefulObserver.dispatchEvent(lifecycleOwner, event);
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
/**
* 这个class是LifecycleRegistry中的一个内部类
*/
static class ObserverWithState {
Lifecycle.State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, Lifecycle.State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Lifecycle.Event event) {
Lifecycle.State newState = event.getTargetState();
mState = min(mState, newState);
//看到了这个mLifecycleObserver调用自己的onStateChanged()方法,
//所以我们需要看下这个类的onStateChanged()方法干了啥?
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
package androidx.lifecycle;
import androidx.annotation.NonNull;
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
//--------------------------------分割线--------------------------------
package androidx.lifecycle;
public interface LifecycleObserver {
}
打开一看,发现LifecycleEventObserver是个接口,继承的父类呢?嘿嘿~也是个接口,所以这时我们就需要看下LifecycleRegistry中的那个内部类,看看它里面是如何创建了这个LifecycleEventObserver的~
/**
* 这个class是LifecycleRegistry中的一个内部类
*/
static class ObserverWithState {
Lifecycle.State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, Lifecycle.State initialState) {
//看了一圈又回来了~,快让我们来看下这个方法是如何创建的LifecycleEventObserver对象的吧
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Lifecycle.Event event) {
Lifecycle.State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
/**
* Lifecycling.java部分代码
*/
@NonNull
@SuppressWarnings("deprecation")
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);
}
//原来是这里返回的一个FullLifecycleObserverAdapter~
//因为我们在MainActivity.java中注册的那个Observer就是继承了DefaultLifecycleObserver
//而DefaultLifecycleObserver是继承了FullLifecycleObserver,所以满足条件~
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);
}
那么让我们来看下FullLifecycleObserverAdapter.onStateChanged()吧
package androidx.lifecycle;
import androidx.annotation.NonNull;
class FullLifecycleObserverAdapter implements LifecycleEventObserver {
private final FullLifecycleObserver mFullLifecycleObserver;
private final LifecycleEventObserver mLifecycleEventObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
LifecycleEventObserver lifecycleEventObserver) {
mFullLifecycleObserver = fullLifecycleObserver;
mLifecycleEventObserver = lifecycleEventObserver;
}
//原来是这么实现的,那么这个mFullLifecycleObserver是谁呢?还记得我们在LifecycleRegistry
//中通过Lifecycling.lifecycleEventObserver(observer)传入的那个吗?
//这时候就会有人问:那这个observer是从哪儿来的呢?
//还记得那个getLifecycle().addObserver(lifecycleObserver)吗?
//没错,在addObserver()方法中创建ObserverWithState时已经将我们在MainActivity
//中创建的observer传进去了,所以onStateChanged()中调用的onCreate() / onStart() / onResume()...
//就是在回调我们在MainActivity中的那个LifecycleObserver的方法~
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mFullLifecycleObserver.onCreate(source);
break;
case ON_START:
mFullLifecycleObserver.onStart(source);
break;
case ON_RESUME:
mFullLifecycleObserver.onResume(source);
break;
case ON_PAUSE:
mFullLifecycleObserver.onPause(source);
break;
case ON_STOP:
mFullLifecycleObserver.onStop(source);
break;
case ON_DESTROY:
mFullLifecycleObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
if (mLifecycleEventObserver != null) {
mLifecycleEventObserver.onStateChanged(source, event);
}
}
}
2.Lifecycle如果感知生命周期变化?
答:通过一个ReportFragment实现感知。
这里我们可以看下androidx.activity.ComponentActivity的父类:androidx.core.app.ComponentActivity.java 的onCreate() 方法。
/**
* androidx.core.app.ComponentActivity.java部分代码
*/
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//这里是重点~
ReportFragment.injectIfNeededIn(this);
}
}
下面让我们看下ReportFragment.java中的injectIfNeededIn()方法,坚持就是胜利!,答案就在这个类里~
/**
* androidx.lifecycle.ReportFragment.java部分代码
*/
package androidx.lifecycle;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
/**
* Internal class that dispatches initialization events.
*
* @hide
*/
@SuppressWarnings({"UnknownNullness", "deprecation"})
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends android.app.Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
public static void injectIfNeededIn(Activity activity) {
//29及以后使用该方法注册
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
androidx.lifecycle.ReportFragment.LifecycleCallbacks.registerIn(activity);
}
//在API 29之前,为了保持与旧版本 ProcessLifecycleOwner的兼容性(更新生命周期运行时,
//并且需要支持不从支持库的FragmentActivity拓展的活动)
//请使用框架片段来获取正确的生命周期事件的计时
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new androidx.lifecycle.ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
//ReportFragment的生命周期方法都会调用这个方法~
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
//那就让我们来看下handleLifecycleEvent()方法
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
//那就让我们来看下handleLifecycleEvent()方法
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
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(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// Only dispatch events from ReportFragment on API levels prior
// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
// added in ReportFragment.injectIfNeededIn
dispatch(getActivity(), event);
}
}
// this class isn't inlined only because we need to add a proguard rule for it (b/142778206)
// In addition to that registerIn method allows to avoid class verification failure,
// because registerActivityLifecycleCallbacks is available only since api 29.
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new androidx.lifecycle.ReportFragment.LifecycleCallbacks());
}
@Override
public void onActivityCreated(@NonNull Activity activity,
@Nullable Bundle bundle) {
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity,
@NonNull Bundle bundle) {
}
@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
}
}
看到这里现在的矛头全部指向handleLifecycleEvent()方法,让我们来看下这个方法
/**
* LifecycleRegistry.java 部分代码
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(Lifecycle.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) {
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);
}
Map.Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//可以看下这里~
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState> entry = descendingIterator.next();
LifecycleRegistry.ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Lifecycle.Event event = Lifecycle.Event.downFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event down from " + observer.mState);
}
pushParentState(event.getTargetState());
//这里observer.dispatchEvent(),最终会调用到ObserverWithState.onStateChanged()
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, LifecycleRegistry.ObserverWithState> entry = ascendingIterator.next();
LifecycleRegistry.ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
final Lifecycle.Event event = Lifecycle.Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
//这里observer.dispatchEvent(),最终会调用到ObserverWithState.onStateChanged()
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
最终结论:Activity会添加一个ReportFragment,通过ReportFragment中每个生命周期方法调用dispatch()方法,最终调用到了LifecycleRegistry.handleLifecycleEvent(),然后调用到ObserverWithState.onStateChanged()
完结,撒花~