关于android:Android-官方架构组件一Lifecycle

45次阅读

共计 25803 个字符,预计需要花费 65 分钟才能阅读完成。

什么是 Lifecycle?

Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,能够让开发者构建能感知其余组件(次要指 Activity、Fragment)生命周期(lifecycle-aware)的类。

为什么要引进 Lifecycle?

后面说了,Lifecycle 可能让开发者构建能感知其余组件(次要指 Activity、Fragment)生命周期(lifecycle-aware)的类。划重点,让开发者构建能感知其余组件(次要指 Activity、Fragment)生命周期(lifecycle-aware)的类。在 android 开发的过程中,咱们经常须要让一些操作可能感知 Activity/Fragment 的生命周期,从而实现在活动状态下容许操作,而在销毁状态下须要主动禁止操作,开释资源,避免内存泄露。例如赫赫有名的图片加载框架 Glide 在 Acticiy/Fragment 处于前台的时候加载图片,而在不可见的状态下进行图片的加载,又例如咱们心愿 RxJava 的 Disposable 可能在 Activity/Fragment 销毁是主动 dispose。Lifecycle 的呈现,让开发者们可能轻易地实现上述的性能。

一个用 Lifecycle 革新的 MVP 例子

比方咱们当初须要实现这样一个性能:监听某个 Activity 生命周期的变动,在生命周期扭转的时候打印日志。

  • 个别做法结构回调的形式

先定义根底 IPresent 接口:

public interface IPresent {void onCreate();
    void onStart();
    void onResume();
    void onPause();
    void onStop();
    void onDestory();}

而后在自定义的 Present 中继承 IPresent 接口:

public class MyPresent implements IPresent {

    private String TAG = "tag";

    @Override
    public void onCreate() {LogUtil.i(TAG, "onCreate");
    }

    @Override
    public void onStart() {LogUtil.i(TAG, "onStart");
    }

    @Override
    public void onResume() {LogUtil.i(TAG, "onResume");
    }

    @Override
    public void onPause() {LogUtil.i(TAG, "onPause");
    }

    @Override
    public void onStop() {LogUtil.i(TAG, "onStop");
    }

    @Override
    public void onDestory() {LogUtil.i(TAG, "onDestory");
    }

最初在 Activity 顺次调用回调办法散发事件:

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {super.onCreate(savedInstanceState, persistentState);
        myPresent = new MyPresent();
        myPresent.onCreate();}

    @Override
    protected void onStart() {super.onStart();
        myPresent.onStart();}

    @Override
    protected void onResume() {super.onResume();
        myPresent.onResume();}

    @Override
    protected void onPause() {super.onPause();
        myPresent.onPause();}

    @Override
    protected void onStop() {super.onStop();
        myPresent.onStop();}

    @Override
    protected void onDestroy() {super.onDestroy();
        myPresent.onDestory();}
}

通过这么一个简略的例子,咱们能够看出,实现流程尽管很简略,然而代码实现繁琐,不够灵便,且代码侵入性太强。该例子只是展现了 Present 监听 Activity 生命周期,如果说还有类 1,类 2,类 3 …… 想要监听 Activity 的生命周期,那么就要在 Activity 的回调中增加对类 1,类 2,类 3 ….. 的回调。这就引起了一个思考,咱们是否可能实现 Activity 在生命周期发生变化时被动告诉需求方的性能呢?能够的,答案就是 Lifecycle。

  • Lifecycle 实现 Present

先实现 MyPresent,同时在每一个办法实现上减少 @OnLifecycleEvent(Lifecycle.Event.XXXX)注解,OnLifecycleEvent 对应了 Activity 的生命周期办法:

