Java Code Examples for com.facebook.react.bridge.ReactContext

The following examples show how to use com.facebook.react.bridge.ReactContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void testUnregisterTemplateSuccessfully() throws Exception {
    final String templateName = "Template Name";

    when(mNotificationHubUtil.getConnectionString(any(ReactContext.class))).thenReturn("Connection String");
    when(mNotificationHubUtil.getHubName(any(ReactContext.class))).thenReturn("Hub Name");
    when(mNotificationHubUtil.getRegistrationID(any(ReactContext.class))).thenReturn("registrationId");
    when(ReactNativeUtil.createNotificationHub(
            anyString(), anyString(), any(ReactContext.class))).thenReturn(mNotificationHub);

    mHubModule.unregisterTemplate(templateName, mPromise);

    verify(mNotificationHub, times(1)).unregisterTemplate(templateName);
    verify(mNotificationHubUtil, times(1)).setRegistrationID(
            any(ReactContext.class), eq(null));
    verify(mNotificationHubUtil, times(1)).setUUID(
            any(ReactContext.class), eq(null));
    verify(mPromise, times(0)).reject(anyString(), anyString());
    verify(mPromise, times(1)).resolve(AZURE_NOTIFICATION_HUB_UNREGISTERED);
}
 
Example 2
@Test
public void testUnregisterTemplateThrowException() throws Exception {
    final String templateName = "Template Name";
    final Exception unhandledException = new Exception("Unhandled exception");

    when(mNotificationHubUtil.getConnectionString(any(ReactContext.class))).thenReturn("Connection String");
    when(mNotificationHubUtil.getHubName(any(ReactContext.class))).thenReturn("Hub Name");
    when(mNotificationHubUtil.getRegistrationID(any(ReactContext.class))).thenReturn("registrationId");
    when(ReactNativeUtil.createNotificationHub(
            anyString(), anyString(), any(ReactContext.class))).thenReturn(mNotificationHub);
    doThrow(unhandledException).when(mNotificationHub).unregisterTemplate(templateName);

    mHubModule.unregisterTemplate(templateName, mPromise);

    verify(mPromise, times(1)).reject(
            ERROR_NOTIFICATION_HUB,
            unhandledException);
}
 
Example 3
Source Project: react-native-GPay   Source File: HeadlessJsTaskContext.java    License: MIT License 6 votes vote down vote up
/**
 * Start a JS task. Handles invoking {@link AppRegistry#startHeadlessTask} and notifying
 * listeners.
 *
 * @return a unique id representing this task instance.
 */
public synchronized int startTask(final HeadlessJsTaskConfig taskConfig) {
  UiThreadUtil.assertOnUiThread();
  ReactContext reactContext = Assertions.assertNotNull(
    mReactContext.get(),
    "Tried to start a task on a react context that has already been destroyed");
  if (reactContext.getLifecycleState() == LifecycleState.RESUMED &&
    !taskConfig.isAllowedInForeground()) {
    throw new IllegalStateException(
      "Tried to start task " + taskConfig.getTaskKey() +
        " while in foreground, but this is not allowed.");
  }
  final int taskId = mLastTaskId.incrementAndGet();
  mActiveTasks.add(taskId);
  reactContext.getJSModule(AppRegistry.class)
    .startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData());
  if (taskConfig.getTimeout() > 0) {
    scheduleTaskTimeout(taskId, taskConfig.getTimeout());
  }
  for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) {
    listener.onHeadlessJsTaskStart(taskId);
  }
  return taskId;
}
 
Example 4
@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 5
Source Project: react-native-GPay   Source File: ReactRootView.java    License: MIT License 6 votes vote down vote up
private void updateRootLayoutSpecs(final int widthMeasureSpec, final int heightMeasureSpec) {
  if (mReactInstanceManager == null) {
    FLog.w(
        ReactConstants.TAG,
        "Unable to update root layout specs for uninitialized ReactInstanceManager");
    return;
  }
  final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext();
  if (reactApplicationContext != null) {
    reactApplicationContext.runOnNativeModulesQueueThread(
        new GuardedRunnable(reactApplicationContext) {
          @Override
          public void runGuarded() {
            UIManagerHelper
              .getUIManager(reactApplicationContext, getUIManagerType())
              .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec);
          }
        });
  }
}
 
