Android Architecture Component之Lifecycle-Aware Components源码分析

Android 224 2017-11-08 16:57

用法

  • api调用
    • 观察者模式: 观察者模式面向的需求是:A对象(观察者)对B对象(被观察者)的某种变化高度敏感,需要在B变化的一瞬间做出反应。举个例子,新闻里喜闻乐见的警察抓小偷,警察需要在小偷伸手作案的时候实施抓捕。在这个例子里,警察是观察者、小偷是被观察者,警察需要时刻盯着小偷的一举一动,才能保证不会错过任何瞬间。程序里的观察者和这种真正的【观察】略有不同,观察者不需要时刻盯着被观察者(例如A不需要每隔1ms就检查一次B的状态),二是采用注册(Register)或者成为订阅(Subscribe)的方式告诉被观察者:我需要你的某某状态,你要在它变化时通知我。采取这样被动的观察方式,既省去了反复检索状态的资源消耗,也能够得到最高的反馈速度
    • 在lifecycle中,LifecycleObserver 是观察者都需要到被观察者Lifecycle中去注册,在生命周期有变化的时候告知所有的observer
    • 自定义观察者
      eg:
    public class MyLifecycle implements LifecycleObserver {
    
    
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner, Lifecycle.Event event) {
        System.out.println("onAny:" + event.name());
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
        System.out.println("onCreate");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy() {
        System.out.println("onDestroy");
    }
    }
    
    • 注册观察者
      在activity或者fragmetn中注册
     getLifecycle().addObserver(new MyLifecycle());
    

代码分析

  1. 手写个观察者模式

    • 观察者
        public interface LifecycleObserver {
        public abstract void onStateChanged(Lifecycle.Event mEvent);
        }
    
    • 被观察者lifecycle
    package com.delta.androiddagger;
    
    
    /**
     * description :
     *
     * @author :  Wenju.Tian
     * @version date : 2017/11/6 14:58
     */
    public abstract  class Lifecycle {
    
        public abstract void addObserver(LifecycleObserver observer);
        
        public abstract void removeObserver(LifecycleObserver observer);
    
        public abstract void handleLifecycleEvent( Event event);
    
        @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;
    
           
            }
        
    }
    
    

    在官方的libary中lifecycle扮演者被观察者(小偷)的角色,所有的观察者(警察)都要在这里注册,移除,notify.

    被观察者实现类

        public class LifecycleRegistry extends Lifecycle {
    
        private State mState;
        private List<LifecycleObserver> mObservers = new ArrayList<>();
        @Override
        public void addObserver(LifecycleObserver observer) {
    
            if (mObservers.contains(observer)) {
                return;
            }
            mObservers.add(observer);
        }
    
        @Override
        public void removeObserver(LifecycleObserver observer) {
    
            if (mObservers.contains(observer)) {
                mObservers.remove(observer);
            }
        }
    
        @Override
        public void handleLifecycleEvent(Event event) {
    
            for (LifecycleObserver mObserver : mObservers) {
    
    
                if (sync(event))
                //判断event状态执行change方法
                mObserver.onStateChanged(event);
            }
        }
    
        private boolean sync(Event event) {
    
            State mStateAfter = getStateAfter(event);
            if (mState==mStateAfter)
                return false;
            return true;
        };
       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);
        }
    
    }
    

    在官方libary中LifecycleRegistry时lifecycle的实现类,这里我们是模拟其实现,handleLifecycleEvent是真正处理事件的方法,在这里可以遍历observer,根据相应的状态变更,notify相应的observer.

    • 自定义Activity
    public class MyActivity {
    
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry();
    
    public LifecycleRegistry getLifecycleRegistry() {
        return mLifecycleRegistry;
    }
    
    public static void main(String[] args) {
        new MyActivity().getLifecycleRegistry().addObserver(new LifecycleObserver() {
            @Override
            public void onStateChanged(Lifecycle.Event mEvent) {
    
            }
        });
    }
    }
    

    这个类是我们模拟的activity,activity中拥有一个被观察者叫LifecycleRegistry。在官方源码中对应的activity中也会有这样一个LifecycleRegistry。我们总结一下就是LifecycleRegistry用handleLifecycleEvent方法通知所有的观察者做出相应的改变。

  2. 官方源代码分析

  • 首先看下被观察者LifecycleRegistry,我们看下他的addObserver
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        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;
        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--;
    }
    
    
    我们需要被观察者注册到LifecycleRegistry需要一个集合来维护官方用的是自己定义的一个mObserverMap,从上面可以看出。里面不是直接存的我们观察者LifecycleObserver,而是做了封装一个叫做ObserverWithState的类我们看下源码
    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;
        }
    }
    

