ComponentActivity 理解

472 阅读2分钟

ComponentActivity

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        HasDefaultViewModelProviderFactory,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
        
        private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
        
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ReportFragment.injectIfNeededIn(this);
        }
        
      
}

ComponentActivity 是一个继承了 LifecycleOwner 的具有生命周期属性的 Activity 组件。 每个 ComponentActivity 及其子类都持有一个 LifecycleRegistry 对象,用于专门处理ComponentActivity 的生命周期事件及管理订阅了生命周期组件的观察者 Observer。 ComponentActivity 并不直接管理自己的生命周期,而是通过ReportFragment 对象来进行管理及分发的。

ReportFragment

public class ReportFragment extends Fragment {
   public static void injectIfNeededIn(Activity activity) {
       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();
       }
   }
   
   private ActivityInitializationListener mProcessListener;
   
       @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);
   }
   ....

ReportFragment 对象用于对 ComponentActivity 生命周期进行具体管理及事件分发的类。每一个 ComponentActivity 在 onCreate 方法里都会创建并将 ReportFragment 对象注册到其中。这里的设计还是比较巧妙的,使用一个 Fragment 来对 Activity 的生命周期进行管理,我们知道 activity 对应的生命周期发生变化后,fragment 也会收到相应的回调。

这种设计我是在 Glide 中有见到过,我们知道 Glide 也是一个具有生命周期感知能力的框架,当我们在创建 Glide 时,使用的是 activity 对象时,当 activity 不可见时,Glide 就会停止处理图片。

从上面的代码中可以看出 activity 所对应的几种生命周期都在 ReportFragment 中得到了重写,而且里面都有一个dispatch(Lifecycle.Event.XXX) 函数,该函数主要是做生命周期事件分发用的。该函数把生命周期转发给 LifecycleRegistry 对象来进行处理。

其实,ReportFragment 除了直接绑定具体的 Activity 做相应的生命周期分发以外,还有一个任务是和 ProcessLifecycleOwner 对象有关的。大家会不会觉得奇怪,在 ReportFragment 中的 onActivityCreated()onStart()onResume() 三个方法中怎么都调用了两个分发事件的方法?先卖个官子吧,在对 ProcessLifecycleOwner 进行分析时,我再来讲这个问题。

作者:allen218
链接:www.jianshu.com/p/14747f05e…
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。