jetpack之Lifecycle的源码解读

源码版本:Android 10

一、Lifecycle基本使用方法

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
    	//源码分析入口:1
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //源码分析入口:2  给当前Activity添加观察者
        lifecycle.addObserver(MainActivityLifeObserver())
        tv_exit.setOnClickListener {
            finish()
        }
    }
}
class MainActivityLifeObserver : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
        Log.e("Observer==", "OnCreate方法调用了")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        Log.e("Observer==", "OnDestroy被调用了")
    }
}

二、Lifecycle源码分析

如下是谷歌官方网站绘制的Lifecycle对象状态转换图
jetpack之Lifecycle的源码解读_第1张图片

2.1 源码入口1

点击super.onCreate方法,往上一直找到ComponentActivity。CompontActvity的onCreate方法源码如下:
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //实现Activity生命周期监听的核心类,通过在Activity上面添加一个空白的没有任何UI的Fragment来监控
    //Activity的生命周期
     ReportFragment.injectIfNeededIn(this);
 }

接下来看 ReportFragment.injectIfNeededIn(this)主要干了什么,其源码如下所示:

public static void injectIfNeededIn(Activity activity) {     
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
        //给当前activity添加一个ReportFragment
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

2.2 源码入口2

点击addObserver方法找到其实现类LifecycleRegistry,LifecycleRegistry中addObserver源码如下所示:
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        //初始化observer的初始状态
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //对传入的observer和它的状态进行封装
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //将oberver和其封装类装入mObserverMap中,其底层是借助HashMap实现的
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        //最开始添加时pervious为null    
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        //最开始添加时lifecycleOwner不为null    
        if (lifecycleOwner == null) {
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        //最开始添加时statefulObserver.mState.compareTo(targetState)等于0,所以不走while里面的内容
        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);
        }
        //最开始添加isReentrance为false    
        if (!isReentrance) {
            //同步状态
            sync();
        }
        mAddingObserverCounter--;
    }


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

        //最开始添加isSysnced()方法返回true,所以不执行while里面的内容
        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;
        //最开始添加时eldestObserverState与newestObserverState指向同一对象,所以返回true
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

2.3 ObserverWidthState源码

ObserverWidthState是实现生命周期监听回调的核心类,该类源码如下:
   static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            //通过反射解析自定义Observer中的方法,将其中的方法和监听的事件进行绑定
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            //当Activity生命周期发生变化时通知自定义Observer
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

Lifecycling.getCallback(observer)源码如下:

@NonNull
static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }
		//LiveData的观察者走这条分支
        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }

        final Class<?> klass = object.getClass();
        //通过该方法将自定义Oberver中的事件和方法进行绑定
        int type = getObserverConstructorType(klass);
        //此Demo中调用时type不等于GENERATED_CALLBACK,所以不进入if分支   
        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);
}

private static int getObserverConstructorType(Class<?> klass) {
        if (sCallbackCache.containsKey(klass)) {
            return sCallbackCache.get(klass);
        }
        int type = resolveObserverCallbackType(klass);
        sCallbackCache.put(klass, type);
        return type;
    }


 private static int resolveObserverCallbackType(Class<?> klass) {

        //....
        //是否拥有监听Activity生命周期的方法,有的话将会返回true
        boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        if (hasLifecycleMethods) {
            return REFLECTIVE_CALLBACK;
        }

       //....
        return REFLECTIVE_CALLBACK;
    }

ClassesInfoCache的部分源码分析如下所示:

class ClassesInfoCache {

    static ClassesInfoCache sInstance = new ClassesInfoCache();

    private static final int CALL_TYPE_NO_ARG = 0;
    private static final int CALL_TYPE_PROVIDER = 1;
    private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2;

    private final Map<Class, CallbackInfo> mCallbackMap = new HashMap<>();
    private final Map<Class, Boolean> mHasLifecycleMethods = new HashMap<>();

    boolean hasLifecycleMethods(Class klass) {
        if (mHasLifecycleMethods.containsKey(klass)) {
            return mHasLifecycleMethods.get(klass);
        }
        //获取自定义Observer中的所有方法    
        Method[] methods = getDeclaredMethods(klass);
        //遍历方法,获取方法上面的注解
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation != null) {
                createInfo(klass, methods);
                return true;
            }
        }
        mHasLifecycleMethods.put(klass, false);
        return false;
    }

    private Method[] getDeclaredMethods(Class klass) {
        try {
            return klass.getDeclaredMethods();
        } catch (NoClassDefFoundError e) {
            throw new IllegalArgumentException("The observer class has some methods that use "
                    + "newer APIs which are not available in the current OS version. Lifecycles "
                    + "cannot access even other methods so you should make sure that your "
                    + "observer classes only access framework classes that are available "
                    + "in your min API level OR use lifecycle:compiler annotation processor.", e);
        }
    }

    //将封装的方法与事件保存起来
    private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
            MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
        Lifecycle.Event event = handlers.get(newHandler);
        if (event != null && newEvent != event) {
            Method method = newHandler.mMethod;
            throw new IllegalArgumentException(
                    "Method " + method.getName() + " in " + klass.getName()
                            + " already declared with different @OnLifecycleEvent value: previous"
                            + " value " + event + ", new value " + newEvent);
        }
        if (event == null) {
            handlers.put(newHandler, newEvent);
        }
    }
	
	//将监听事件与监听回调方法进行绑定
    private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        //....
        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        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 info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

	static class CallbackInfo {
        //...

        @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);
        }
        //根据事件获取对应的MethodReference对象,从而执行监听事件的方法
        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);
                }
            }
        }
	}

	static class MethodReference {
        //....

        //通过反射执行自定义Observer中监听Activity生命周期的方法    
        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);
            }
        }
    //....
	}

}

2.4 ReportFragment如何分发Activity生命周期事件

调用ReportFragment中的dispatch方法进行事件的传递,实际上调用的是LifecycleRegistry的handleLifecycleEvent方法,该方法源码如下:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
 		//获取当前事件对应的自定义Observer的状态,也就是当前Observer的下一个状态
        State next = getStateAfter(event);
        //将Observer的状态移动到下一个状态
        moveToState(next);
 }

 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();//同步状态,因为最开始Observer的状态是INITIALIZED,现在是CREATED,所以调用的是forwardPass方法
        mHandlingEvent = false;
}

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()))) {
                //保存observer.mState之前的状态
                pushParentState(observer.mState);
                //到了给自定义Observer回调事件监听的时候了
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                //事件分发完毕之后弹出之前保存的状态
                popParentState();
            }
        }
    }

observer.dispatchEvent最终调用的是ReflectiveGenericLifecycleObserver中的onStateChanged方法,ReflectiveGenericLifecycleObserver源码如下:

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

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        //在MainActivity添加自定义Observer的时候已经将监听事件和方法进行了绑定
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        //执行自定义Observer方法的回调
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

三、总结

这里只拿监控到Activity的onCreate进行了分析,后续Activity的生命周期回调都是类似的,这里就不作分析了。只是个人对Lifecycle源码的解读,如有不足之处敬请指出。

Lifecycle时序图

你可能感兴趣的:(Android技巧-源码分析)