里面有两个变量,mState存放的是这个observer的状态,GenericLifecycleObserver是我们所需要的观察者,而这个观察者是我们传进来的LifecycleObserver通过Lifecycling.getCallback(observer)方法进行实例化的,我们看下getCallback方法
```
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}

    if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) 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);
}
```
当调用 getCallback 时,Lifecycling 会根据传入的 Object(LifecycleObserver)调用 getGeneratedAdapterConstructor。接着看源码
```
        @Nullable
    private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor(
           Class<?> klass) {
       final String fullPackage = klass.getPackage().getName();
       String name = klass.getCanonicalName();
       // anonymous class bug:35073837
       if (name == null) {
           return null;
       }
       final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
               name.substring(fullPackage.length() + 1));
       try {
           @SuppressWarnings("unchecked")
           final Class<? extends GenericLifecycleObserver> aClass =
                   (Class<? extends GenericLifecycleObserver>) Class.forName(
                           fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
           return aClass.getDeclaredConstructor(klass);
       } catch (ClassNotFoundException e) {
           final Class<?> superclass = klass.getSuperclass();
           if (superclass != null) {
               // 找不到 LifecycleAdapter 时获取父类的 LifecycleAdapter
               return getGeneratedAdapterConstructor(superclass);
           }
       } catch (NoSuchMethodException e) {
           // this should not happen
           throw new RuntimeException(e);
       }
       return null;
    }
    static String getAdapterName(String className) {
       return className.replace(".", "_") + "_LifecycleAdapter";
    }
```
不难看出,getGeneratedAdapterConstructor 主要是获取 annotationProcessor 生成的 xxx_LifecycleAdapter(eg:我们定义了MyLifecycle,就会自动生成MyLifecycle_LifecycleAdapter,存放在build/generated/source/apt文件夹下,感兴趣的同学请看怎么编译器生成注解的文章)的构造函数,并实例化返回到 getCallback 中。需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父类时会试图获取父类的。 LifecycleAdapter(估计是为了应对混淆时只混淆了子类的情况)。
apt自动生成的MyLifecycle_LifecycleAdapter源码
```
     public class MyLifecycle_LifecycleAdapter implements GeneratedAdapter {
      final MyLifecycle mReceiver;
    
      MyLifecycle_LifecycleAdapter(MyLifecycle receiver) {
        this.mReceiver = receiver;
      }
    
      @Override
      public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
          MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {
          if (!hasLogger || logger.approveCall("onAny", 4)) {
            mReceiver.onAny(owner,event);
          }
          return;
        }
        if (event == Lifecycle.Event.ON_CREATE) {
          if (!hasLogger || logger.approveCall("onCreate", 1)) {
            mReceiver.onCreate();
          }
          return;
        }
        if (event == Lifecycle.Event.ON_DESTROY) {
          if (!hasLogger || logger.approveCall("onDestroy", 1)) {
            mReceiver.onDestroy();
          }
          return;
        }
      }
    }
```
里面有个callMethods根据不同得到event执行不同的方法回调,调用我们自己定义的MyLifecycle。回到getCallback方法,这时候我们自动生成的MyLifecycle_LifecycleAdapter,在return的时候传进去,如果只有一个构造的话返回SingleGeneratedAdapterObserver,多个的话返回CompositeGeneratedAdaptersObserver都失败的话返回ReflectiveGenericLifecycleObserver,估计是为了应对代码混淆的情况。

