AndroidJetPack中Lifecycle原理和机制

本文详细探讨了Android Jetpack中的Lifecycle组件,包括ComponentActivity和Fragment中实现生命周期感知和传递的机制。讲解了如何通过LifecycleOwner和LifecycleRegistry进行状态管理,以及为何在Fragment中建议使用FragmentViewLifecycleOwner绑定LiveData以避免重复订阅问题。同时,分析了ObserverWithState的角色,它是如何包装LifecycleObserver并与状态同步。通过对Lifecycle内部状态机的理解,可以更好地掌握Android应用的生命周期管理。
摘要由CSDN通过智能技术生成

Lifecycle原理和机制

Lifectcle的用来感知页面的生命周期,并通过利用观察者模式,将感知到的生命周期告知到相应的回调中去。

ComponentActivity中的实现探讨

ComponentActivity首先实现了LifecycleOwner接口并返回LifecycleRegistry对象

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        ContextAware,
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner,
        ActivityResultRegistryOwner,
        ActivityResultCaller {
   

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
    public Lifecycle getLifecycle() {
   
        return mLifecycleRegistry;
    }        
 }

生命周期的感知与传递

为什么说ComponentActivity已经实现好生命周期观察派发,其实在它执行onCreate的生命周期时,其内部会添加一个ReportFragment,接下来请查看部分源码:

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
   
        mSavedStateRegistryController.performRestore(savedInstanceState);
        
        mContextAwareHelper.dispatchOnContextAvailable(this);
        super.onCreate(savedInstanceState);
        //在这里调用 ReportFragment.injectIfNeededIn 静态方法 动态添加一个ReportFragment
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
   
            setContentView(mContentLayoutId);
        }
    }
    
    public static void injectIfNeededIn(Activity activity) {
   
        if (Build.VERSION.SDK_INT >= 29) {
   
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            LifecycleCallbacks.registerIn(activity);
        }
        // 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();
        }
    }

其实在ReportFragment最为核心的在于两个地方:静态内部类LifecycleCallbacks、静态方法dispatch,

其中LifecycleCallbacks中在高于29以上版本中它通过实现了ActivityLifecycleCallbacks这个接口,通过回调及时的调用dispatch方法将相应的Activity中的生命周期及时的派发出去

    @RequiresApi(29)
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
   

        static void registerIn(Activity activity) {
   
            activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
        }

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

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


        @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 onActivityPreStopped(@NonNull Activity activity) {
   
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }


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

那么我们来看看ReportFragment中的dispatch是如何实现事件的派发

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

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
   
   		enforceMainThreadIfNeeded("handleLifecycleEvent");
   		moveToState(event.getTargetState());
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值