【Android Jetpack】组件之Lifecycle源码解析

前言

Android Jetpack组件之Lifecycle源码解析

基于androidx.lifecycle2.1.0组件包进行分析

一、如何使用 lifecycle

1.1、最简单的在Activity里面监听,当你的Activity的生命周期发生变化的时候会打印对应的日志

lifecycle.addObserver(object :LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        Log.d(TAG, "onCreate: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() {
        Log.d(TAG, "onStart: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        Log.d(TAG, "onResume: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        Log.d(TAG, "onPause: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {
        Log.d(TAG, "onStop: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        Log.d(TAG, "onDestroy: ")
    }
}) 

结果如下:打开其他界面然后返回

2022-04-26 19:53:36.100 31510-31510/com.cnstrong.eccard D/HtmlVersionUpdate: onPause: 
2022-04-26 19:53:36.416 31510-31510/com.cnstrong.eccard D/HtmlVersionUpdate: onStop: 
2022-04-26 19:53:39.470 31510-31510/com.cnstrong.eccard D/HtmlVersionUpdate: onStart: 
2022-04-26 19:53:39.472 31510-31510/com.cnstrong.eccard D/HtmlVersionUpdate: onResume: 

为什么Activity里面lifecycle 注册LifecycleObserver 后会监测到activity的生命周期:

猜测:内部将activity的生命周期进行分发,然后监测 LifecycleObserver 函数,找到内部的添加了不同注解的方法,通过反射进行调用

1.2、自定义一个生命周期观察者

 class ActivityLifecycleProxy : LifecycleOwner {

     var mLifecycleRegistry = LifecycleRegistry(this)

    override fun getLifecycle(): Lifecycle {
        return mLifecycleRegistry
    }

    ///处理生命周期事件
    fun handleLifeEvent(event: String?) {
        Log.e("test", "接收到的event事件:$event")
        when (event) {
            //通过自定义的“字符串”匹配,进行Lifecycle的生命周期调度
            Constant.Life.ON_CREATE -> mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
            Constant.Life.ON_START -> mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
            Constant.Life.ON_RESUME -> mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
            Constant.Life.ON_PAUSE -> mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            Constant.Life.ON_STOP -> mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
            Constant.Life.ON_DESTROY -> {
                mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            }
            Constant.Life.ON_SAVE_INSTANCE -> mLifecycleRegistry.currentState =
                Lifecycle.State.CREATED
        }
    }
}

class MyActivity:AppCompatActivity(){
    val activityLifecycleProxy :ActivityLifecycleProxy()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout.xml)
        
        //将activity的生命周期进行分发
        activityLifecycleProxy.handleLifeEvent(Constant.Life.ON_CREATE)
        
        activityLifecycleProxy.lifecycle.addObserver(object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
            fun onCreate() {
                LogUtil.d(TAG, "onCreate: ")

            }
            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            fun onResume() {
                LogUtil.d(TAG, "onResume: ")
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
            fun onDestroy() {
                LogUtil.d(TAG, "onDestroy: ")
            }
        })
    }
    
    override fun onResume() {
        super.onResume()
        activityLifecycleProxy.handleLifeEvent(Constant.Life.ON_RESUME)
    }
    
} 

这样自定义的ActivityLifecycleProxy类也有了观察MyActivity的生命周期的能力

1.3、通过自定义的ActivityLifecycleProxy 过程 分析Activity为什么也有这个能力

1.3.1、分析

lifecycle对象是属于LifecycleOwner对象的如下:

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
} 

那为什么Activity能够拿到该对象,那肯定是当前的Activity实现的LifecycleOwner接口类

1.
BaseViewBindActivity<VB : ViewDataBinding> : AppCompatActivity()
2.
public class AppCompatActivity extends FragmentActivity implements AppCompatCallback,
        TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider
3.        
public class FragmentActivity extends ComponentActivity implements
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator 
4.        
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner 

看上面第四点发现ComponentActivity实现了 LifecycleOwner接口

看ComponentActivity类的getLifecycle()方法如下:

 ...
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

    @CallSuper
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Lifecycle lifecycle = getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
        }
        super.onSaveInstanceState(outState);
        mSavedStateRegistryController.performSave(outState);
    }



/**
Returns the Lifecycle of the provider.
Overriding this method is no longer supported and this method will be made final in a future version of ComponentActivity. If you do override this method, you must:
Return an instance of LifecycleRegistry
Lazily initialize your LifecycleRegistry object when this is first called. Note that this method will be called in the super classes' constructor, before any field initialization or object state creation is complete.
翻译:
返回提供程序的生命周期。
不再支持重写这个方法,这个方法将在未来的ComponentActivity版本中成为final。如果你重写了这个方法,你必须:
返回一个lifecyclerregistry实例
当它第一次被调用时惰性地初始化你的lifecyclereregistry对象。注意,这个方法将在父类的构造函数中调用,在任何字段初始化或对象状态创建完成之前。
**/
...
@NonNull
@Override
public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}
... 