我们看下SingleGeneratedAdapterObserver的源码
```
        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);
        }
    }
```
GeneratedAdapter就是MyLifecycle_LifecycleAdapter,SingleGeneratedAdapterObserver有个onStateChanged方法,它是有谁调用的?

我们回到ObserverWithState,发现了它的dispatchEvent方法里面有个onStateChanged,而这个mLifecycleObserver就是我们上面讲的SingleGeneratedAdapterObserver,它是通过我们上面讲的Lifecycling.getCallback(observer)生成的。
```
    void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
```
后面会讲到怎么通知所有的观察者处理事件,我们先总结下添加及调用的过程。
* acitivty中调用LifecycleRegistry的ddObserver(LifecycleObserver observer)
* LifecycleObserver 被封装成了ObserverWithState并存入我们集合中
* ObserverWithState 在构造的时候,调用了Lifecycling.getCallback(observer)
    * getCallback(observer)调用了createGeneratedAdapter()
    * createGeneratedAdapter通过反射生了MyLifecycle_LifecycleAdapter对象
    * MyLifecycle_LifecycleAdapter是在编译器有apt帮我们生成的
    * 最后返回一个SingleGeneratedAdapterObserver对象
* 在ObserverWithState的dispatchEvent()方法调用了SingleGeneratedAdapterObserver对象的onStateChanged方法,二他又调用了MyLifecycle_LifecycleAdapter的callMethods,然后再调用了我们自定义的MyLifecycle方法   
  • 被观察者LifecycleRegister的handleLifecycleEvent(),源码分析

     public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
          State next = getStateAfter(event);
          moveToState(next);
      }
    
    • 其中有个event和state是我们需要关注的,看下源码都有哪些
     public enum Event {
         /**
          * Constant for onCreate event of the {@link LifecycleOwner}.
          */
         ON_CREATE,
         /**
          * Constant for onStart event of the {@link LifecycleOwner}.
          */
         ON_START,
         /**
          * Constant for onResume event of the {@link LifecycleOwner}.
          */
         ON_RESUME,
         /**
          * Constant for onPause event of the {@link LifecycleOwner}.
          */
         ON_PAUSE,
         /**
          * Constant for onStop event of the {@link LifecycleOwner}.
          */
         ON_STOP,
         /**
          * Constant for onDestroy event of the {@link LifecycleOwner}.
          */
         ON_DESTROY,
         /**
          * An {@link Event Event} constant that can be used to match all events.
          */
         ON_ANY
     }
     
     
     public enum State {
         /**
          * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
          * any more events. For instance, for an {@link android.app.Activity}, this state is reached
          * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
          */
         DESTROYED,
    
         /**
          * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
          * the state when it is constructed but has not received
          * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
          */
         INITIALIZED,
    
         /**
          * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
          * is reached in two cases:
          * <ul>
          *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
          *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
          * </ul>
          */
         CREATED,
    
         /**
          * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
          * is reached in two cases:
          * <ul>
          *     <li>after {@link android.app.Activity#onStart() onStart} call;
          *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
          * </ul>
          */
         STARTED,
    
         /**
          * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
          * is reached after {@link android.app.Activity#onResume() onResume} is called.
          */
         RESUMED;
    
         /**
          * Compares if this State is greater or equal to the given {@code state}.
          *
          * @param state State to compare with
          * @return true if this State is greater or equal to the given {@code state}
          */
         public boolean isAtLeast(@NonNull State state) {
             return compareTo(state) >= 0;
         }
     }
    

    他们是怎样的一个对应关系呢,我们看下官方图解
    [图片上传失败...(image-927d44-1510123896670)]
    举个列子,假如传入的event是onstart那么我们就可以知道它现在的状态是create,经过onstart他要去Started状态.我们再回到handleLifecycleEvent
    其中getStateAfter方法就是获得的是next状态就是Started.那么MovetoNext方法是干啥的呢?
    看下源码

     private void moveToState(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;
     }
    

    里面有个mstate变量这个变量存放的是LifecycleRegister的当前的state,以上面例子,假如我们当前的是Started,那么我们就不需要sync()了;如果不是Started,我们先当前的mState状态重新赋值,然后同步,怎么同步策略呢?看 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;
     }
    

    它是比较当前的状态和我们存我们存放观察者的集合最早或最新放入的观察者的状态,我们知道集合存放的是ObserverWithState里面有我们注册观察者的状态,假如mState是STARTED,如果观察者的状态是CREATED,那么我们需要通过forwardPass()告诉观察者状态变了你要回退,看官方图就可以知道这个event就为ON_START,看下forwardPass()源码

     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
                     pushParentState(observer.mState);
                 observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                 popParentState();
             }
         }
    

    第一个while循坏遍历我们存储观察者的集合,第二个是要处理各个状态经过的event,eg:msate是RESUMED而ObserverWithState中的state是INITIALIZED,那么他要分发ON_CREATE,ON_RESUME,调用ObserverWithState的dispatchEvent方法,其中upEvent就是返回event,这就和我们上面的连接起来了。

  • 被观察者LifecycleRegister的handleLifecycleEvent()调用,我们先猜测一下,引文这个方法需要传入一个event事件,那么这个event肯定和生命周期关联起来,那怎么关联的呢?还有这个官方的框架怎么没有看到初始化的地方?

    其实官方用了一个很好的方法,它是在provider中进行初始化的,我们找到xml文件,在as3.0中在xml中我们能找到merge的manifest文件看下

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="android.arch.lifecycle.extensions" >
    
       <uses-sdk
           android:minSdkVersion="14"
           android:targetSdkVersion="26" />
    
       <application>
           <provider
               android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
               android:authorities="${applicationId}.lifecycle-trojan"
               android:exported="false"
               android:multiprocess="true" />
       </application>
    
    </manifest>
    

    有个provider这个清单文件是在lifecycle:extensions下的也就是说merge之后这个provider就加到我们的manifest,我们看下ProcessLifecycleOwnerInitializer,源码

     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
        public class ProcessLifecycleOwnerInitializer extends ContentProvider {
        @Override
        public boolean onCreate() {
            LifecycleDispatcher.init(getContext());
            ProcessLifecycleOwner.init(getContext());
            return true;
        }
    
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, String[] strings, String s, String[] strings1,
            String s1) {
        return null;
    }
    
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
        return null;
    }
    
    @Override
    public int delete(@NonNull Uri uri, String s, String[] strings) {
        return 0;
    }
    
    @Override
    public int update(@NonNull Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
    }
    
    

    我们可以看到onCreate()方法里面有init方法,我们重点关注 LifecycleDispatcher.init(getContext());
    看下他的源码

    static void init(Context context) {
       if (sInitialized.getAndSet(true)) {
           return;
       }
       ((Application) context.getApplicationContext())
               .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }
    

    在这里注册了ActivityLifecycleCallbacks叫做new DispatcherActivityCallback(),看下他的源码

    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);
       }
    
       @Override
       public void onActivityStopped(Activity activity) {
           if (activity instanceof FragmentActivity) {
               markState((FragmentActivity) activity, CREATED);
           }
       }
    
       @Override
       public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
           if (activity instanceof FragmentActivity) {
               markState((FragmentActivity) activity, CREATED);
           }
       }
    }
    

    我们看到onActivityCreated中注册了一个FragmentLifecycleCallbacks,这个是监控fragment的生命周期回调,我们看下面那句injectIfNeededIn,看下他的源码

    public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";
    
    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) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            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);
        // just want to be sure that we won't leak reference to an activity
        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();
    }
    

    在injectIfNeededIn中我们把reportFragment加入到我们的activity中然后在其各个生命周期中调用dispatch,最后调用了被观察者的handleLifecycleEvent,这就回答了我们的问题,但是还有一个疑问,就是为什么要用fragment而不用ActivityCallBack呢,其实很简单,ActivityCallBack生命周期比我们的activity的生命周期要早,也就是说
    ctivityCallBack的oncreate比activity的要早,所以我们用了fragment的生命周期和我们handleLifecycleEvent相绑定。这设计的很巧妙。

文章评论