com.facebook.react.bridge.ReactContext Java Examples

The following examples show how to use com.facebook.react.bridge.ReactContext. 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: ReactNativeNotificationHubModuleTest.java    From react-native-azurenotificationhub with MIT License 6 votes vote down vote up
@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
Source File: ReactRootView.java    From react-native-GPay with 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 #3
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 #4
Source File: ReactNativeNotificationHubModuleTest.java    From react-native-azurenotificationhub with MIT License 6 votes vote down vote up
@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 #5
Source File: HeadlessJsTaskContext.java    From react-native-GPay with 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 #6
Source File: ReactIdleDetectionUtil.java    From react-native-GPay with 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 #7
Source File: ReactNativeNotificationHubModuleTest.java    From react-native-azurenotificationhub with MIT License 6 votes vote down vote up
@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 #8
Source File: ReactRootView.java    From react-native-GPay with 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
Source File: ReactNativeNotificationHubModule.java    From react-native-azurenotificationhub with MIT License 6 votes vote down vote up
@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 File: RNYandexMapKitView.java    From react-native-yandexmapkit with 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 #11
Source File: Screen.java    From react-native-screens with 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 #12
Source File: ArcGISMapManager.java    From react-native-arcgis-sdk-demo with Apache License 2.0 5 votes vote down vote up
private void emitExtentChange() {
    Log.v(REACT_CLASS, "emit extent change");

    WritableMap event = Arguments.createMap();
    event.putDouble("x", mapView.getCenter().getX());
    event.putDouble("y", mapView.getCenter().getY());
    event.putDouble("scale", mapView.getScale());

    ReactContext reactContext = (ReactContext) mapView.getContext();
    reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("onExtentChange", event);
}
 
Example #13
Source File: InCallManagerModule.java    From react-native-incall-manager with ISC License 5 votes vote down vote up
private String _checkPermission(String targetPermission) {
    try {
        ReactContext reactContext = getReactApplicationContext();
        if (ContextCompat.checkSelfPermission(reactContext, targetPermission) == PackageManager.PERMISSION_GRANTED) {
            return "granted";
        } else {
            return "denied";
        }
    } catch (Exception e) {
        Log.d(TAG, "_checkPermission() catch");
        return "denied";
    }
}
 
Example #14
Source File: ReactSwitchManager.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  ReactContext reactContext = (ReactContext) buttonView.getContext();
  reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent(
      new ReactSwitchEvent(
          buttonView.getId(),
          isChecked));
}
 
Example #15
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void toggleElementInspector() {
  ReactContext currentContext = getCurrentReactContext();
  if (currentContext != null) {
    currentContext
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit("toggleElementInspector", null);
  }
}
 
Example #16
Source File: RNAGSMapView.java    From react-native-arcgis-mapview with MIT License 5 votes vote down vote up
@Override
public void onHostDestroy() {
    mapView.dispose();
    if (getContext() instanceof ReactContext) {
        ((ReactContext) getContext()).removeLifecycleEventListener(this);
    }
}
 
Example #17
Source File: AppBarLayoutManager.java    From react-native-collapsing-toolbar with MIT License 5 votes vote down vote up
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    WritableMap event = Arguments.createMap();
    event.putDouble("offset", verticalOffset);
    ReactContext reactContext = (ReactContext) appBarLayout.getContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(appBarLayout.getId(), "topOffsetChanged", event);
}
 
Example #18
Source File: ReactScrollView.java    From react-native-GPay with 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 #19
Source File: TranslucentModalHostView.java    From react-native-modal-translucent with MIT License 5 votes vote down vote up
@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 #20
Source File: YouTubeView.java    From react-native-youtube with 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 #21
Source File: RNPushNotification.java    From react-native-push-notification-CE with MIT License 5 votes vote down vote up
@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 #22
Source File: RNViewUtils.java    From react-native-sensors-analytics with Apache License 2.0 5 votes vote down vote up
public static View getViewByTag(ReactContext reactContext, int viewTag) {
    NativeViewHierarchyManager manager = getNativeViewHierarchyManager(reactContext);
    if (manager == null) {
        return null;
    }
    return manager.resolveView(viewTag);
}
 
Example #23
Source File: StepSensor.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public StepSensor(ReactContext reactContext, Activity activity) {
    this.mReactContext = reactContext;
    this.activity = activity;

    boolean stepCounter = hasStepCounter();
    Log.i(TAG, "hasStepCounter: " + stepCounter);

    if(stepCounter) {
        mSensorManager = (SensorManager) reactContext.getSystemService(reactContext.SENSOR_SERVICE);
    }
}
 
Example #24
Source File: YouTubeView.java    From react-native-youtube with 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);
}
 
Example #25
Source File: ReactNativeNotificationHubModuleTest.java    From react-native-azurenotificationhub with MIT License 5 votes vote down vote up
@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 #26
Source File: RNPublisherBannerViewManager.java    From react-native-admob with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void sendEvent(String name, @Nullable WritableMap event) {
    ReactContext reactContext = (ReactContext) getContext();
    reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
                    getId(),
                    name,
                    event);
}
 
Example #27
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 #28
Source File: ReactAppTestActivity.java    From react-native-GPay with 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 #29
Source File: ReactAztecText.java    From react-native-aztec with GNU General Public License v2.0 5 votes vote down vote up
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 #30
Source File: ReactView.java    From react-native-navigation with 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);
       }
}