看到ComponentActivity实现了接口LifecycleOwner,并在getLifecycle()返回了LifecycleRegistry实例。前面提到LifecycleRegistry是Lifecycle具体实现。

然后在onSaveInstanceState()中设置mLifecycleRegistry的状态为State.CREATED,然后怎么没有了?其他生命周期方法内咋没处理?what?和猜测的不一样啊。 别急,在onCreate()中有这么一行:ReportFragment.injectIfNeededIn(this),这个就是关键所在。从方法名可以看出注入了一个Fragment,熟悉Glide的朋友肯定知道这个套路了。添加一个透明的Fragment,用它来感知宿主Activity的生命周期,然后进行转发。

1.3.2、下面看:ReportFragment

**下面主要分为两种:**他们走的都是dispatch(activity, ...);方法

  • api29以上-- activity.registerActivityLifecycleCallbacks( new LifecycleCallbacks()); 看下面的 LifecycleCallbacks类,进行生命周期分发
  • api29以下---根据这个透明的fragment的生命周期进行分发

ReportFragment类中的 dispatch方法如下:

根据条件判断我们走的是下面第2点 LifecycleRegistry类的handleLifecycleEvent(event)方法

@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }
    //2.我们的lifecycle走的是这个方法
    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
} 

ReportFragment整个类代码如下:

public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        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();
        }
    }

    @SuppressWarnings("deprecation")
    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        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);
            }
        }
    }

    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(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            // Only dispatch events from ReportFragment on API levels prior
            // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
            // added in ReportFragment.injectIfNeededIn
            dispatch(getActivity(), event);
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }

    // this class isn't inlined only because we need to add a proguard rule for it. (b/142778206)
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity,
                @Nullable Bundle bundle) {
        }

        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostStarted(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_START);
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPostResumed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_RESUME);
        }

        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
        }

        @Override
        public void onActivityPreStopped(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity,
                @NonNull Bundle bundle) {
        }

        @Override
        public void onActivityPreDestroyed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_DESTROY);
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }
} 

二、分析LifecycleRegistry类的handleLifecycleEvent(event)方法

/**
Sets the current state and notifies the observers.
Note that if the currentState is the same state as the last call to this method, calling this method has no effect.
Params:
event – The event that was received
解释:
设置当前状态并通知观察者。
注意,如果currentState的状态与对该方法的最后一次调用相同,则调用该方法没有效果。
参数:event -接收到的事件
**/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
} 

上面主要是进行生命周期的比较与分发

2.1、我们根据Lifecycle的addObserver方法来进行分析,LifecycleRegistry的addObserver方法如下:

override fun onCreate(savedInstanceState: Bundle?) {

val myLifecycleObserver = object :LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        Log.d(TAG, "onCreate: ")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        Log.d(TAG, "onDestroy: ")
    }
}
lifecycle.addObserver(myLifecycleObserver)

}
  
  
  override fun onStart() {
    super.onStart()
  } 
@Override
public void addObserver(@NonNull LifecycleObserver observer) {//这里的 observer对象可以认为是上面我们监测的myLifecycleObserver
    
    //1.刚开始mState的初始值在构造函数中设置为INITIALIZED
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    
    //2.ObserverWithState是对observer对象的一个包装类,将状态与事件类结合,在其构造方法内,又创建了一个LifecycleEventObserver类型的观察者对象,它是一个接口,它继承自LifecycleObserver,在这里返回的实现类是ReflectiveGenericLifecycleObserver。
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    
    //3.将我们的观察者作为key,包装对象ObserverWithState作为value,将其保存到一个Map中,并且在Map中的value还被维护成了一个双向链表。
    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;
    
    //4.注释4
    State targetState = calculateTargetState(observer);
    mAddingObserverCounter++;
    
    //注释5:看完注释4,我们知道首次注册的时候targetState = INITIALIZED,statefulObserver.mState也 = INITIALIZED(这个要看注释3的map的put过程)
    //所以比较compareTo的返回值,前面大于后面大于0,相等=0,前面小于后面 小于0,所以首次注册该方法不会调用
    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);
    }
    
    //注释6:isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
    //刚开始mHandlingEvent的默认值为false,所以下面必定成立
    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
} 

