public class FourActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BusLogUtils.d("------AppCompatActivity onCreate() called"); testLifecycle(); } @Override protected void onResume() { super.onResume(); BusLogUtils.d("------AppCompatActivity onResume() called"); } @Override protected void onDestroy() { super.onDestroy(); BusLogUtils.d("------AppCompatActivity onDestroy() called"); } private void testLifecycle() { getLifecycle().addObserver(new LifecycleObserver() { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreate(){ BusLogUtils.d("------LifecycleObserver onCreate() called"); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResume(){ BusLogUtils.d("------LifecycleObserver onResume() called"); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestroy(){ BusLogUtils.d("------LifecycleObserver onDestroy() called"); } }); } }
//打开页面 2020-03-06 09:44:09.522 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------AppCompatActivity onCreate() called 2020-03-06 09:44:09.545 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------LifecycleObserver onCreate() called 2020-03-06 09:44:09.551 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------AppCompatActivity onResume() called 2020-03-06 09:44:09.552 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------LifecycleObserver onResume() called //关闭页面 2020-03-06 09:44:14.265 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------LifecycleObserver onStop() called 2020-03-06 09:44:14.265 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------AppCompatActivity onStop() called 2020-03-06 09:44:14.266 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------LifecycleObserver onDestroy() called 2020-03-06 09:44:14.266 11647-11647/com.ycbjie.yclivedatabus D/BusLogUtils: ------AppCompatActivity onDestroy() called
public abstract class Lifecycle { @MainThread public abstract void addObserver(@NonNull LifecycleObserver observer); @MainThread public abstract void removeObserver(@NonNull LifecycleObserver observer); @MainThread @NonNull public abstract State getCurrentState(); @SuppressWarnings("WeakerAccess") public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } @SuppressWarnings("WeakerAccess") public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } } }
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) { //把Fragment加入到Activity中 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 activity = getActivity(); 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); } } } //... }
class LifecycleDispatcher { static void init(Context context) { if (sInitialized.getAndSet(true)) { return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback()); } @SuppressWarnings("WeakerAccess") @VisibleForTesting 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); } } }
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
@RestrictTo(LIBRARY_GROUP) public class ComponentActivity extends Activity implements LifecycleOwner { private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @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); } @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } } public class LifecycleRegistry extends Lifecycle {} public abstract class Lifecycle {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnLifecycleEvent { Lifecycle.Event value(); }
public void handleLifecycleEvent(Lifecycle.Event event) { mState = getStateAfter(event); if (mHandlingEvent || mAddingObserverCounter != 0) { mNewEventOccurred = true; // we will figure out what to do on upper level. return; } mHandlingEvent = true; sync(); mHandlingEvent = false; }
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); }
private void sync() { 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(); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(); } } mNewEventOccurred = false; }
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()))) { //调用 downEvent 获取更前面的 Event Event event = downEvent(observer.mState); pushParentState(getStateAfter(event)); //分发 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); }
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; } }
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver { //mWrapped 是 我们的 Observer private final Object mWrapped; //反射 mWrapped 获取被注解了的方法 private final CallbackInfo mInfo; @SuppressWarnings("WeakerAccess") static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>(); ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = getInfo(mWrapped.getClass()); } @Override public void onStateChanged(LifecycleOwner source, Event event) { invokeCallbacks(mInfo, source, event); } private void invokeCallbacks(CallbackInfo info, LifecycleOwner source, Event event) { invokeMethodsForEvent(info.mEventToHandlers.get(event), source, event); invokeMethodsForEvent(info.mEventToHandlers.get(Event.ON_ANY), source, event); } private void invokeMethodsForEvent(List<MethodReference> handlers, LifecycleOwner source, Event event) { if (handlers != null) { for (int i = handlers.size() - 1; i >= 0; i--) { MethodReference reference = handlers.get(i); invokeCallback(reference, source, event); } } } //最后走到 invokeCallback 这里 private void invokeCallback(MethodReference reference, LifecycleOwner source, Event event) { //noinspection TryWithIdenticalCatches try { switch (reference.mCallType) { case CALL_TYPE_NO_ARG: reference.mMethod.invoke(mWrapped); break; case CALL_TYPE_PROVIDER: reference.mMethod.invoke(mWrapped, source); break; case CALL_TYPE_PROVIDER_WITH_EVENT: reference.mMethod.invoke(mWrapped, source, event); break; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method", e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static CallbackInfo getInfo(Class klass) { CallbackInfo existing = sInfoCache.get(klass); if (existing != null) { return existing; } existing = createInfo(klass); return existing; } //通过反射获取 method 信息 private static CallbackInfo createInfo(Class klass) { //... Method[] methods = klass.getDeclaredMethods(); Class[] interfaces = klass.getInterfaces(); for (Class intrfc : interfaces) { for (Entry<MethodReference, Event> entry : getInfo(intrfc).mHandlerToEvent.entrySet()) { verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass); } } for (Method method : methods) { OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class); if (annotation == null) { continue; } 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"); } } Event event = annotation.value(); //... MethodReference methodReference = new MethodReference(callType, method); verifyAndPutHandler(handlerToEvent, methodReference, event, klass); } CallbackInfo info = new CallbackInfo(handlerToEvent); sInfoCache.put(klass, info); return info; } @SuppressWarnings("WeakerAccess") static class CallbackInfo { final Map<Event, List<MethodReference>> mEventToHandlers; final Map<MethodReference, Event> mHandlerToEvent; CallbackInfo(Map<MethodReference, Event> handlerToEvent) { //... } } static class MethodReference { final int mCallType; final Method mMethod; MethodReference(int callType, Method method) { mCallType = callType; mMethod = method; mMethod.setAccessible(true); } } private static final int CALL_TYPE_NO_ARG = 0; private static final int CALL_TYPE_PROVIDER = 1; private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2; }
@Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; //构造ObserverWithState ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //将observer对象和statefulObserver对象添加到FastSafeIterableMap数据结构中 ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // 它是null,我们应该被摧毁。快速回退 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--; }
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; } }
@NonNull static GenericLifecycleObserver getCallback(Object object) { if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } //获取传入对象object的Class对象 final Class<?> klass = object.getClass(); //获取类型是否包含注解处理器 int type = getObserverConstructorType(klass); if (type == GENERATED_CALLBACK) { 这里是包含注解处理器 返回SingleGeneratedAdapterObserver 或者CompositeGeneratedAdaptersObserver 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); }
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver { private final GeneratedAdapter mGeneratedAdapter; SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) { mGeneratedAdapter = generatedAdapter; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { mGeneratedAdapter.callMethods(source, event, false, null); mGeneratedAdapter.callMethods(source, event, true, null); } }
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class CompositeGeneratedAdaptersObserver implements GenericLifecycleObserver { private final GeneratedAdapter[] mGeneratedAdapters; CompositeGeneratedAdaptersObserver(GeneratedAdapter[] generatedAdapters) { mGeneratedAdapters = generatedAdapters; } @Override public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { MethodCallsLogger logger = new MethodCallsLogger(); for (GeneratedAdapter mGenerated: mGeneratedAdapters) { mGenerated.callMethods(source, event, false, logger); } for (GeneratedAdapter mGenerated: mGeneratedAdapters) { mGenerated.callMethods(source, event, true, logger); } } }
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver { 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); } }