React Native模塊加載與原理分析

后面會陸續(xù)寫一些文章分析React Native源碼,今天分析下模塊加載的過程,包括系統(tǒng)模塊和用戶自定義模塊的加載。源碼是基于0.19.1,加載的大概流程和0.54差別不大,所以小伙伴們也不用特別糾結。

首先先看下怎么自定義Java模塊給JS調(diào)用。直接用的官方的ToastAndroid的例子了。

1.自定義模塊

首先創(chuàng)建一個原生模塊,原生模塊是繼承了ReactContextBaseJavaModule的Java類,它可以實現(xiàn)一些JavaScript所需的功能。

public class ToastModule extends ReactContextBaseJavaModule {

  private static final String DURATION_SHORT_KEY = "SHORT";
  private static final String DURATION_LONG_KEY = "LONG";

  public ToastModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "ToastExample";
  }

  @ReactMethod
  public void show(String message, int duration) {
    Toast.makeText(getReactApplicationContext(), message, duration).show();
  }

}

ReactContextBaseJavaModule要求派生類實現(xiàn)getName方法。這個函數(shù)用于返回一個字符串名字,這個名字在JavaScript端標記這個模塊。這里我們把這個模塊叫做ToastExample,這樣就可以在JavaScript中通過React.NativeModules.ToastExample訪問到這個模塊。要導出一個方法給JavaScript使用,Java方法需要使用注解@ReactMethod。方法的返回類型必須為void。
這樣模塊就定義好了,接下來就是注冊這個模塊了。在Java層需要注冊這個模塊,在應用的Package類的createNativeModules方法中添加這個模塊。如果模塊沒有被注冊,它也無法在JavaScript中被訪問到。

public class AnExampleReactPackage implements ReactPackage {

 @Override
 public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
   return Collections.emptyList();
 }

 @Override
 public List<NativeModule> createNativeModules(
                             ReactApplicationContext reactContext) {
   List<NativeModule> modules = new ArrayList<>();

   modules.add(new ToastModule(reactContext));

   return modules;
 }

這個package需要在MainApplication.java文件的getPackages方法中提供。這個文件位于你的react-native應用文件夾的android目錄中。具體路徑是: android/app/src/main/java/com/your-app-name/MainApplication.java.

public class MainApplication extends Application implements ReactApplication {
    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new AnExampleReactPackage()
            );
        }

        @Override
        protected String getJSMainModuleName() {
            return "index.android";
        }

        @Nullable
        @Override
        protected String getBundleAssetName() {
            return "index.android.bundle";
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
      ...
    }
}

這樣就完成了模塊的注冊工作了,可以看出來框架的封裝做的很好,可以很好的擴展組件的定義和注冊。

不知道大家有沒有疑問,反正我在剛做RN的時候做完上面的步驟后是有疑問的,模塊怎么被加載的?RN的界面和Android原生的界面比如Activity有什么關系?
首先來看下,RN的界面和Android原生的界面比如Activity有什么關系?

2.ReactActivity

大家都知道,在原生Android中肯定是有一個MainActivity,然后再onCreate中setContentView塞入我們在xml中定義的布局文件,這樣界面就能被系統(tǒng)給繪制出來。那么RN的所有界面其實也可以放到一個布局文件中,只不過現(xiàn)在布局文件不是xml了,而是js寫的文件了,然后把這個布局文件給到一個Activity中,空口無憑,去扒一扒源碼。

