com.facebook.react.bridge.CatalystInstance Java Examples

The following examples show how to use com.facebook.react.bridge.CatalystInstance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsLoaderUtil.java    From MetroExample with Apache License 2.0 6 votes vote down vote up
public static void fromAssets(Application application, String bundleName, boolean isSync) {
    if (hasBundle(bundleName) || JsLoaderUtil.jsState.isDev) {
        return;
    }
    String source = bundleName;
    if (!bundleName.startsWith("assets://")) {
        source = "assets://" + bundleName;
    }
    if (!source.endsWith(jsState.bundleSuffix)) {
        source = source + jsState.bundleSuffix;
    }
    CatalystInstance catalyst = getCatalyst(application);
    try {
        if (catalyst != null) {
            catalyst.loadScriptFromAssets(application.getAssets(), source, isSync);
            addBundle(bundleName);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: ActivityStarterModule.java    From react-native-android-activity with MIT License 6 votes vote down vote up
@ReactMethod
void callJavaScript() {
    Activity activity = getCurrentActivity();
    if (activity != null) {
        MainApplication application = (MainApplication) activity.getApplication();
        ReactNativeHost reactNativeHost = application.getReactNativeHost();
        ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
        ReactContext reactContext = reactInstanceManager.getCurrentReactContext();

        if (reactContext != null) {
            CatalystInstance catalystInstance = reactContext.getCatalystInstance();
            WritableNativeArray params = new WritableNativeArray();
            params.pushString("Hello, JavaScript!");

            // AFAIK, this approach to communicate from Java to JavaScript is officially undocumented.
            // Use at own risk; prefer events.
            // Note: Here we call 'alert', which shows UI. If this is done from an activity that
            // doesn't forward lifecycle events to React Native, it wouldn't work.
            catalystInstance.callFunction("JavaScriptVisibleToJava", "alert", params);
        }
    }
}
 
Example #3
Source File: JsLoaderUtil.java    From MetroExample with Apache License 2.0 6 votes vote down vote up
public static void fromFile(Application application, String bundleName, String sourceUrl, boolean isSync) {
    if (hasBundle(sourceUrl) || JsLoaderUtil.jsState.isDev) {
        return;
    }
    if (TextUtils.isEmpty(jsState.filePath)) {
        setDefaultFileDir(application);
    }
    String bundleDir = jsState.filePath;

    CatalystInstance catalyst = getCatalyst(application);
    try {
        if (catalyst != null) {
            catalyst.loadScriptFromFile(bundleDir + File.separator + bundleName, sourceUrl, isSync);
            addBundle(sourceUrl);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void detachViewFromInstance(
    ReactRootView rootView,
    CatalystInstance catalystInstance) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.detachViewFromInstance()");
  UiThreadUtil.assertOnUiThread();
  if (rootView.getUIManagerType() == FABRIC) {
    catalystInstance.getJSModule(ReactFabric.class)
      .unmountComponentAtNode(rootView.getId());
  } else {
    catalystInstance.getJSModule(AppRegistry.class)
      .unmountApplicationComponentAtRootTag(rootView.getId());
  }

}
 
Example #5
Source File: JsLoaderUtil.java    From MetroExample with Apache License 2.0 5 votes vote down vote up
@Nullable
public static CatalystInstance getCatalyst(Application application) {
    ReactInstanceManager manager = getReactIM(application);
    if (manager == null) {
        return null;
    }
    ReactContext context = manager.getCurrentReactContext();
    if (context == null) {
        return null;
    }
    return context.getCatalystInstance();
}
 
Example #6
Source File: FabricReconcilerTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Before
public void setUp() {
  CatalystInstance catalystInstance = ReactTestHelper.createMockCatalystInstance();
  ReactApplicationContext reactContext =
      new ReactApplicationContext(RuntimeEnvironment.application);
  reactContext.initializeWithInstance(catalystInstance);
  List<ViewManager> viewManagers = new ArrayList<>();
  ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers);
  JavaScriptContextHolder jsContext = mock(JavaScriptContextHolder.class);
  EventDispatcher eventDispatcher = mock(EventDispatcher.class);
  mFabricUIManager = new FabricUIManager(reactContext, viewManagerRegistry, jsContext, eventDispatcher);
  mMockUIViewOperationQueue = new MockUIViewOperationQueue(reactContext);
  mFabricReconciler = new FabricReconciler(mMockUIViewOperationQueue);
}
 
Example #7
Source File: ReactSliderPropertyTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Before
public void setup() {
  ReactApplicationContext mContext = new ReactApplicationContext(RuntimeEnvironment.application);
  CatalystInstance mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance();
  mContext.initializeWithInstance(mCatalystInstanceMock);
  mThemedContext = new ThemedReactContext(mContext, mContext);
  mManager = new ReactSliderManager();
}
 
Example #8
Source File: ReactTestHelper.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static ReactTestFactory.ReactInstanceEasyBuilder catalystInstanceBuilder(
    final ReactIntegrationTestCase testCase) {
  final ReactTestFactory.ReactInstanceEasyBuilder builder =
    getReactTestFactory().getCatalystInstanceBuilder();
  ReactTestFactory.ReactInstanceEasyBuilder postBuilder =
    new ReactTestFactory.ReactInstanceEasyBuilder() {
      @Override
      public ReactTestFactory.ReactInstanceEasyBuilder setContext(Context context) {
        builder.setContext(context);
        return this;
      }

      @Override
      public ReactTestFactory.ReactInstanceEasyBuilder addNativeModule(NativeModule module) {
        builder.addNativeModule(module);
        return this;
      }

      @Override
      public CatalystInstance build() {
        final CatalystInstance instance = builder.build();
        testCase.initializeWithInstance(instance);
        instance.runJSBundle();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
          @Override
          public void run() {
            ReactChoreographer.initialize();
            instance.initialize();
          }
        });
        testCase.waitForBridgeAndUIIdle();
        return instance;
      }
    };

  postBuilder.setContext(testCase.getContext());
  return postBuilder;
}
 
Example #9
Source File: UIManagerHelper.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * @return a {@link UIManager} that can handle the react tag received by parameter.
 */
public static UIManager getUIManager(ReactContext context, @UIManagerType int uiManagerType) {
  CatalystInstance catalystInstance = context.getCatalystInstance();
  return uiManagerType == FABRIC ?
    catalystInstance.getJSIModule(UIManager.class) :
    catalystInstance.getNativeModule(UIManagerModule.class);
}
 
Example #10
Source File: ReactRootView.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * Calls into JS to start the React application. Can be called multiple times with the
 * same rootTag, which will re-render the application from the root.
 */
/* package */ void runApplication() {
    Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication");
    try {
      if (mReactInstanceManager == null || !mIsAttachedToInstance) {
        return;
      }

      ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
      if (reactContext == null) {
        return;
      }

      CatalystInstance catalystInstance = reactContext.getCatalystInstance();

      WritableNativeMap appParams = new WritableNativeMap();
      appParams.putDouble("rootTag", getRootViewTag());
      @Nullable Bundle appProperties = getAppProperties();
      if (appProperties != null) {
        appParams.putMap("initialProps", Arguments.fromBundle(appProperties));
      }
      if (getUIManagerType() == FABRIC) {
        appParams.putBoolean("fabric", true);
      }

      mShouldLogContentAppeared = true;

      String jsAppModuleName = getJSModuleName();
      catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
    } finally {
      Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
    }
}
 
Example #11
Source File: ModuleDataCleaner.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void cleanDataFromModules(CatalystInstance catalystInstance) {
  for (NativeModule nativeModule : catalystInstance.getNativeModules()) {
    if (nativeModule instanceof Cleanable) {
      FLog.d(ReactConstants.TAG, "Cleaning data from " + nativeModule.getName());
      ((Cleanable) nativeModule).clearSensitiveData();
    }
  }
}
 
Example #12
Source File: ScriptLoadUtil.java    From react-native-multibundler with The Unlicense 5 votes vote down vote up
public static void loadScriptFromFile(String fileName,
                                       CatalystInstance instance,
                                       String sourceUrl,boolean isSync) {
    if (sLoadedScript.contains(sourceUrl)) {
        return;
    }
    BridgeUtil.loadScriptFromFile(fileName,instance,sourceUrl,isSync);
    sLoadedScript.add(sourceUrl);
}
 
Example #13
Source File: ScriptLoadUtil.java    From react-native-multibundler with The Unlicense 5 votes vote down vote up
public static void loadScriptFromAsset(Context context,
                                CatalystInstance instance,
                                String assetName,boolean isSync) {
    if (sLoadedScript.contains(assetName)) {
        return;
    }
    BridgeUtil.loadScriptFromAsset(context,instance,assetName,isSync);
    sLoadedScript.add(assetName);
}
 
Example #14
Source File: ScriptLoadUtil.java    From react-native-multibundler with The Unlicense 5 votes vote down vote up
@Nullable
public static CatalystInstance getCatalystInstance(ReactNativeHost host) {
    ReactInstanceManager manager = host.getReactInstanceManager();
    if (manager == null) {
        Log.e(TAG,"manager is null!!");
        return null;
    }

    ReactContext context = manager.getCurrentReactContext();
    if (context == null) {
        Log.e(TAG,"context is null!!");
        return null;
    }
    return context.getCatalystInstance();
}
 
Example #15
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 4 votes vote down vote up
private void setupReactContext(final ReactApplicationContext reactContext) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.setupReactContext()");
  ReactMarker.logMarker(PRE_SETUP_REACT_CONTEXT_END);
  ReactMarker.logMarker(SETUP_REACT_CONTEXT_START);
  Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "setupReactContext");
  synchronized (mReactContextLock) {
    mCurrentReactContext = Assertions.assertNotNull(reactContext);
  }
  CatalystInstance catalystInstance =
    Assertions.assertNotNull(reactContext.getCatalystInstance());

  catalystInstance.initialize();
  mDevSupportManager.onNewReactContextCreated(reactContext);
  mMemoryPressureRouter.addMemoryPressureListener(catalystInstance);
  moveReactContextToCurrentLifecycleState();

  ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_START);
  synchronized (mAttachedRootViews) {
    for (ReactRootView rootView : mAttachedRootViews) {
      attachRootViewToInstance(rootView);
    }
  }
  ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_END);

  ReactInstanceEventListener[] listeners =
    new ReactInstanceEventListener[mReactInstanceEventListeners.size()];
  final ReactInstanceEventListener[] finalListeners =
      mReactInstanceEventListeners.toArray(listeners);

  UiThreadUtil.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          for (ReactInstanceEventListener listener : finalListeners) {
            listener.onReactContextInitialized(reactContext);
          }
        }
      });
  Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
  ReactMarker.logMarker(SETUP_REACT_CONTEXT_END);
  reactContext.runOnJSQueueThread(
      new Runnable() {
        @Override
        public void run() {
          Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
        }
      });
  reactContext.runOnNativeModulesQueueThread(
      new Runnable() {
        @Override
        public void run() {
          Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
        }
      });
}
 