Example 6
@Test
public void testRegisterExistingUUID() {
    when(mConfig.getString(KEY_REGISTRATION_CONNECTIONSTRING)).thenReturn(KEY_REGISTRATION_CONNECTIONSTRING);
    when(mConfig.getString(KEY_REGISTRATION_HUBNAME)).thenReturn(KEY_REGISTRATION_HUBNAME);
    when(mConfig.getString(KEY_REGISTRATION_SENDERID)).thenReturn(KEY_REGISTRATION_SENDERID);
    when(mNotificationHubUtil.getUUID(any(ReactContext.class))).thenReturn(
            PowerMockito.mock(String.class));

    mHubModule.register(mConfig, mPromise);

    verify(mNotificationHubUtil, times(1)).getUUID(any(ReactContext.class));
    verify(mNotificationHubUtil, times(0)).setUUID(
            any(ReactContext.class), anyString());
    PowerMockito.verifyStatic((ReactNativeUtil.class), times(0));
    ReactNativeUtil.genUUID();
}
 
Example 7
Source Project: react-native-screens   Source File: Screen.java    License: MIT License 6 votes vote down vote up
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
  if (changed) {
    final int width = r - l;
    final int height = b - t;
    final ReactContext reactContext = (ReactContext) getContext();
    reactContext.runOnNativeModulesQueueThread(
            new GuardedRunnable(reactContext) {
              @Override
              public void runGuarded() {
                reactContext.getNativeModule(UIManagerModule.class)
                        .updateNodeSize(getId(), width, height);
              }
            });
  }
}
 
Example 8
Source Project: react-native-GPay   Source File: ReactRootView.java    License: MIT License 6 votes vote down vote up
@Override
public void onChildStartedNativeGesture(MotionEvent androidEvent) {
  if (mReactInstanceManager == null || !mIsAttachedToInstance ||
    mReactInstanceManager.getCurrentReactContext() == null) {
    FLog.w(
      ReactConstants.TAG,
      "Unable to dispatch touch to JS as the catalyst instance has not been attached");
    return;
  }
  if (mJSTouchDispatcher == null) {
    FLog.w(
      ReactConstants.TAG,
      "Unable to dispatch touch to JS before the dispatcher is available");
    return;
  }
  ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
  EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
  mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher);
}
 
Example 9
@ReactMethod
public void unregister(Promise promise) {
    ReactNativeNotificationHubUtil notificationHubUtil = ReactNativeNotificationHubUtil.getInstance();

    ReactContext reactContext = getReactApplicationContext();
    String connectionString = notificationHubUtil.getConnectionString(reactContext);
    String hubName = notificationHubUtil.getHubName(reactContext);
    String registrationId = notificationHubUtil.getRegistrationID(reactContext);

    if (connectionString == null || hubName == null || registrationId == null) {
        promise.reject(ERROR_NOT_REGISTERED, ERROR_NOT_REGISTERED_DESC);
        return;
    }

    NotificationHub hub = ReactNativeUtil.createNotificationHub(hubName, connectionString, reactContext);
    try {
        hub.unregister();
        notificationHubUtil.setRegistrationID(reactContext, null);
        notificationHubUtil.setUUID(reactContext, null);
        promise.resolve(AZURE_NOTIFICATION_HUB_UNREGISTERED);
    } catch (Exception e) {
        promise.reject(ERROR_NOTIFICATION_HUB, e);
    }
}
 
Example 10
Source Project: react-native-GPay   Source File: ReactIdleDetectionUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Waits for both the UI thread and bridge to be idle. It determines this by waiting for the
 * bridge to become idle, then waiting for the UI thread to become idle, then checking if the
 * bridge is idle again (if the bridge was idle before and is still idle after running the UI
 * thread to idle, then there are no more events to process in either place).
 * <p/>
 * Also waits for any Choreographer callbacks to run after the initial sync since things like UI
 * events are initiated from Choreographer callbacks.
 */
public static void waitForBridgeAndUIIdle(
    ReactBridgeIdleSignaler idleSignaler,
    final ReactContext reactContext,
    long timeoutMs) {
  UiThreadUtil.assertNotOnUiThread();

  long startTime = SystemClock.uptimeMillis();
  waitInner(idleSignaler, timeoutMs);

  long timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
  waitForChoreographer(timeToWait);
  waitForJSIdle(reactContext);

  timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
  waitInner(idleSignaler, timeToWait);
  timeToWait = Math.max(1, timeoutMs - (SystemClock.uptimeMillis() - startTime));
  waitForChoreographer(timeToWait);
}
 
