Android JetPack架构组件(三)带你了解Lifecycle

每日一言:每个人都有俩条路,一条用心走,叫做梦想;一条用脚走,叫做现实。心走得太慢,现实会苍白;脚走得太慢,梦想不会高飞。人生得精彩,莫过于心走得美,与脚步合一。不忘初心,脚踏实地,你也可以创造独有得精彩。

原文链接:http://liuwangshu.cn/application/jetpack/3-lifecycle-theory.html

前言

在上一篇文章中,我们学习了如何去使用Lifecycle,当然之会使用是不够的,还需要了解它的原理,这是成为优秀工程师必备的。这篇文章就来学习Lifecycle的基本原理。

1.Lifecycle的生命周期状态事件和状态

Lifecycle使用两个枚举来跟踪其关联组件的生命周期状态,这两个枚举分别是Event和State。
State指的是Lifecycle的生命周期所处的状态。
Event代表Lifecycle生命周期对应的事件,这些事件会映射到Activity和Fragment中的回调事件中。

Android 9.0的Lifecycle的源码如下所示。
frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/Lifecycle.java

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

Lifecycle是一个抽象类,其内部不仅包括了添加和移除观察者的方法,还包括了此前说到的Event和State枚举。可以看到Event中的事件和Activity的生命周期几乎是对应的,除了ON_ANY,它可用于匹配所有事件。

State与Event的关系入下面的时序图所示。


Android JetPack架构组件(三)带你了解Lifecycle_第1张图片
m1KKN6.png

2.Lifecycle如何观察Activity和Fragment的生命周期

在Android Support Library 26.1.0 及其之后的版本,Activity和Fragment已经默认实现了LifecycleOwner接口,LifecycleOwner可以理解为被观察者,那么Lifecycle是如何观察Activity和Fragment的生命周期的呢?

在上一篇文章举的例子中,MainActivity继承了AppCompatActivity,而AppCompatActivity继承了FragmentActivity。在Android 8.0时,FragmentActivity继承自SupportActivity,而在Android 9.0,FragmentActivity继承自ComponentActivity 。SupportActivity和ComponentActivity的代码区别不大,这里以ComponentActivity举例,如下所示。

frameworks/support/compat/src/main/java/androidx/core/app/ComponentActivity.java

@RestrictTo(LIBRARY_GROUP)
public class ComponentActivity extends Activity implements LifecycleOwner {
    private SimpleArrayMap, ExtraData> mExtraDataMap =
            new SimpleArrayMap<>();

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//1

    @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);//2
    }

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

    @RestrictTo(LIBRARY_GROUP)
    public  T getExtraData(Class extraDataClass) {
        return (T) mExtraDataMap.get(extraDataClass);
    }

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

    @RestrictTo(LIBRARY_GROUP)
    public static class ExtraData {
    }
}

注释1处创建了LifecycleRegistry,它是Lifecycle的实现类。注释4处实现了LifecycleOwner接口定义的getLifecycle方法,返回了LifecycleRegistry。在注释3处,将Lifecycle的State设置为CREATED。正常来说应该在ComponentActivity的各个生命周期方法中改变Lifecycle的State,显然在ComponentActivity中没有做这些,而是将这个任务交给了ReportFragment,注释2处的将ComponentActivity注入到ReportFragment中。

frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/ReportFragment.java

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
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);
    }
   ...
    @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);//1
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

  ...
    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {//2
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {//3
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }
  ...
}

ReportFragment的onStart方法中会调用注释1处的dispatch方法。在dispatch方法的注释2处,判断Activity是否实现了LifecycleRegistryOwner接口,LifecycleRegistryOwner继承了LifecycleOwner接口,这两个接口不同的是,LifecycleRegistryOwner定义的getLifecycle方法返回的是LifecycleRegistry类型,而LifecycleOwner定义的getLifecycle方法返回的是Lifecycle类型。注释3处如果Activity实现了LifecycleOwner接口,会调用LifecycleRegistry的handleLifecycleEvent方法。
frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/LifecycleRegistry.java

 public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}

getStateAfter方法会获取“即将的事件” :当前事件执行后,即将会处于什么事件,代码如下所示。

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

这个和文章开头给出的State与Event关系的时序图对照看会比较好理解,比如当前执行了ON_CREATE事件或者ON_STOP事件,那么状态就会处于CREATED。回到handleLifecycleEvent方法,其内部还会调用moveToState方法。

private void moveToState(State next) {
     if (mState == next) {
         return;
     }
     mState = next;
     if (mHandlingEvent || mAddingObserverCounter != 0) {
         mNewEventOccurred = true;
         return;
     }
     mHandlingEvent = true;
     sync();
     mHandlingEvent = false;
 }

如果当前所处的状态和即将要处于的状态一样就不做任何操作,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;
          if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
              backwardPass(lifecycleOwner);
          }
          Entry newest = mObserverMap.newest();
          if (!mNewEventOccurred && newest != null
                  && mState.compareTo(newest.getValue().mState) > 0) {
              forwardPass(lifecycleOwner);
          }
      }
      mNewEventOccurred = false;
  }

