ReactNative 源码分析4——ReactActivity之加载JSBundle

10 阅读1分钟

接着ReactInstanceManager.createReactContext方法继续讲

////ReactInstanceManager.createReactContext
private ReactApplicationContext createReactContext(
    JavaScriptExecutor jsExecutor, JSBundleLoader jsBundleLoader) {
    ...
    catalystInstance.runJSBundle();
    ...
}

最终会调用到如下 2 个方法进入C++层

private native void jniLoadScriptFromAssets(
    AssetManager assetManager, String assetURL, boolean loadSynchronously);

private native void jniLoadScriptFromFile(
    String fileName, String sourceURL, boolean loadSynchronously);

jniLoadScriptFromFile是调用到instance_->loadScriptFromString,然后调用loadBundle

void Instance::loadBundle(
    std::unique_ptr<RAMBundleRegistry> bundleRegistry,
    std::unique_ptr<const JSBigString> string,
    std::string sourceURL) {
  callback_->incrementPendingJSCalls();
  SystraceSection s( "Instance::loadBundle" , "sourceURL" , sourceURL);
  nativeToJsBridge_->loadBundle(
      std::move(bundleRegistry), std::move(string), std::move(sourceURL));
}
  • callback_是Java层的InstanceCallback实例,这里是通知Java层
  • nativeToJsBridge_是NativeToJsBridge对象
void NativeToJsBridge::loadBundle(
    std::unique_ptr<RAMBundleRegistry> bundleRegistry,
    std::unique_ptr<const JSBigString> startupScript,
    std::string startupScriptSourceURL) {
  runOnExecutorQueue(
      [this,
       bundleRegistryWrap = makeMoveWrapper(std::move(bundleRegistry)),
       startupScript = makeMoveWrapper(std::move(startupScript)),
       startupScriptSourceURL =
           std::move(startupScriptSourceURL)](JSExecutor* executor) mutable {
        auto bundleRegistry = bundleRegistryWrap.move();
        if (bundleRegistry) {
          executor->setBundleRegistry(std::move(bundleRegistry));
        }
        try {
          executor->loadBundle(
              std::move(*startupScript), std::move(startupScriptSourceURL));
        } catch (...) {
          m_applicationScriptHasFailure = true;
          throw;
        }
      });
}
  • runOnExecutorQueue在JS线程中执行
  • executor是HermesExecutor对象
void JSIExecutor::loadBundle(
    std::unique_ptr<const JSBigString> script,
    std::string sourceURL) {
  ...
  runtime_->evaluateJavaScript(
      std::make_unique<BigStringBuffer>(std::move(script)), sourceURL);
  ...
}
  • runtime_:DecoratedRuntime对象,它里面包装了HermesRuntime运行时

到这里其实就明确了,调用Hermes引擎去加载JSBundle