首先在開發(fā)RN程序的時候要新建一個Activity繼承于ReactActivity,比如下面這樣:

 public class MainActivity extends ReactActivity implements DefaultHardwareBackBtnHandler {
        /**
         * Returns the name of the main component registered from JavaScript.
         * This is used to schedule rendering of the component.
         */
        @Override
        protected String getMainComponentName() {
            return "TEST";
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public void invokeDefaultOnBackPressed() {
            super.onBackPressed();
        }
    }

首先繼承ReactActivity,把生命周期交給系統(tǒng)進行管理,其他工作通過Delegate完成。

看下ReactActivity,其中getMainComponentName方法需要進行重寫,為什么需要重寫?后面在代碼里面分析,這里先略過。

/**
 * Base Activity for React Native applications.
 */
public abstract class ReactActivity extends Activity
    implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {

  private final ReactActivityDelegate mDelegate;

  protected ReactActivity() {
    mDelegate = createReactActivityDelegate();
  }

  /**
   * 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;
  }

  /**
   * Called at construction time, override if you have a custom delegate implementation.
   */
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName());
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDelegate.onCreate(savedInstanceState);
  }
  ...
}

getMainComponentName返回的名稱需要和Android入口文件index.android.js里面注冊的組件名稱一致:

class TEST extends Component {
    render() {
        return <App />;
    }
}

AppRegistry.registerComponent('TEST', () => TEST);

其實到這里可以知道要渲染的組件就是TEST這個Component(RN中的組件,可以簡單對等于View)。

接著返回去看ReactActivity,生命周期里面都調(diào)用ReactActivityDelegate:

protected void onCreate(Bundle savedInstanceState) {
        boolean needsOverlayPermission = false;
        //如果Android版本是M(23)也就是Android 6.0系統(tǒng),在調(diào)式模式下需要彈窗獲取權限
        if (getReactNativeHost().getUseDeveloperSupport() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          // Get permission to show redbox in dev builds.
          if (!Settings.canDrawOverlays(getContext())) {
            needsOverlayPermission = true;
            Intent serviceIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getContext().getPackageName()));
            FLog.w(ReactConstants.TAG, REDBOX_PERMISSION_MESSAGE);
            Toast.makeText(getContext(), REDBOX_PERMISSION_MESSAGE, Toast.LENGTH_LONG).show();
            ((Activity) getContext()).startActivityForResult(serviceIntent, REQUEST_OVERLAY_PERMISSION_CODE);
          }
        }
    
        if (mMainComponentName != null && !needsOverlayPermission) {
          loadApp(mMainComponentName);
        }
        mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
      }
    
      protected void loadApp(String appKey) {
        if (mReactRootView != null) {
          throw new IllegalStateException("Cannot loadApp while app is already running.");
        }
        mReactRootView = createRootView();
        mReactRootView.startReactApplication(
          getReactNativeHost().getReactInstanceManager(),
          appKey,
          getLaunchOptions());
        getPlainActivity().setContentView(mReactRootView);
      }

1.mMainComponentName就是前面重寫方法需要返回的,如果復寫了就會進入loadApp,這就是前面需要復寫該方法的原因嘍

3.loadApp進行三個很重要的工作,

  • 創(chuàng)建ReactRootView,這個是RN 的自定義根View,可以監(jiān)聽屏幕尺寸的變化,攔截Touch事件然后進行發(fā)送給JS層進行處理。最終會把這個View塞給activity的setContentView??聪鹿俜降亩x:
   Default root view for catalyst apps. Provides the ability to listen for 
