jetpack之LifeCycle

Posted 做一个苦行僧

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jetpack之LifeCycle相关的知识,希望对你有一定的参考价值。

假如 我们有某个Activity 需要用到定位相关的逻辑我们代码大家或许会这样写

internal class MyLocationListener(
        private val context: Context,
        private val callback: (Location) -> Unit
) 

    fun start() 
        // connect to system location service
    

    fun stop() 
        // disconnect from system location service
    


class MyActivity : AppCompatActivity() 
    private lateinit var myLocationListener: MyLocationListener

    override fun onCreate(...) 
        myLocationListener = MyLocationListener(this)  location ->
            // update UI
        
    

    public override fun onStart() 
        super.onStart()
        myLocationListener.start()
        // manage other components that need to respond
        // to the activity lifecycle
    

    public override fun onStop() 
        super.onStop()
        myLocationListener.stop()
        // manage other components that need to respond
        // to the activity lifecycle
    

在我们需要 使用定位的activity 中,注册定位的监听,然后在onStart()方法中开启定位监听,在onStop()方法中关闭定位监听。相比一般人都会这么写。此时如果我们假如有许多Activity都可能使用到定位,好一点的,我们会将定位的逻辑抽取到BaseActivity中然后根据子类是否需要 ,按需去开启定位的功能。这样写的确是可以实现我们的功能,但是如果android的多个model,或者Fragemnt中要使用这一功能,我们是不是在每个需要使用的地方重写这样一套逻辑呢,显然大部分人都不希望这么干。此时我们可以使用我们的LifeCycle.

什么是Lifecycle

Lifecycle是一套专门用来感知Activity或Fragment生命周期变化的组件,当Activity或Fragment的生命周期发生的变化的时候,将会通知到Lifecycle的订阅者。这样我们可以把原本需要写在Activity或Fragment的代码抽出来,减少Activity或者Fragment的代码侵入性,使Activity或Fragment更加精简并且易于维护,也可以减少内存泄漏

Lifecycle的使用

1.继承LifeCycleObserver

class CustomLifecycleObserver:LifecycleObserver 
    val TAG = CustomLifecycleObserver::class.java.simpleName
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreateMethod()
        Log.e(TAG,"onCreateMethod run")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStartMethod()
        Log.e(TAG,"onStartMethod run")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResumeMethod()
        Log.e(TAG,"onResumeMethod run")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPauseMethod()
        Log.e(TAG,"onPauseMethod run")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStopMethod()
        Log.e(TAG,"onStopMethod run")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestoryMethod()
        Log.e(TAG,"onDestoryMethod run")
    

我们只需要 继承LifeCycleObserver ,然后在我们的Activity中注册一个观察者就行了

class LifeCycleActivity : AppCompatActivity() 
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_life_cycle)

        lifecycle.addObserver(CustomLifecycleObserver())
    

这样我们就可以在自定义的CustomLifecycleObserver中去监听Activity的生命周期变化了。

在CustomLifecycleObserver中,我们可以看到方法上面都有@OnLifecycleEvent注解,注解的参数正好是对应了Activity的各种生命周期。

2. 利用LifecycleOwner来实现(具体 原来后面分析源码可以得知)

class CustomLifeOwnerActivity: Activity(),LifecycleOwner 
    private lateinit var lifecycleRegistry: LifecycleRegistry

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        lifecycleRegistry = LifecycleRegistry(this)
        lifecycleRegistry.currentState = Lifecycle.State.CREATED
        lifecycleRegistry.addObserver(CustomLifecycleObserver())
    

    override fun onStart() 
        super.onStart()
        lifecycleRegistry.currentState = Lifecycle.State.STARTED
    

    override fun onResume() 
        super.onResume()
        lifecycleRegistry.currentState = Lifecycle.State.RESUMED
    
    
    override fun getLifecycle(): Lifecycle 
        return lifecycleRegistry;
    

这种实现,我们继承自Activity 而不是AppcompactActivity ,因为AppcompactActivity 已经帮我们实现了 这些生命周期的处理。一般我们使用LifeCycle也不使用这种方式,使用第一种 就OK了

Lifecycle的源码分析

在下面的代码中

class LifeCycleActivity : AppCompatActivity() 
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_life_cycle)

        lifecycle.addObserver(CustomLifecycleObserver())
    

我只要使用lifecycle.addObserver(CustomLifecycleObserver()) 代码注册观察者之后CustomLifecycleObserver就可以监听当前Activity的所有生命周期了,我们跟踪源码看看其到底是怎么实现的。

