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

前言

系列文章

android.arch.lifecycle 包提供了类和接口允许你构建生命周期感知(lifecycle-aware)的组件——可以基于当前activity或fragment生命周期自动调节它们的行为的组件。

注意:将 android.arch.lifecycle 导入Android工程,请参见将Architecture Components引入工程。
大部分定义在Android框架中的组件都包含附加到其上的生命周期。这些生命周期由操作系统或运行在你的进程中的框架代码管理。它们是Android如何工作的核心,你的应用程序必须尊重它们。不这样做可能会触发内存泄漏甚至应用程序崩溃。

常用场景

  • 位置获取精细度的切换,在程序可见启用精度高定位,程序进入后台切换低精度定位
  • 视频缓冲,在生命周期组件启动启动视频缓冲,延迟缓冲直到应用程序完全启动,在终止应用的时候销毁。
  • 启动停止网络连接,程序在前台的时候更新网络数据,后台的时候取消或暂停
  • 暂停或者回复动画绘制。使用生命周期组件的时候在后台的时候暂停动画绘制,前台的时候恢复绘制。

用法

  • 观察者模式: 观察者模式面向的需求是: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());
    
    • 在service中注册继承LifecycleService
    public class MyService extends LifecycleService {
    
    
    @Override
    public void onCreate() {
        super.onCreate();
    
        getLifecycle().addObserver(new MyLifecycle());
    }
    }
    
    • 监测app进入前后台的写法
    
    public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyLifecycle());
    }
    }
    

代码分析

  1. 先不看官方代码,手写代码实现lifecycle功能
  • 观察者

        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.

  • 被观察者实现类LifecycleRegistry

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

    其中我们需要关心的有三点

    • addObserver 添加观察者
    • handleLifecycleEvent(Event event) 通知观察者
    • 怎么获取Event从而调用handleLifecycleEvent。

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

  • 自定义Activity(这里不是Android四大组件)

    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) {
    
            }
        });
         lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }
    }
    

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

  1. 官方源代码分析

    我们主要从三点进行分析

    • addObserver 添加观察者
    • handleLifecycleEvent(Event event) 通知观察者
    • 怎么获取Event从而调用handleLifecycleEvent。
  • 首先看下被观察者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--;
    }
    
    

    我们的被观察着传入进来之后,首先被封装成ObserverWithState,意思是带状态的Observer,初始化的是INITIALIZED或者DESTROYED,然后放入我们的mObserverMap,管理起来。我们看下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的状态,传入进来的observer通过Lifecycling.getCallback(observer)返回了一个GenericLifecycleObserver对象,我们先看下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(估计是为了应对混淆时只混淆了子类的情况)。

    LifecycleAdapter的主要作用就是把我们写的MyLifecycle转化为我们的GenericLifecycleObserver。

    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构造方法方法,然后反射生产GeneratedAdapter对象.

    如果只有一个构造的话返回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方法,在调用onStateChanged的时候会调用GeneratedAdapter的callMethods,从而会调用MyLifecycle的方法。那么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;
            }
    

    后面会讲到怎么通知所有的观察者处理事件,我们先总结下添加及调用的过程。

    image
    • 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是我们需要关注的,看下源码

    @SuppressWarnings("WeakerAccess")
    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
    }
    
    /**
    * Lifecycle states. You can consider the states as the nodes in a graph and
    * {@link Event}s as the edges between these nodes.
    */
    @SuppressWarnings("WeakerAccess")
    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

    举个列子,假如传入的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()告诉观察者状态变了你要到STARTED,看官方图就可以知道这个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,那么dispatchEvent什么时候调用的?

  • 被观察者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呢,其实很简单,ActivityCallBacks生命周期比我们的activity的生命周期要早,也就是说ActivityCallBacks的oncreate比activity的要早,所以我们用了fragment的生命周期和我们handleLifecycleEvent相绑定。这设计的很巧妙。

    总结一下调用过程


    image
    • 清单文件注册的ProcessLifecycleOwnerInitializer这个provider在oncreate中调用了 LifecycleDispatcher.init(getContext());
    • LifecycleDispatcher中的init方法调用了((Application) context.getApplicationContext())
      .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    • DispatcherActivityCallback中的onActivityCreated中调用了
      ReportFragment.injectIfNeededIn 把(activity);
    • injectIfNeededIn 把ReportFragment的各个生命周期中调用了加入到我们activity中
    • 在ReportFragment的各个生命周期中调用了它的dispatch()调用了。
    • dispatch()调用了LifecycleRegister的handleLifecycleEvent()。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349

推荐阅读更多精彩内容