size changes so that a UI manager can re-layout its elements. It delegates 
handling touch events for itself and child views and sending those events to 
JS by using JSTouchDispatcher. This view is overriding {@link
   ViewGroup#onInterceptTouchEvent} method in order to be notified about the events 
for all of its children and it's also overriding 
{@link ViewGroup#requestDisallowInterceptTouchEvent} to make sure that 
{@link ViewGroup#onInterceptTouchEvent} will get events even when some child view 
start intercepting it. In case when no child view is interested in handling 
some particular touch event this view's {@link View#onTouchEvent} will still 
return true in order to be notified about all subsequent touch events related to 
that gesture (in case when JS code want to handle that gesture
  • 創(chuàng)建ReactContext
Schedule rendering of the react component rendered by the JS application from the
given JS* module (@{param moduleName}) using provided 
{@param reactInstanceManager} to attach to the* JS context of that manager.
  • setContentView(ReactRootView)

到這里就明白主要工作在ReactActivityDelegate中的loadApp,首先構造根View-createRootView,然后構造ReactContext上下文,渲染appKey-- mMainComponentName這里就是在index.android.js中注冊的入口模塊,之后將該View塞給Activity,最終Android系統(tǒng)將其顯示到屏幕上。

3.RN框架加載Package

接下來看看Package怎么加載到RN框架中。

首先回到前面ReactActivityDelegate中的loadApp會拿到MainApplication中的ReactNativeHost:

protected void loadApp(String appKey) {
    if (mReactRootView != null) {
      throw new IllegalStateException("Cannot loadApp while app is already running.");
    }
    mReactRootView = createRootView();
    mReactRootView.startReactApplication(
      getReactNativeHost().getReactInstanceManager(),
      appKey,
      getLaunchOptions());
    getPlainActivity().setContentView(mReactRootView);
  }

protected ReactNativeHost getReactNativeHost() {
    return ((ReactApplication) getPlainActivity().getApplication()).getReactNativeHost();
  }

loadApp會調(diào)用getReactNativeHost().getReactInstanceManager(),接著看看ReactInstanceManager是什么,跟到ReactNativeHost中,第一次會構建ReactInstanceManager,用來管理CatalystInstance,CatalystInstance是Java/C++/JS三方通信的總管:

/**
   * Get the current {@link ReactInstanceManager} instance, or create one.
   */
  public ReactInstanceManager getReactInstanceManager() {
    if (mReactInstanceManager == null) {
      mReactInstanceManager = createReactInstanceManager();
    }
    return mReactInstanceManager;
  }

protected ReactInstanceManager createReactInstanceManager() {
    ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
      .setApplication(mApplication)
      .setJSMainModulePath(getJSMainModuleName())
      .setUseDeveloperSupport(getUseDeveloperSupport())
      .setRedBoxHandler(getRedBoxHandler())
      .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
      .setUIImplementationProvider(getUIImplementationProvider())
      .setInitialLifecycleState(LifecycleState.BEFORE_CREATE);

    for (ReactPackage reactPackage : getPackages()) {
      builder.addPackage(reactPackage);
    }

    String jsBundleFile = getJSBundleFile();
    if (jsBundleFile != null) {
      builder.setJSBundleFile(jsBundleFile);
    } else {
      builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName()));
    }
    return builder.build();
  }

從上面可以看到用到了建造者模式構造 ReactInstanceManager:

/**
 * Builder class for {@link ReactInstanceManager}
 */
public class ReactInstanceManagerBuilder {

  private final List<ReactPackage> mPackages = new ArrayList<>();
  
  public ReactInstanceManagerBuilder addPackage(ReactPackage reactPackage) {
    mPackages.add(reactPackage);
    return this;
  }

  public ReactInstanceManagerBuilder addPackages(List<ReactPackage> reactPackages) {
    mPackages.addAll(reactPackages);
    return this;
  }
  
  /**
     * Instantiates a new {@link ReactInstanceManagerImpl}.
     * Before calling {@code build}, the following must be called:
     * <ul>
     * <li> {@link #setApplication}
     * <li> {@link #setJSBundleFile} or {@link #setJSMainModuleName}
     * </ul>
     */
    public ReactInstanceManager build() {
      return new ReactInstanceManagerImpl(
          Assertions.assertNotNull(
              mApplication,
              "Application property has not been set with this builder"),
          mJSBundleFile,
          mJSMainModuleName,
          mPackages,
          mUseDeveloperSupport,
          mBridgeIdleDebugListener,
          Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"),
          mUIImplementationProvider,
          mNativeModuleCallExceptionHandler);
    }
}

到這里系統(tǒng)定義的和我們自定義的ReactPackage都加載到ReactInstanceManageImpl中的mPackages中。
再返回前面ReactRootView startReactApplication,會調(diào)用mReactInstanceManager.createReactContextInBackground

//com/facebook/react/ReactRootView
public void startReactApplication(
      ReactInstanceManager reactInstanceManager,
      String moduleName,
      @Nullable Bundle initialProperties) {
    Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication");
    try {
      UiThreadUtil.assertOnUiThread();

      if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
        mReactInstanceManager.createReactContextInBackground();
      }

      attachToReactInstanceManager();

    } finally {
      Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
    }
  }

接著到ReactInstanceManagerImpl中:

//com/facebool/react/ReactInstanceManagerImpl
@ThreadConfined(UI)
  public void createReactContextInBackground() {
    ......
    mHasStartedCreatingInitialContext = true;
    recreateReactContextInBackgroundInner();
  }

@ThreadConfined(UI)
  private void recreateReactContextInBackgroundInner() {
    ......
    UiThreadUtil.assertOnUiThread();

    if (mUseDeveloperSupport && mJSMainModulePath != null &&
      !Systrace.isTracing(TRACE_TAG_REACT_APPS | TRACE_TAG_REACT_JSC_CALLS)) {
      final DeveloperSettings devSettings = mDevSupportManager.getDevSettings();

      // If remote JS debugging is enabled, load from dev server.
      if (mDevSupportManager.hasUpToDateJSBundleInCache() &&
          !devSettings.isRemoteJSDebugEnabled()) {
        // If there is a up-to-date bundle downloaded from server,
        // with remote JS debugging disabled, always use that.
        onJSBundleLoadedFromServer();
      } else if (mBundleLoader == null) {
        mDevSupportManager.handleReloadJS();
      } else {
        mDevSupportManager.isPackagerRunning(
            new PackagerStatusCallback() {
              @Override
              public void onPackagerStatusFetched(final boolean packagerIsRunning) {
                UiThreadUtil.runOnUiThread(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (packagerIsRunning) {
                          mDevSupportManager.handleReloadJS();
                        } else {
                          // If dev server is down, disable the remote JS debugging.
                          devSettings.setRemoteJSDebugEnabled(false);
                          recreateReactContextInBackgroundFromBundleLoader();
                        }
                      }
                    });
              }
            });
      }
      return;
    }

    recreateReactContextInBackgroundFromBundleLoader();
  }