addObserver ->Lifecycle.addObserver(抽象类的方法) -->LifecycleRegistry.addObserver(具体实现)

@Override
    public void addObserver(@NonNull LifecycleObserver observer) 
        enforceMainThreadIfNeeded("addObserver");
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

        ..... //后面省略的代码 可以到之后的LiveData中讲解 具体的意义
    

这里其实 就是将自己创建的CustomLifecycleObserver加入到mObserverMap中缓存起来,供后面的生命周期回调。

Activity的生命周期回调 ,怎么使我们的自定义Observer回调呢,这里其实有使用到跟Glide相同方法,就是构建一个Fragment,然后在Fragment中去回调 生命周期,这样的确有点巧妙,我们看具体的代码

// ComponentActivity
protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    


// ReportActivity
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();
        
    

使用这些代码之后 就注入了一个不可见的ReportFragment,来感知Activity的生命周期,看ReportFragment的onResume方法

//ReprotFragment
@Override
    public void onResume() 
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    



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

如果是Activity的话,最后走到了LifecycleRegistry 的handleLifecycleEvent(event)方法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) 
        // 检查是否在主线程中执行
        enforceMainThreadIfNeeded("handleLifecycleEvent");
        moveToState(event.getTargetState());
    


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;
    

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;
            // 检测如果你住处Observer的时候activity 状态 与存储的Observer状态对比
            // Activity 为onResume Observer可能需要执行从onCreate->onResume
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) 
                backwardPass(lifecycleOwner);
            
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) 
                forwardPass(lifecycleOwner);
            
        
        mNewEventOccurred = false;
    

最终的逻辑会进入sync方法中,走两个分支的方法,backwardPass或者forwardPass方法,无非 就是 向前或者向后执行 生命周期的相关方法。我们这里看forwardPass方法的距离逻辑

private void forwardPass(LifecycleOwner lifecycleOwner) 
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) 
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) 
                pushParentState(observer.mState);
                final Event event = Event.upFrom(observer.mState);
                if (event == null) 
                    throw new IllegalStateException("no event up from " + observer.mState);
                
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            
        
    

最后都会走到 observer.dispatchEvent(lifecycleOwner, event); 其中的observer 是 ObserverWithState。这个类我们在最开始的时候 lifecycle.addObserver方法中看到

@Override
    public void addObserver(@NonNull LifecycleObserver observer) 
        enforceMainThreadIfNeeded("addObserver");
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

       .....
    

最终会走到ObserverWithState方法中的dispatchEvent方法中

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 = event.getTargetState();
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        
    

调用LifecycleEventObserver 的onStateChanged方法。看构造函数中的LifecycleEventObserver是怎么生成的

@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();
        // 根据我们传入的对象,获得tyep类型,带有@OnLifecycleEvent注解的类型 就返回
        // REFLECTIVE_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);
        
        return new ReflectiveGenericLifecycleObserver(object);
    


//Lifecycling.java   resolveObserverCallbackType 方法
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);


//ClassesInfoCache
 boolean hasLifecycleMethods(Class<?> klass) 
        Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
        if (hasLifecycleMethods != null) 
            return hasLifecycleMethods;
        

        Method[] methods = getDeclaredMethods(klass);
        for (Method method : methods) 
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation != null) 
                // Optimization for reflection, we know that this method is called
                // when there is no generated adapter. But there are methods with @OnLifecycleEvent
                // so we know that will use ReflectiveGenericLifecycleObserver,
                // so we createInfo in advance.
                // CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
                // here.
                createInfo(klass, methods);
                return true;
            
        
        mHasLifecycleMethods.put(klass, false);
        return false;
    



这里 会将有OnLifecycleEvent 注解的方法 通过反射拿出来,最后缓存起来。

然后回到Lifecycleing的方法 因为type返回的是 REFLECTIVE_CALLBACK 所以最终 会返回 ReflectiveGenericLifecycleObserver的对象,然后调用其onStateChanged方法,

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



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

最终回去从这里执行到刚刚 通过反射 缓存的生命周期的方法,这样 就从ReportFragment 中生命周期回调到我们自定义的Observer中的回调方法了。

以上是关于jetpack之LifeCycle的主要内容,如果未能解决你的问题,请参考以下文章

Jetpack 之 LifeCycle 组件使用详解

Android Jetpack系列之Lifecycle

jetpack之LifeCycle

jetpack之LifeCycle

jetpack之LifeCycle

Jetpack组件之Lifecycle使用与源码分析