Example #16
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 4 votes vote down vote up
/**
 * @return instance of {@link ReactContext} configured a {@link CatalystInstance} set
 */
private ReactApplicationContext createReactContext(
    JavaScriptExecutor jsExecutor,
    JSBundleLoader jsBundleLoader) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()");
  ReactMarker.logMarker(CREATE_REACT_CONTEXT_START, jsExecutor.getName());
  final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext);

  NativeModuleCallExceptionHandler exceptionHandler = mNativeModuleCallExceptionHandler != null
      ? mNativeModuleCallExceptionHandler
      : mDevSupportManager;
  reactContext.setNativeModuleCallExceptionHandler(exceptionHandler);

  NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false);

  CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder()
    .setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
    .setJSExecutor(jsExecutor)
    .setRegistry(nativeModuleRegistry)
    .setJSBundleLoader(jsBundleLoader)
    .setNativeModuleCallExceptionHandler(exceptionHandler);

  ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_START);
  // CREATE_CATALYST_INSTANCE_END is in JSCExecutor.cpp
  Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createCatalystInstance");
  final CatalystInstance catalystInstance;
  try {
    catalystInstance = catalystInstanceBuilder.build();
  } finally {
    Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
    ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_END);
  }
  if (mJSIModulePackage != null) {
    catalystInstance.addJSIModules(mJSIModulePackage
      .getJSIModules(reactContext, catalystInstance.getJavaScriptContextHolder()));
  }

  if (mBridgeIdleDebugListener != null) {
    catalystInstance.addBridgeIdleDebugListener(mBridgeIdleDebugListener);
  }
  if (Systrace.isTracing(TRACE_TAG_REACT_APPS | TRACE_TAG_REACT_JS_VM_CALLS)) {
    catalystInstance.setGlobalVariable("__RCTProfileIsProfiling", "true");
  }
  ReactMarker.logMarker(ReactMarkerConstants.PRE_RUN_JS_BUNDLE_START);
  catalystInstance.runJSBundle();
  reactContext.initializeWithInstance(catalystInstance);

  return reactContext;
}
 