最后都會回調(diào):

//com/facebool/react/ReactInstanceManagerImpl
private void recreateReactContextInBackground(
      JavaScriptExecutor.Factory jsExecutorFactory,
      JSBundleLoader jsBundleLoader) {
    UiThreadUtil.assertOnUiThread();

    ReactContextInitParams initParams =
        new ReactContextInitParams(jsExecutorFactory, jsBundleLoader);
    if (!mIsContextInitAsyncTaskRunning) {
      // No background task to create react context is currently running, create and execute one.
      ReactContextInitAsyncTask initTask = new ReactContextInitAsyncTask();
      initTask.execute(initParams);
      mIsContextInitAsyncTaskRunning = true;
    } else {
      // Background task is currently running, queue up most recent init params to recreate context
      // once task completes.
      mPendingReactContextInitParams = initParams;
    }
  }

會啟動一個AsyncTask來構造ReactContext:

//com/facebool/react/ReactInstanceManagerImpl
/*
   * Task class responsible for (re)creating react context in the background. These tasks can only
   * be executing one at time, see {@link #recreateReactContextInBackground()}.
   */
  private final class ReactContextInitAsyncTask extends
      AsyncTask<ReactContextInitParams, Void, Result<ReactApplicationContext>> {
    @Override
    protected void onPreExecute() {
      if (mCurrentReactContext != null) {
        tearDownReactContext(mCurrentReactContext);
        mCurrentReactContext = null;
      }
    }

    @Override
    protected Result<ReactApplicationContext> doInBackground(ReactContextInitParams... params) {
      Assertions.assertCondition(params != null && params.length > 0 && params[0] != null);
      try {
        JavaScriptExecutor jsExecutor = params[0].getJsExecutorFactory().create();
        return Result.of(createReactContext(jsExecutor, params[0].getJsBundleLoader()));
      } catch (Exception e) {
        // Pass exception to onPostExecute() so it can be handled on the main thread
        return Result.of(e);
      }
    }

    @Override
    protected void onPostExecute(Result<ReactApplicationContext> result) {
      try {
        setupReactContext(result.get());
      } catch (Exception e) {
        mDevSupportManager.handleException(e);
      } finally {
        mIsContextInitAsyncTaskRunning = false;
      }
      ......
    }
  }

