ReactNative源码分析之ReactActivity启动流程

本文详细分析了ReactActivity的启动流程,从ReactActivity、ReactActivityDelegate到ReactDelegate的交互,重点探讨了onCreate方法、loadApp过程,以及ReactContext和ReactRootView的创建。最后,解释了如何通过AppRegistry加载JavaScript模块并执行jsAppModuleName组件。
摘要由CSDN通过智能技术生成

讲解ReactActivity之前,需要理清如下三个类之间的关系:
1.ReactActivity;
2.ReactActivityDelegate;
3.ReactDelegate;

通过源码我们看到,ReactAcitivy -> ReactActivityDelegate -> ReactDelegate,三者之间是包含与被包含关系;

ReactActivity相关的行为都由ReactActivityDelegate代理,其中有两个方法需要注意:

  protected final void loadApp(String appKey) {
   
    mDelegate.loadApp(appKey);
  }

该方法提供整个module加载的入口,RN框架如果经过修改,它本身是支持加载多bundle。

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component. e.g. "MoviesApp"
   */
  protected @Nullable String getMainComponentName() {
   
    return null;
  }

上面方法注释已经解释很清楚,它提供了main component的名称,告诉框架,该Activity对应的ReactRootView最终会加载哪个component。

接下来继续看ReactActivityDelegate类,该类部分功能由ReactDelegate代理,我们先看如下方法:

  protected void onCreate(Bundle savedInstanceState) {
   
    String mainComponentName = getMainComponentName();
    mReactDelegate =
        new ReactDelegate(
            getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions()) {
   
          @Override
          protected ReactRootView createRootView() {
   
            return ReactActivityDelegate.this.createRootView();
          }
        };
    if (mMainComponentName != null) {
   
      loadApp(mainComponentName);
    }
  }

我们看到,当activity创建完,会执行onCreate方法,该方法核心逻辑如下:
1.创建ReactDelegate;
2.执行loadApp方法,加载component;

先来看ReactDelegate类的实现,该类一部分功能由外部传进来的ReactNativeHost代理,提供ReactInstanceManager类,同时会提供创建ReactRootView方法。

再来看loadApp,具体到ReactDelegate里的loadApp,代码如下:

  public void loadApp(String appKey) {
   
    if (mReactRootView != null) {
   
      throw new IllegalStateException("Cannot loadApp while app is already running.");
    }
    mReactRootView = createRootView();
    mReactRootView.startReactApplication(
        getReactNativeHost().getReactInstanceManager(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值