解释:

  • 注释1://1.刚开始mState的初始值在构造函数中设置为INITIALIZED

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    } 
    
  • 注释2:

    ObserverWithState是对observer对象的一个包装类,将状态与事件类结合,在其构造方法内,又创建了一个LifecycleEventObserver类型的观察者对象,它是一个接口,它继承自LifecycleObserver,在这里返回的实现类是ReflectiveGenericLifecycleObserver。

    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;
    
        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);//返回ReflectiveGenericLifecycleObserver对象
            mState = initialState;
        }
    
        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    } 
    
  • 注释3: ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    //主要是记录上一次的State状态,在isSynced()方法中进行比较,决定生命周期变更后是否需要发送监测回调

    将我们的观察者作为key,包装对象ObserverWithState作为value,将其保存到一个Map中,并且在Map中的value还被维护成了一个双向链表。

    @Override
    public V putIfAbsent(@NonNull K key, @NonNull V v) {
        Entry<K, V> current = get(key);
        if (current != null) {
            return current.mValue;
        }
        mHashMap.put(key, put(key, v));//再看put方法
        return null;
    }
    
    
    protected Entry<K, V> put(@NonNull K key, @NonNull V v) {
            Entry<K, V> newEntry = new Entry<>(key, v);
            mSize++;
            if (mEnd == null) {
                mStart = newEntry;
                mEnd = mStart;
                return newEntry;
            }
    
            mEnd.mNext = newEntry;
            newEntry.mPrevious = mEnd;
            mEnd = newEntry;
            return newEntry;
    } 
    
  • 注释4:

    计算我们的观察者对象的 mState。这里的previous为包含我们的观察者对象的Entry节点的前驱节点,它不为空且它的StateINITIALIZEDmParentStates的size为空,所以在return语句中内层min方法返回的是INITIALIZED,而外层min方法返回还是INITIALIZED

    **注意:**下面的mState(这个就是ObserverWithState的State,与LifecycleRegistry的 mState,虽然类型一致但是值有个先后关系的过程,这就涉及到生命周期的同步分发流程,他就是通过mObserverMap与LifecycleRegistry的 mState进行区分)

    private State calculateTargetState(LifecycleObserver observer) {
      
      //previous这个的值其实就是我们的myLifecycleObserver的对象,包装的ObserverWithState对象,具体看它的值,看上面注释3出
        Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
    
        State siblingState = previous != null ? previous.getValue().mState : null;
        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
                : null;
        return min(min(mState, siblingState), parentState);
    } 
    
  • 注释5:

    看完注释4,我们知道首次注册的时候targetState = INITIALIZED,statefulObserver.mState也 = INITIALIZED(这个要看注释3的map的put过程) 所以比较compareTo的返回值,前面大于后面结果值要大于0,相等=0,前面小于后面 小于0,所以首次注册该方法不会调用

 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);
    } 
  • 注释6:

    //isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; //刚开始mHandlingEvent的默认值为false,所以下面必定成立

    ... boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; ... //注释6:isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; //刚开始mHandlingEvent的默认值为false,所以下面必定成立 if (!isReentrance) { // we do sync only on the top level. sync(); }

2.2、下面看sync方法

// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                + "garbage collected. It is too late to change lifecycle state.");
    }
    //首次addObserver()的过程该方法不会执行
    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;
} 

先看看进入while循环的条件判断方法isSynced()方法mObserverMap.eldest()为双向链表的头节点,它的mStateINITIALIZEDmObserverMap.newest()为双向链表的尾节点,也就是我们的观察地者对象,它的mState也是为INITIALIZED。而LifecycleRegistrymSate初始值也是INITIALIZED,所以整个方法返回值为true,while循环体不会执行。

到这里,我们的Activity的addObserver方法分析完成。接下来就是执行前面提到的ReportFragment的生命周期分发的handleLifecycleEvent方法

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

[图片上传失败...(image-3a3c1f-1689062740616)]

2.3、上面分析流程切换由onCreate切换到onStart()方法

我们从前面的1.3知道,activity生命周期切换会触发LifecycleRegistry 的 handleLifecycleEvent 方法

//1.
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}
//2.onStart() 方法 发送的是 ON_START ,所以next = STARTED
 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);
    }
    
    //3.前面走了oncreate方法mState =处于CREATED,因为不相等所以, mState被赋值为了STARTED
     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;
    } 

由上面几个注释得出又到了sync()方法

private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                + "garbage collected. It is too late to change lifecycle state.");
    }
    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;
}


private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    } 

isSynced()方法这次返回的是false,为什么呢mObserverMap.eldest().getValue().mState的值为CREATED 状态,而 mState为STARTED