public class MyPresent implements IPresent, LifecycleObserver {@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void onCreate() {LogUtil.i(TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    @Override
    public void onStart() {LogUtil.i(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume() {LogUtil.i(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    @Override
    public void onPause() {LogUtil.i(TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    @Override
    public void onStop() {LogUtil.i(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void onDestory() {LogUtil.i(TAG, "onDestory");
    }
}

而后在须要监听的 Activity 中注册:

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {super.onCreate(savedInstanceState, persistentState);
        
        getLifecycle().addObserver(new MyPresent()); // 增加监听对象
    }

}

运行如下:

com.cimu.lifecycle I/MyPresent : onCreate()
com.cimu.lifecycle I/MyPresent : onStart()
com.cimu.lifecycle I/MyPresent : onResume()
com.cimu.lifecycle I/MyPresent : onPause()
com.cimu.lifecycle I/MyPresent : onStop()
com.cimu.lifecycle I/MyPresent : onDestroy()

是不是很简略,咱们心愿 MyPresent 感知监听 Activity 的生命周期,只须要在 Activity 中调用一句 getLifecycle().addObserver(new MyPresent())就能够了。Lifecycle 是怎么实现感知生命周期进而告诉观察者的性能的呢?

Lifecycle 源码剖析

首先须要晓得三个要害的货色:

  • LifecycleOwner:生命周期的事件分发者,在 Activity/Fragment 他们的生命周期发生变化的时收回相应的 Event 给 LifecycleRegistry。
  • LifecycleObserver:生命周期的观察者,通过注解将处理函数与心愿监听的 Event 绑定, 当相应的 Event 产生时,LifecycleRegistry 会告诉相应的函数进行解决。
  • LifecycleRegistry:控制中心。它负责管制 state 的转换、承受散发 event 事件。

LifeCycle 的源码剖析,咱们分为两个步骤来剖析:

  • 注册 / 登记监听流程
  • * 生命周期 散发流程 *

注册 / 登记监听流程源码剖析

从下面的 MVP 例子,咱们曾经晓得,注册只须要调用 getLifecycle().addObserver(observer)即可,那么 addObserver 就能够作为源码剖析的入口。

通过追踪,咱们发现 getLifecycle 返回的是 SupportActivity 中的 mLifecycleRegistry,类型为 LifecycleRegistry:

public class SupportActivity extends Activity implements LifecycleOwner {

    ......

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
                                                             = new FastSafeIterableMap<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    ......

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

    ......
}

那么 addObserver 实际上是调用了 LifecycleRegistry 的 addObserver 办法,咱们来看一下这个办法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

    // 将传进来的监听者 observer 封装成一个 ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    // 将封装好的 ObserverWithState 存入汇合中
    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();
        // 咱们 dispatch 了一个事件给观察者,在回调观察者代码的时候,观察者可能会
        // 批改咱们的状态
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        // we do sync only on the top level.
        sync();}
    mAddingObserverCounter--;
}

对于注册流程,下面咱们重点关注封装了 observer 的 ObserverWithState:

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {//getCallback()通过不同的类型的 observer 返回不同 GenericLifecycleObserver 实现类
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    // 生命周期 event 的散发,最终会调用到这个办法,这个办法中在调用了 GenericLifecycleObserver 的
    // 的 onStateChanged 办法
    void dispatchEvent(LifecycleOwner owner, Event event) {State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}
public interface GenericLifecycleObserver extends LifecycleObserver {void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

ObserverWithState 的构造方法调用了 Lifecycling.getCallback()将传入的 observer 进行解析,生成了对接口类 GenericLifecycleObserver 的具体实现返回,并且在具体实现类中重写了 onStateChanged 办法,在 onStateChanged 实现了生命周期的散发。当 Activity/Fragment 的生命周期发生变化时,会遍历 LifecycleRegistry 中的 mObserverMap 汇合,取出其中的 ObserverWithState 节点,调用它的 onStateChanged 办法,而在 ObserverWithState 的 onStateChanged 的办法中又调用了实现了具体生命周期散发的 GenericLifecycleObserver.onStateChanged 办法。

在剖析 Lifecycling.getCallback()办法之前,咱们先来看一下 Lifecycle 应用的三种根本应用形式:

  • 第一种应用形式。应用 @onLifecycleEvent 注解。注解处理器会将该注解解析并动静生成 GeneratedAdapter 代码,这个 GeneratedAdapter 会把对应的 Lifecycle.Event 封装为办法调用。最终通过 GenericLifecycleObserver 的 onStateChanged 办法调用生成的GeneratedAdapter 的 callMechods 办法进行事件散发(联合上面例子了解)
public class MyLifeCycleObserver implements LifeCycleObserver {@onLifecycleEvent(LifeCycle.Event.ON_CREATE)
    public onCreate(LifeCycleOwner owner) {//doSomething}
    
    @onLifecycleEvent(LifeCycle.Event.ON_DESTROY)
    public onDestroy(LifeCycleOwner owner) {//doSomething}
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}

上述的例子中的 MyLifeCycleObserver 将会在编译时,生成 GeneratedAdapter 代码如下:

public class MyLifeCycleObserver_LifecycleAdapter implements GeneratedAdapter {

    final MyLifeCycleObserver mReceiver;

    MyLifeCycleObserver_LifecycleAdapter(MyLifeCycleObserver receiver) {
        //mReceiver 就是咱们开发者传入的 MyLifeCycleObserver 
        this.mReceiver = receiver;
    }

    //callMechod 办法会被 GenericLifecycleObserver 的 onStateChanged 办法调用,用以散发生命周期
    @Override
    public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {return;}

        // 如果生命周期事件是 ON_CREATE,那么调用 MyLifeCycleObserver 的 onCreate 办法
        if (event == Lifecycle.Event.ON_CREATE) {if (!hasLogger || logger.approveCall("onCreate", 2)) {mReceiver.onCreate(owner);
            }
            return;
        }

        // 如果生命周期事件是 ON_DESTROY,那么调用 MyLifeCycleObserver 的 onDestroy 办法
        if (event == Lifecycle.Event.ON_DESTROY) {if (!hasLogger || logger.approveCall("onDestroy", 2)) {mReceiver.onDestroy(owner);
            }
            return;
        }
    }
}
  • 第二种应用形式。间接继承 GenericLifecycleObserver,并实现 onStateChange 办法
public class MyLifeCycleObserver extends GenericLifeCycleObserver {
    
    @override
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {if(event == LifeCycleEvent.Event.ON_CREATE) {//dosomething} else if(event == LifeCycleEvent.Event.ON_DESTROY) {//doSomething}    
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
  • 第三种应用形式。继承 DefaultLifecycleObserver 接口(DefaultLifecycleObserver 又继承自 FullLifecycleObserver 接口),并实现FullLifecycleObserver 接口的onCreate、onStart、onResume、onPause、onStop、onDestroy 等对应各自生命周期的办法
class MyLifycycleObserver implements DefaultLifecycleObserver {

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {//doSomething}

    ......

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {//doSomething}
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}

下面咱们学习了应用 Lifecycle 的三种根本办法,上面咱们简略看看 Lifecycling.getCallback()办法是如何生成 GenericLifecycleObserver 具体实现类返回的:

// 首先,咱们先相熟一下 resolveObserverCallbackType 这个办法,这个办法在 Lifecycling.getCallback()
// 中被调用,getCallback 中会依据它的返回值决定返回什么类型的 GenericLifecycleObserver 实现类
private static int resolveObserverCallbackType(Class<?> klass) {if (klass.getCanonicalName() == null) {return REFLECTIVE_CALLBACK;}
    
    // 当应用第一种形式注解时,会主动生成代码,生成的 adapter 继承了 GeneratedAdapter,// 所以返回值是 GENERATED_CALLBACK
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }

    //hasLifecycleMethods 办法是判断 klass 中是否蕴含了 onLifecycleEvent.class 注解
    // 如果蕴含,返回 REFLECTIVE_CALLBACK
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
    if (hasLifecycleMethods) {return REFLECTIVE_CALLBACK;}

    // 递归调用 resolveObserverCallbackType 办法,遍历 klass 的父类
    Class<?> superclass = klass.getSuperclass();
    List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
    if (isLifecycleParent(superclass)) {if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {return REFLECTIVE_CALLBACK;}
        adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
    }

    // 遍历并且递归 kclass 的接口
    for (Class<?> intrface : klass.getInterfaces()) {if (!isLifecycleParent(intrface)) {continue;}
        if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {return REFLECTIVE_CALLBACK;}
        if (adapterConstructors == null) {adapterConstructors = new ArrayList<>();
        }
        adapterConstructors.addAll(sClassToAdapters.get(intrface));
    }
    if (adapterConstructors != null) {sClassToAdapters.put(klass, adapterConstructors);
        return GENERATED_CALLBACK;
    }

    return REFLECTIVE_CALLBACK;
}
//getCallBack 的参数 object 是咱们 getLifeCycle().addObserver(observer)时传入的监听者 observer
static GenericLifecycleObserver getCallback(Object object) {if (object instanceof FullLifecycleObserver) {
       // 第三种应用形式,因为 DefaultLifecycleObserver 继承与 FullLifecycleObserver
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        // 第二种应用形式,当咱们应用间接继承 GenericLifecycleObserver 这种办法时,间接返回
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    // 第一种应用形式,当应用注解时,getObserverConstructorType 的返回值是 GENERATED_CALLBACK
    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);
    }

    // 当 oberver 都不合乎下面几种类型时,会间接实例化 ReflectiveGenericLifecycleObserver
    // 作为代替返回(个别状况下,是不会走到这里的,可能是为了应答混同机制而做的的一种平安模式)// 在 ReflectiveGenericLifecycleObserver 中会找 oberver 中的 onLifecyleEvent 注解,并且将这些带注解
    // 的办法生成 MethodReference 并增加到 List<MethodReference> 中,作为生命周期散发的调用办法
    return new ReflectiveGenericLifecycleObserver(object);
}

好了,Lifecycling.getCallback()如果真的要具体的剖析,篇幅会很大,在这里,咱们粗略的剖析了下。大家如果想深刻理解,本人联合源码看是最好不过的。

总结一下注册的流程:

  1. Acitivty 中调用 LifecycleRegistry 的 addObserver,传入一个 LifecycleObserver
  2. 传入的 LifecycleObserver 被封装成一个 ObserverWithState 存入汇合中,当生命周期产生扭转的时候,就会遍历这个 ObserverWithState 汇合,并且调用 ObserverWithState 的 dispatchEvent 进行散发
  3. 在 ObserverWithState 构造方法中,调用了 Lifecycling.getCallback(observer)生成了具体的 GenericLifecycleObserver 对象返回。在 ObserverWithState 的 dispatchEvent()办法中调用了 GenericLifecycleObserver 对象的 onStateChanged 办法进行事件散发

至于登记流程就很简略了,间接将 observer 从汇合中 remove,代码如下:

@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    // we consciously decided not to send destruction events here in opposition to addObserver.
    // Our reasons for that:
    // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
    // actually occurred but earlier.
    // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
    // event. If removeObserver method sends destruction events, then a clean up routine becomes
    // more cumbersome. More specific example of that is: your LifecycleObserver listens for
    // a web connection, in the usual routine in OnStop method you report to a server that a
    // session has just ended and you close the connection. Now let's assume now that you
    // lost an internet and as a result you removed this observer. If you get destruction
    // events in removeObserver, you should have a special case in your onStop method that
    // checks if your web connection died and you shouldn't try to report anything to a server.
    mObserverMap.remove(observer);
}

生命周期的散发流程

咱们注册 observer 的时候,实际上是调用了 SupportActivity 中的 mLifecycleRegistry 对象的办法,那么咱们剖析下 SupportActivity 的 onCreate 办法:

@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}

在 onCreate 中调用了 ReportFragment 的 injectIfNeedIn 办法。这个办法其实就是往 Activity 中增加了一个 Fragment。咱们晓得,Fragment 是依附于 Activity 上的,Fragment 的生命周期追随 Activity 的生命周期。既然这个 ReportFragment 可能感知 Activity 的生命周期,那么它是不是就是负责将生命周期事件分发给 LifecycleObserver 的呢?

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

ReportFragment 的代码很好了解,咱们可能在代码外面发现 Lifecycle.Event.xxx 事件,并且在它的生命周期回调办法中将 Lifecycle.Event.xxx 事件传给了 dispatch 办法,很显著是用来散发生命周期的。在 ReportFragment 的 dispatch 办法中,调用了 LifecycleRegistry 的 handleLifecycleEvent 办法:

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

在剖析这个办法之前,咱们先要理解 Lifecycle 的事件与状态:

public abstract class Lifecycle {

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

Lifecycle.Event 对应 activity 的各个申明周期,Lifecycle.State 则是 Lifecycle 的状态。在 LifecycleRegistry 中定义了状态间的转化关系:

public class LifecycleRegistry extends Lifecycle {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 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);
    }

    private static Event upEvent(State state) {switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();}
        throw new IllegalArgumentException("Unexpected state value" + state);
    }
}

这三个办法,能够总结为上面这样一张图:

downEvent 在图中示意从一个状态到他上面的那个状态,upEvent 则是往上。

理解了 Lifecycle 的状态后,咱们持续来看 LifecycleRegistry。下面咱们晓得,当 Activity 的生命周期发生变化后,ReportFragment 会感知到,从而会调用到 dispatch 办法,最终调用到 LifecycleRegistry 的 handleLifecycleEvent 办法:

public class LifecycleRegistry extends Lifecycle {

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;

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

    private void moveToState(State next) {if (mState == next) {return;}
        mState = next;
        // 当咱们在 LifecycleRegistry 回调 LifecycleObserver 的时候触发状态变动时,// mHandlingEvent 为 true;// 增加 observer 的时候,也可能会执行回调办法,这时候如果触发了状态变动,// 则 mAddingObserverCounter != 0
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // 不须要执行 sync。// 执行到这里的状况是:sync() -> LifecycleObserver -> moveToState()
            // 这里间接返回后,还是会回到 sync(),而后持续同步状态给 observer
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // sync() 会把状态的变动转化为生命周期事件,而后转发给 LifecycleObserver
        sync();
        mHandlingEvent = false;
    }
}

LifecycleRegistry 原本要做的事其实是很简略的,但因为他须要执行客户的代码,由此引入了很多额定的复杂度。起因是,客户代码并不处在咱们的管制之下,他们可能做出任何能够做到的事。例如这里,在回调中又触发状态变动。相似的状况是,在持有锁的时候不调用客户代码,这个也会让实现变得比较复杂。

接下来咱们看 sync():

public class LifecycleRegistry extends Lifecycle {

    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * 这个 Invariant 十分重要,他会影响到 sync() 的逻辑
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

    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 是为了在 observer 触发状态变动时让 backwardPass/forwardPass()
            // 提前返回用的。咱们刚筹备调他们,这里设置为 false 即可。mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大
                // 如果 mState 小于队列里最大的那个,阐明有元素须要更新状态
                // 为了维持 mObserverMap 的 Invariant,这里咱们须要从队尾往前更新元素的状态
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 如果 mNewEventOccurred,阐明在下面调用 backwardPass() 时,客户触发了状态批改
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    // 判断是否须要同步,如果所有的 observer 的状态都曾经同步完,返回 true,否则返回 false
    private boolean isSynced() {if (mObserverMap.size() == 0) {return true;}
        //eldestObserverState 是最早增加的 observer,newestObserverState 是最新增加的 observer
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        // 因为咱们保障队头的 state >= 前面的元素的 state,所以只有判断头尾就够了
        // 如果最新的和最老的 Observer 的状态不统一或者以后的状态和最新的状态不统一时,那么须要进行状态同步
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

}

sync() 的次要作用就是依据把 mObserverMap 里所有元素的状态都同步为 mState。咱们持续看剩下的 backwardPass/forwardPass:

public class LifecycleRegistry extends Lifecycle {

    // 这段正文应该是这整个类外面最难了解的了吧,至多对于我来说是这样
    // we have to keep it for cases:
    // void onStart() {//     // removeObserver(this),阐明 this 是一个 LifecycleObserver
    //     // 所以这里说的是,咱们在回调里执行了上面两个操作
    //     mRegistry.removeObserver(this);
    //     mRegistry.add(newObserver);
    // }
    // 假设当初咱们要从 CREATED 转到 STARTED 状态(也就是说,mState 当初是 STARTED)。// 这种状况下,只有将新的 observer 设置为 CREATED 状态,它的 onStart 才会被调用
    // 为了失去这个 CREATED,在这里才引入了 mParentStates。在 forwardPass 中执行
    // pushParentState(observer.mState) 时,observer.mState 就是咱们须要的 CREATED。// backwardPass 的状况相似。// newObserver should be brought only to CREATED state during the execution of
    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
    // is no longer in the map.
    private ArrayList<State> mParentStates = new ArrayList<>();

    // 第一个 while 循坏遍历咱们存储观察者的汇合,
    // 第二个是要解决各个状态通过的 event
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        // 从队头开始迭代
        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
                    // 可能在回调客户代码的时候,客户把本人移除了
                    && mObserverMap.contains(entry.getKey()))) {pushParentState(observer.mState);
                //upEvent 返回所要经验的 event
                // 例如:以后是 STARTED , 那么他的通过的 events 就是 ON_RESUME
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();}
        }
    }

    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()))) {Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();}
        }
    }