Example 11
Source Project: react-native-yandexmapkit   Source File: RNYandexMapKitView.java    License: MIT License 6 votes vote down vote up
@Override
public boolean onFinishGeoCode(GeoCode geoCode) {
    if (geoCode != null) {
        WritableMap payload = Arguments.createMap();
        payload.putString("displayName", geoCode.getDisplayName());
        payload.putString("kind", geoCode.getKind());
        payload.putString("title", geoCode.getTitle());
        payload.putString("subtitle", geoCode.getSubtitle());
        WritableMap point = Arguments.createMap();
        GeoPoint geoPoint = geoCode.getGeoPoint();
        point.putDouble("latitude", geoPoint.getLat());
        point.putDouble("longitude", geoPoint.getLon());
        payload.putMap("point", point);

        ReactContext reactContext = (ReactContext) getContext();
        reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(this.getId(), GEOCODING_EVENT, payload);
    }
    return true;
}
 
Example 12
Source Project: react-native-arcgis-mapview   Source File: RNAGSMapView.java    License: MIT License 5 votes vote down vote up
@Override
public void onHostDestroy() {
    mapView.dispose();
    if (getContext() instanceof ReactContext) {
        ((ReactContext) getContext()).removeLifecycleEventListener(this);
    }
}
 
Example 13
Source Project: react-native-gps   Source File: RNLocationModule.java    License: MIT License 5 votes vote down vote up
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
  if (reactContext.hasActiveCatalystInstance()) {
    reactContext
      .getJSModule(RCTDeviceEventEmitter.class)
      .emit(eventName, params);
  } else {
    Log.i(TAG, "Waiting for CatalystInstance...");
  }
}
 
Example 14
private void sendEvent(ReactContext reactContext,
                       String eventName,
                       @Nullable WritableMap params) {
    reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
}
 
Example 15
@Test
public void testRegisterHasChannelEnableLights() {
    final boolean channelEnableLights = true;

    when(mConfig.getString(KEY_REGISTRATION_CONNECTIONSTRING)).thenReturn(KEY_REGISTRATION_CONNECTIONSTRING);
    when(mConfig.getString(KEY_REGISTRATION_HUBNAME)).thenReturn(KEY_REGISTRATION_HUBNAME);
    when(mConfig.getString(KEY_REGISTRATION_SENDERID)).thenReturn(KEY_REGISTRATION_SENDERID);
    when(mConfig.hasKey(KEY_REGISTRATION_CHANNELENABLELIGHTS)).thenReturn(true);
    when(mConfig.getBoolean(KEY_REGISTRATION_CHANNELENABLELIGHTS)).thenReturn(channelEnableLights);

    mHubModule.register(mConfig, mPromise);

    verify(mNotificationHubUtil, times(1)).setChannelEnableLights(
            any(ReactContext.class), eq(channelEnableLights));
}
 