Example #17
Source File: ScriptLoadUtil.java    From react-native-multibundler with The Unlicense 4 votes vote down vote up
@Nullable
public static String getSourceUrl(CatalystInstance instance) {
    return ReactUtil.getSourceUrl(instance);
}
 
Example #18
Source File: ReactIntegrationTestCase.java    From react-native-GPay with MIT License 4 votes vote down vote up
public void initializeWithInstance(CatalystInstance instance) {
  mInstance = instance;
  mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
  mInstance.addBridgeIdleDebugListener(mBridgeIdleSignaler);
  getContext().initializeWithInstance(mInstance);
}
 
Example #19
Source File: ReactUtil.java    From react-native-multibundler with The Unlicense 4 votes vote down vote up
@Nullable
public static String getSourceUrl(CatalystInstance instance) {
    return instance.getSourceURL();
}
 
Example #20
Source File: AsyncReactActivity.java    From react-native-multibundler with The Unlicense 4 votes vote down vote up
protected void loadScript(final LoadScriptListener loadListener){
    final RnBundle bundle = getBundle();
    /** all buz module is loaded when in debug mode*/
    if(ScriptLoadUtil.MULTI_DEBUG){//当设置成debug模式时,所有需要的业务代码已经都加载好了
        loadListener.onLoadComplete(true,null);
        return;
    }
    ScriptType pathType = bundle.scriptType;
    String scriptPath = bundle.scriptUrl;
    final CatalystInstance instance = ScriptLoadUtil.getCatalystInstance(getReactNativeHost());
    if(pathType== ScriptType.ASSET) {
        ScriptLoadUtil.loadScriptFromAsset(getApplicationContext(),instance,scriptPath,false);
        loadListener.onLoadComplete(true,null);
    }else if(pathType== ScriptType.FILE){
        File scriptFile = new File(getApplicationContext().getFilesDir()
                +File.separator+/*ScriptLoadUtil.REACT_DIR+File.separator+*/scriptPath);
        scriptPath = scriptFile.getAbsolutePath();
        ScriptLoadUtil.loadScriptFromFile(scriptPath,instance,scriptPath,false);
        loadListener.onLoadComplete(true,scriptPath);
    }else if(pathType== ScriptType.NETWORK){
        initView();
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Loading jsBundle");
        dialogBuilder.setCancelable(false);
        final TextView tvv = new TextView(this);
        tvv.setText("conneting");//由于demo中把文件放在了github上,所以http建立连接要花好几秒时间
        tvv.setTextColor(Color.BLACK);
        tvv.setGravity(Gravity.CENTER);
        tvv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        dialogBuilder.setView(tvv);
        mProgressDialog = dialogBuilder.create();
        mProgressDialog.show();
        //由于downloadRNBundle里面的md5参数由组件名代替了,实际开发中需要用到md5校验的需要自己修改
        FileUtils.downloadRNBundle(this.getApplicationContext(), scriptPath, getMainComponentName(), new UpdateProgressListener() {
            @Override
            public void updateProgressChange(final int precent) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(tvv!=null) {
                            tvv.setText(String.valueOf(precent));
                        }
                    }
                });
            }

            @Override
            public void complete(boolean success) {
                if(mProgressDialog!=null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                            mProgressDialog = null;
                        }
                    });
                }
                if(!success){
                    loadListener.onLoadComplete(false,null);
                    return;
                }
                String info = FileUtils.getCurrentPackageMd5(getApplicationContext());
                String bundlePath = FileUtils.getPackageFolderPath(getApplicationContext(),info);
                String jsBundleFilePath = FileUtils.appendPathComponent(bundlePath,bundle.scriptPath);
                File bundleFile = new File(jsBundleFilePath);
                if(bundleFile!=null&&bundleFile.exists()){
                    ScriptLoadUtil.loadScriptFromFile(jsBundleFilePath,instance,jsBundleFilePath,false);
                }else{
                    success=false;
                }
                loadListener.onLoadComplete(success,jsBundleFilePath);
            }
        });
    }
}
 
Example #21
Source File: ReactTestFactory.java    From react-native-GPay with MIT License votes vote down vote up
CatalystInstance build();