下面列出了怎么用com.facebook.react.bridge.ReactContext的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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);
}
/**
* 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;
}
@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);
}
}
}
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);
}
});
}
}
@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();
}
@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);
}
});
}
}
@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);
}
@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);
}
}
/**
* 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);
}
@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;
}
@Override
public void onHostDestroy() {
mapView.dispose();
if (getContext() instanceof ReactContext) {
((ReactContext) getContext()).removeLifecycleEventListener(this);
}
}
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...");
}
}
private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
@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));
}
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;
});
}
@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;
}
private void sendEvent(String name, @Nullable WritableMap event) {
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
name,
event);
}
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)
);
}
@Override
public void sendOnNavigationButtonPressed(String buttonId) {
ReactContext currentReactContext = reactInstanceManager.getCurrentReactContext();
if (currentReactContext != null) {
new EventEmitter(currentReactContext).emitOnNavigationButtonPressed(componentId, buttonId);
}
}
public static View getViewByTag(ReactContext reactContext, int viewTag) {
NativeViewHierarchyManager manager = getNativeViewHierarchyManager(reactContext);
if (manager == null) {
return null;
}
return manager.resolveView(viewTag);
}
@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);
}
}
/**
* 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);
}
}
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);
}
@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);
}
public ReactScrollView(ReactContext context, @Nullable FpsListener fpsListener) {
super(context);
mFpsListener = fpsListener;
mReactBackgroundManager = new ReactViewBackgroundManager(this);
mScroller = getOverScrollerFromParent();
setOnHierarchyChangeListener(this);
setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
}
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);
}
}
@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();
}
@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));
}
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);
}