在doInBackground中構造ReactContext:

  • 構造ReactContext
  • 加載CoreModulesPackage,系統(tǒng)的核心模塊
  • 加載用戶自定義Packages
  • 構造NativeModuleRegistry,管理暴露給JS層的Java本地模塊
  • 構造JavaScriptModulesConfig,存儲JS層暴露給Java調(diào)用的JS模塊
  • 構造CatalystInstanceImpl,三方總管
  • runJSBundle
    /**
       * @return instance of {@link ReactContext} configured a {@link CatalystInstance} set
       */
      private ReactApplicationContext createReactContext(
          JavaScriptExecutor jsExecutor,
          JSBundleLoader jsBundleLoader) {
        mSourceUrl = jsBundleLoader.getSourceUrl();
        NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder();
        JavaScriptModulesConfig.Builder jsModulesBuilder = new JavaScriptModulesConfig.Builder();
    
        //構造ReactContext
        ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext);
        if (mUseDeveloperSupport) {
          reactContext.setNativeModuleCallExceptionHandler(mDevSupportManager);
        }
    
        //加載CoreModulesPackage
        Systrace.beginSection(
            Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
            "createAndProcessCoreModulesPackage");
        try {
          CoreModulesPackage coreModulesPackage =
              new CoreModulesPackage(this, mBackBtnHandler, mUIImplementationProvider);
          processPackage(coreModulesPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder);
        } finally {
          Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
        }
    
        //加載用戶自定義Packages
        for (ReactPackage reactPackage : mPackages) {
          Systrace.beginSection(
              Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
              "createAndProcessCustomReactPackage");
          try {
            processPackage(reactPackage, reactContext, nativeRegistryBuilder, jsModulesBuilder);
          } finally {
            Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
          }
        }
    
        //構造NativeModuleRegistry
        Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "buildNativeModuleRegistry");
        NativeModuleRegistry nativeModuleRegistry;
        try {
           nativeModuleRegistry = nativeRegistryBuilder.build();
        } finally {
          Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
        }
    
        //構造JavaScriptModulesConfig
        Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "buildJSModuleConfig");
        JavaScriptModulesConfig javaScriptModulesConfig;
        try {
          javaScriptModulesConfig = jsModulesBuilder.build();
        } finally {
          Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
        }
    
        ...
        //構造CatalystInstanceImpl
        CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder()
            .setCatalystQueueConfigurationSpec(CatalystQueueConfigurationSpec.createDefault())
            .setJSExecutor(jsExecutor)
            .setRegistry(nativeModuleRegistry)
            .setJSModulesConfig(javaScriptModulesConfig)
            .setJSBundleLoader(jsBundleLoader)
            .setNativeModuleCallExceptionHandler(exceptionHandler);
    
        Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "createCatalystInstance");
        CatalystInstance catalystInstance;
        try {
          catalystInstance = catalystInstanceBuilder.build();
        } finally {
          Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
        }
    
        ......
        reactContext.initializeWithInstance(catalystInstance);
    
        //runJSBundle
        Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "runJSBundle");
        try {
          catalystInstance.runJSBundle();
        } finally {
          Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
        }
    
        ReactMarker.logMarker("CREATE_REACT_CONTEXT_END");
        return reactContext;
      }
    //加載模塊
    private void processPackage(
          ReactPackage reactPackage,
          ReactApplicationContext reactContext,
          NativeModuleRegistry.Builder nativeRegistryBuilder,
          JavaScriptModulesConfig.Builder jsModulesBuilder) {
        for (NativeModule nativeModule : reactPackage.createNativeModules(reactContext)) {
          nativeRegistryBuilder.add(nativeModule);
        }
        for (Class<? extends JavaScriptModule> jsModuleClass : reactPackage.createJSModules()) {
          jsModulesBuilder.add(jsModuleClass);
        }
      }