mObserverMap.eldest().getValue().mState其实你可以认为它是一个缓存缓存上一次的状态,它会在, 符合条件的情况下backwardPass(lifecycleOwner);方法或者 forwardPass(lifecycleOwner)中进行记录

因为:mObserverMap.eldest().getValue().mState的值为CREATED 状态,而 mState为STARTED 所以走的 forwardPass(lifecycleOwner);方法

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);
            
            //1.拿到上次的缓存 mObserverMap中的值observer.mState为CREATED 看upEvent(observer.mState)方法
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
            popParentState();
        }
    }
}

//2.返回 ON_START,再看  observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
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);
    }
    
    
   //3.ObserverWithState 类中的
   void dispatchEvent(LifecycleOwner owner, Event event) {
            //根据event ,第二点传入的值,获取状态
            State newState = getStateAfter(event);
            //`得出最小的状态进行记录,后续activity的状态变更后,拿到的状态又要在 isSynced() 方法里面进行比对才决定是否需要同步`
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

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

到这里状态切换变更结束了,后面是状态变更后如何通知对应的观察者

三、分析ObserverWithState,就是addObserver(@NonNull LifecycleObserver observer)方法中的observer的包装类,在这个类里面进行事件分发

static class ObserverWithState {
    State mState;
    LifecycleEventObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //主要在这个构造器里面进行注册
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        
        //状态变更,通过onStateChanged方法进行,通知
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
} 

3.1、Lifecycling.lifecycleEventObserver(observer)方法的注册

它在Lifecycling类中的 lifecycleEventObserver(Object object) 方法的object,就是我们在2.1中的例子LifecycleObserver的对象

所以经过一系列判断知道走的是ReflectiveGenericLifecycleObserver(object)对象实例

@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }

    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) 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);
} 

3.2、ReflectiveGenericLifecycleObserver类

class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        //走这里
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
} 
、、1.
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());

、、2.
 CallbackInfo getInfo(Class<?> klass) {
        CallbackInfo existing = mCallbackMap.get(klass);
        if (existing != null) {
            return existing;
        }
        、、3.
        existing = createInfo(klass, null);
        return existing;
    }
3.、、
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
        Class<?> superclass = klass.getSuperclass();
        Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
        if (superclass != null) {
            CallbackInfo superInfo = getInfo(superclass);
            if (superInfo != null) {
                handlerToEvent.putAll(superInfo.mHandlerToEvent);
            }
        }

        Class<?>[] interfaces = klass.getInterfaces();
        for (Class<?> intrfc : interfaces) {
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        
        、、获取OnLifecycleEvent注解的方法,存储起来
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            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();

            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
                if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. second arg must be an event");
                }
                if (event != Lifecycle.Event.ON_ANY) {
                    throw new IllegalArgumentException(
                            "Second arg is supported only for ON_ANY value");
                }
            }
            if (params.length > 2) {
                throw new IllegalArgumentException("cannot have more than 2 params");
            }
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        、、存储需要返回的事件,构造CallbackInfo类
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    } 

3.3、 CallbackInfo 最后的分发类

static class CallbackInfo {
    final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
    final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;

    //分发事件的存储
    CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
        mHandlerToEvent = handlerToEvent;
        mEventToHandlers = new HashMap<>();
        for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
            Lifecycle.Event event = entry.getValue();
            List<MethodReference> methodReferences = mEventToHandlers.get(event);
            if (methodReferences == null) {
                methodReferences = new ArrayList<>();
                mEventToHandlers.put(event, methodReferences);
            }
            methodReferences.add(entry.getKey());
        }
    }

    //,具体的反射,调用被 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)注解标记的方法
    @SuppressWarnings("ConstantConditions")
    void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
        invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
        invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                target);
    }

    private static void invokeMethodsForEvent(List<MethodReference> 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);
            }
        }
    }
} 
@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) {
        //noinspection TryWithIdenticalCatches
        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);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MethodReference that = (MethodReference) o;
        return mCallType == that.mCallType && mMethod.getName().equals(that.mMethod.getName());
    }

    @Override
    public int hashCode() {
        return 31 * mCallType + mMethod.getName().hashCode();
    }
} 

到了这里整个事件结束,当activity的生命周期进行变更,然后调用handleLifecycleEvent(@NonNull Lifecycle.Event event) -->ObserverWithState 类的mLifecycleObserver.onStateChanged(owner, event);-->ReflectiveGenericLifecycleObserver类的onStateChanged分发-->`MethodReference类的invokeCallback方法反射调用被注解标记的方法

最后

如果你进阶的路上缺乏方向,

需要更多的Android 可以查看我的个人介绍!!!

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

推荐阅读更多精彩内容