Example 16
Source Project: react-native-image-filter-kit   Source File: TempFileUtils.java    License: MIT License 5 votes vote down vote up
static void writeFile(
  @NonNull final ReactContext context,
  @NonNull final CloseableReference<CloseableImage> ref,
  @NonNull final Functor.Arity1<String> sendUri,
  @NonNull final Functor.Arity1<String> sendError
) {
  CloseableReference<CloseableImage> cloned = ref.clone();

  Task.callInBackground((Callable<Void>) () -> {
    try {
      final File outputFile = createFile(context);
      final FileOutputStream fos = new FileOutputStream(outputFile);
      final Bitmap bitmap = ((CloseableBitmap) cloned.get()).getUnderlyingBitmap();

      bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

      final String path = Uri.fromFile(outputFile).toString();

      FLog.w(ReactConstants.TAG, "ImageFilterKit: created file " + path);

      Task.call((Callable<Void>) () -> {
        sendUri.call(path);

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } catch (Exception e) {
      Task.call((Callable<Void>) () -> {
        sendError.call(e.getMessage());

        return null;
      }, UiThreadImmediateExecutorService.getInstance());

    } finally {
      CloseableReference.closeSafely(cloned);
    }

    return null;
  });
}
 
Example 17
@TargetApi(23)
private boolean isDark() {
    Activity activity = ((ReactContext) getContext()).getCurrentActivity();
    // fix activity NPE
    if (activity == null) {
        return true;
    }
    return (activity.getWindow().getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0;
}
 
Example 18
private void sendEvent(String name, @Nullable WritableMap event) {
    ReactContext reactContext = (ReactContext) getContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                    getId(),
                    name,
                    event);
}
 
Example 19
private void propagateSelectionChanges(int selStart, int selEnd) {
    if (!shouldHandleOnSelectionChange) {
        return;
    }
    String content = toHtml(false);
    ReactContext reactContext = (ReactContext) getContext();
    EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
    eventDispatcher.dispatchEvent(
            new ReactAztecSelectionChangeEvent(getId(), content, selStart, selEnd)
    );
}
 
Example 20
Source Project: react-native-navigation   Source File: ReactView.java    License: MIT License 5 votes vote down vote up
@Override
public void sendOnNavigationButtonPressed(String buttonId) {
       ReactContext currentReactContext = reactInstanceManager.getCurrentReactContext();
       if (currentReactContext != null) {
           new EventEmitter(currentReactContext).emitOnNavigationButtonPressed(componentId, buttonId);
       }
}
 
Example 21
public static View getViewByTag(ReactContext reactContext, int viewTag) {
    NativeViewHierarchyManager manager = getNativeViewHierarchyManager(reactContext);
    if (manager == null) {
        return null;
    }
    return manager.resolveView(viewTag);
}
 
Example 22
@ReactMethod
public void requestPermissions(String senderID) {
    ReactContext reactContext = getReactApplicationContext();

    Intent GCMService = new Intent(reactContext, RNPushNotificationRegistrationService.class);

    try {
        GCMService.putExtra("senderID", senderID);
        reactContext.startService(GCMService);
    } catch (Exception e) {
        Log.d("EXCEPTION SERVICE::::::", "requestPermissions: " + e);
    }
}
 
Example 23
Source Project: react-native-GPay   Source File: ReactRootView.java    License: 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 24
Source Project: react-native-youtube   Source File: YouTubeView.java    License: MIT License 5 votes vote down vote up
public void receivedError(String param) {
    WritableMap event = Arguments.createMap();
    ReactContext reactContext = getReactContext();
    event.putString("error", param);
    event.putInt("target", getId());
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "error", event);
}
 
Example 25
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
    WritableMap event = Arguments.createMap();
    event.putInt("state", newState);
    ReactContext reactContext = (ReactContext) bottomSheet.getContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(bottomSheet.getId(), "topStateChange", event);
}
 
Example 26
Source Project: react-native-GPay   Source File: ReactScrollView.java    License: MIT License 5 votes vote down vote up
public ReactScrollView(ReactContext context, @Nullable FpsListener fpsListener) {
  super(context);
  mFpsListener = fpsListener;
  mReactBackgroundManager = new ReactViewBackgroundManager(this);

  mScroller = getOverScrollerFromParent();
  setOnHierarchyChangeListener(this);
  setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
}
 
Example 27
Source Project: react-native-GPay   Source File: ReactAppTestActivity.java    License: MIT License 5 votes vote down vote up
private ReactContext waitForReactContext() {
  Assertions.assertNotNull(mReactInstanceManager);

  try {
    while (true) {
      ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
      if (reactContext != null) {
        return reactContext;
      }
      Thread.sleep(100);
    }
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example 28
Source Project: react-native-multibundler   Source File: ScriptLoadUtil.java    License: 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 29
@Test
public void testRegisterHasChannelImportance() {
    final int channelImportance = 1;

    when(mConfig.getString(KEY_REGISTRATION_CONNECTIONSTRING)).thenReturn(KEY_REGISTRATION_CONNECTIONSTRING);
    when(mConfig.getString(KEY_REGISTRATION_HUBNAME)).thenReturn(KEY_REGISTRATION_HUBNAME);
    when(mConfig.getString(KEY_REGISTRATION_SENDERID)).thenReturn(KEY_REGISTRATION_SENDERID);
    when(mConfig.hasKey(KEY_REGISTRATION_CHANNELIMPORTANCE)).thenReturn(true);
    when(mConfig.getInt(KEY_REGISTRATION_CHANNELIMPORTANCE)).thenReturn(channelImportance);

    mHubModule.register(mConfig, mPromise);

    verify(mNotificationHubUtil, times(1)).setChannelImportance(
            any(ReactContext.class), eq(channelImportance));
}
 
Example 30
Source Project: react-native-youtube   Source File: YouTubeView.java    License: MIT License 5 votes vote down vote up
public void didChangeToState(String param) {
    WritableMap event = Arguments.createMap();
    event.putString("state", param);
    event.putInt("target", getId());
    ReactContext reactContext = getReactContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "state", event);
}