sync方法中会根据当前状态和mObserverMap中的eldest和newest的状态做对比 ,判断当前状态是向前还是向后,比如由STARTED到RESUMED是状态向前,反过来就是状态向后,这个不要和Activity的生命周期搞混。向前还是向后的代码大同小异,这里以向后为例。

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();//1
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));//2
            popParentState();
        }
    }
}

注释1处的用于获取ObserverWithState,后面会在提到它。
注释2处的upEvent方法会得到当前状态的向前状态。ObserverWithState的dispatchEvent方法如下所示。

frameworks/support/lifecycle/runtime/src/main/java/androidx/lifecycle/LifecycleRegistry.java

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.getCallback(observer);//1
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}

从名称就可以看出来,它内部包括了State和GenericLifecycleObserver,GenericLifecycleObserver是一个接口,它继承了LifecycleObserver接口。
ReflectiveGenericLifecycleObserver和CompositeGeneratedAdaptersObserver是GenericLifecycleObserver的实现类,这里主要查看ReflectiveGenericLifecycleObserver的onStateChanged方法是如何实现的。
frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ReflectiveGenericLife.java

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);//1
    }
}

注释1处会调用CallbackInfo的invokeCallbacks方法,在讲这个方法前,需要先了解CallbackInfo是怎么创建的,是由createInfo方法创建的,如下所示。

private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
       Class superclass = klass.getSuperclass();
       Map handlerToEvent = new HashMap<>();
      ...
       Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
       boolean hasLifecycleMethods = false;
       for (Method method : methods) {
           OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);//1
           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");
               }
           }
           Lifecycle.Event event = annotation.value();//2
           ...
           MethodReference methodReference = new MethodReference(callType, method);//3
           verifyAndPutHandler(handlerToEvent, methodReference, event, klass);//4
       }
       CallbackInfo info = new CallbackInfo(handlerToEvent);//5
       mCallbackMap.put(klass, info);
       mHasLifecycleMethods.put(klass, hasLifecycleMethods);
       return info;
   }

关键点在注释1处,不断的遍历各个方法,获取方法上的名为OnLifecycleEvent的注解,这个注解正是实现LifecycleObserver接口时用到的。注释2处获取该注解的值,也就是在@OnLifecycleEvent中定义的事件。注释3处新建了一个MethodReference,其内部包括了使用了该注解的方法。注释4处的verifyAndPutHandler方法用于将MethodReference和对应的Event存在类型为Map 的handlerToEvent中。
注释5处新建CallbackInfo,并将handlerToEvent传进去。

接着回头看CallbackInfo的invokeCallbacks方法,代码如下所示。
frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ClassesInfoCache.java

static class CallbackInfo {
        final Map> mEventToHandlers;
        final Map mHandlerToEvent;
        CallbackInfo(Map handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            for (Map.Entry entry : handlerToEvent.entrySet()) {//1
                Lifecycle.Event event = entry.getValue();
                List 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);//2
            invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
        }

        private static void invokeMethodsForEvent(List handlers,
                LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
            if (handlers != null) {
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);//1
                }
            }
        }

注释1处的循环的意义在于将handlerToEvent进行数据类型转换,转化为一个HashMap,key的值为事件,value的值为MethodReference。注释2处的invokeMethodsForEvent方法会传入mEventToHandlers.get(event),也就是事件对应的MethodReference的集合。invokeMethodsForEvent方法中会遍历MethodReference的集合,调用MethodReference的invokeCallback方法。

frameworks/support/lifecycle/common/src/main/java/androidx/lifecycle/ClassesInfoCache.java

@SuppressWarnings("WeakerAccess")
   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);
           }
       }
     ...
   }

MethodReference类中有两个变量,一个是callType,它代表调用方法的类型,另一个是Method,它代表方法,不管是哪种callType都会通过invoke对方法进行反射。
简单来说,实现LifecycleObserver接口的类中,注解修饰的方法和事件会被保存起来,通过反射对事件的对应方法进行调用。
这个调用链的时序图如下所示。


Android JetPack架构组件(三)带你了解Lifecycle_第2张图片
m1KM4K.png

3.Lifecycle关联类

第2节是以一个调用链的形式来介绍Lifecycle,调用链中涉及的类具体都是什么关系很难整体去把握,因此这里再以UML图的形式给出Lifecycle关联类,版本为Android 9.0。

Android JetPack架构组件(三)带你了解Lifecycle_第3张图片
m1KuAx.png

AppCompatActivity继承自FragmentActivity,这两个类都不算是Lifecycle关联类。FragmentActivity实现了LifecycleOwner接口,LifecycleOwner和Lifecycle有一个”弱拥有的关系”,LifecycleRegistry继承自Lifecycle,剩下的就不多介绍了,看图一目了然。如果看不懂UML类图,可以阅读《大话设计模式》这本书。


Android JetPack架构组件(三)带你了解Lifecycle_第4张图片
qrcode_for_gh_a02f69255027_258.jpg

你可能感兴趣的:(Android JetPack架构组件(三)带你了解Lifecycle)