CoreModulesPackage

封裝了一些系統(tǒng)的核心模塊,有NativeModules和JSModules

class CoreModulesPackage implements ReactPackage{
  @Override
  public List<NativeModule> createNativeModules(
      ReactApplicationContext catalystApplicationContext) {
    ......
    return Arrays.<NativeModule>asList(
        new AnimationsDebugModule(
            catalystApplicationContext,
            mReactInstanceManager.getDevSupportManager().getDevSettings()),
        new AndroidInfoModule(),
        new DeviceEventManagerModule(catalystApplicationContext, mHardwareBackBtnHandler),
        new ExceptionsManagerModule(mReactInstanceManager.getDevSupportManager()),
        new Timing(catalystApplicationContext),
        new SourceCodeModule(
            mReactInstanceManager.getSourceUrl(),
            mReactInstanceManager.getDevSupportManager().getSourceMapUrl()),
        uiManagerModule,
        new DebugComponentOwnershipModule(catalystApplicationContext));
  }
  
  @Override
  public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Arrays.asList(
        DeviceEventManagerModule.RCTDeviceEventEmitter.class,
        JSTimersExecution.class,
        RCTEventEmitter.class,
        RCTNativeAppEventEmitter.class,
        AppRegistry.class,
        com.facebook.react.bridge.Systrace.class,
        DebugComponentOwnershipModule.RCTDebugComponentOwnership.class);
  }
}

public interface ReactPackage {

  /**
   * @param reactContext react application context that can be used to create modules
   * @return list of native modules to register with the newly created catalyst instance
   */
  List<NativeModule> createNativeModules(ReactApplicationContext reactContext);

  /**
   * @return list of JS modules to register with the newly created catalyst instance.
   *
   * IMPORTANT: Note that only modules that needs to be accessible from the native code should be
   * listed here. Also listing a native module here doesn't imply that the JS implementation of it
   * will be automatically included in the JS bundle.
   */
  List<Class<? extends JavaScriptModule>> createJSModules();

  /**
   * @return a list of view managers that should be registered with {@link UIManagerModule}
   */
  List<ViewManager> createViewManagers(ReactApplicationContext reactContext);
}

到這里就把所有的Java模塊和JS模塊傳遞給了CatalystInstanceImpl,這個是三方的中轉模塊,調(diào)用邏輯在這里中轉。再之后就是Java<-->JS雙方通信的原理了,后面專門的文章進行分析。

4.總結

整個流程其實是:

  ReactActivity--->
  ReactActivityDelegate--->
         createRootView->
          getReactNativeHost->
          createReactInstanceManager->ReactInstanceManagerImpl
                  recreateReactContextInBackground->
                     1.構造ReactContext->
                     2.加載CoreModulesPackage->
                     3.加載用戶自定義Packages->
                     4.構造CatalystInstanceImpl->
                     5.runJSBundle
          setContentView(mReactRootView)

React Native框架就是套一個自定義的根View-ReactRootView,在這個自定義View中創(chuàng)建ReactInstanceManager,ReactInstanceManager會構造ReactContext(包括JS運行環(huán)境和JSBundleLoader),同時加載系統(tǒng)和用戶定義的Package,構造三方通信的中轉站CatalystInstanceImpl,然后解釋執(zhí)行JSBundle,最后getPlainActivity().setContentView(mReactRootView)塞給Activity這樣RN界面就顯示到屏幕上了,而這個Activity的生命周期其實還是交給Android進行管理的。

后面會接著分析RN中Java與JS的通信原理,感興趣的小伙伴們歡迎關注。

如果文章內(nèi)容能夠幫到你,幫忙點贊哈。

歡迎關注公眾號:JueCode

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容