How to change JavaScript bundle directory path from assets to internal storage in React Native AAR in Android?

此生再无相见时 提交于 2019-12-14 03:08:25

问题


We are using React Native with our existing application.

Due to various reasons, we are downloading a JavaScript bundle from our server and storing it in internal storage.

Now we want React Native AAR to refer to our JavaScript bundle from internal storage instead of the assets folder. For this, somewhere we will need to set a JavaScript bundle directory path, that React Native refers to.

Please let me know how we can achieve this. Is there some kind of property where this path can be set?


回答1:


On android, the bundle file is provided by the ReactNativeHost. To provide a custom file, you should:

  1. Subclass ReactNativeHost. The default react native template already does that for you inside MainApplication (the mReactNativeHost member is an anonymous subclass)
  2. Override getJSBundleFile with a URI to your file (in internal storage)
  3. Override getReactNativeHost in MainApplication and return your custom host implementation.

Example:

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.asList(new MainReactPackage());
    }

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

    @Nullable @Override protected String getJSBundleFile() {
      return "uri://to/your/file"; // <----!!
    }
  };

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

  @Override public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}



回答2:


I found answer to my question after a little research. In Android, to start react application we need an instance of ReactInstanceManager. ReactInstanceManagerBuilder is an builder class for ReactInstanceManager. ReactInstanceManagerBuilder has method to set path to JS bundle file. Please refer below snippet.

ReactInstanceManagerBuilder builder = ReactInstanceManager.builder();
builder.setJSBundleFile("PATH TO YOUR JSBundleFile"); // ex: "assets://index.android.js" or "/sdcard/main.jsbundle"
.
.//other setter calls
.
mReactInstanceManager = builder.build();
mReactRootView.startReactApplication(mReactInstanceManager, appName, arguments);


来源:https://stackoverflow.com/questions/50625098/how-to-change-javascript-bundle-directory-path-from-assets-to-internal-storage-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!