    private void popParentState() {mParentStates.remove(mParentStates.size() - 1);
    }

    private void pushParentState(State state) {mParentStates.add(state);
    }
}

提醒:在看这 forwardPass 以及 backwardPass 这两个办法时,参考下面的状态转换图

  1. 假如以后汇合中所有 ObserverWithState 元素都处于 CREATED 状态。此时接着收到了一个 ON_START 事件,从图能够看出,接下来应该是要转换到 STARTED 状态。因为 STARTED 大于 CREATED,所以会执行forwardPass 办法。forwardPass里调用 upEvent(observer.mState),返回从 CREATED 往上到 STARTED 须要发送的事件,也就是 ON_START,于是ON_START 事件发送给了观察者。
  2. 假如以后 LifecycleRegistrymState 处于 RESUMED 状态。而后调用 addObserver 办法新增加一个 LifecycleObserver,该 observer 会被封装成ObserverWithState 存进汇合中,此时这个新的 ObserverWithState 处于 INITIALIZED 状态,因为 RESUMED 大于 INITIALIZED,所以会 执行 forwardPass 办法。ObserverWithState 状态会依照 **INITIALIZED -> CREATED -> STARTED -> RESUMED** 这样的程序变迁。

总结

一些集体疑难:

  • 疑点 1:为什么不间接在 SupportActivity 的生命周期函数中给 Lifecycle 散发生命周期事件,而是要加一个 Fragment 呢?

因为不是所有的页面都继承 AppCompatActivity,为了兼容非 AppCompatActivity,所以封装一个同样具备生命周期的 Fragment 来给 Lifecycle 散发生命周期事件。显然 Fragment 侵入性低。

  • 疑点 2:为什么用 ReportFragment 散发生命周期而不间接应用 ActivityLifecycleCallbacks 的回调来解决 Lifecycle 生命周期的变动?

因为 ActivityLifecycleCallbacks 的回调比 Fragment 和 Activity 还要早,实际上未真正执行对应的生命周期办法

Lifecycle 的剖析咱们在这里就到此为止了,最初附上幅流程图,帮忙了解并记忆:

正文完
 0