private static void waitForJSIdle(ReactContext reactContext) { if (!reactContext.hasActiveCatalystInstance()) { return; } final CountDownLatch latch = new CountDownLatch(1); reactContext.runOnJSQueueThread( new Runnable() { @Override public void run() { latch.countDown(); } }); try { if (!latch.await(5000, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Timed out waiting for JS thread"); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * 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; }
private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scrollEventType) { View contentView = scrollView.getChildAt(0); if (contentView == null) { return; } ReactContext reactContext = (ReactContext) scrollView.getContext(); reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( ScrollEvent.obtain( scrollView.getId(), scrollEventType, scrollView.getScrollX(), scrollView.getScrollY(), contentView.getWidth(), contentView.getHeight(), scrollView.getWidth(), scrollView.getHeight())); }
SocketClient(ReadableMap params, ReactContext reactContext) { //String addr, int port, boolean autoReconnect mReactContext = reactContext; dstAddress = params.getString("address"); dstPort = params.getInt("port"); if (params.hasKey("reconnect")) { reconnectOnClose = params.getBoolean("reconnect"); } if (params.hasKey("maxReconnectAttempts")) { maxReconnectAttempts = params.getInt("maxReconnectAttempts"); } if (params.hasKey("reconnectDelay")) { reconnectDelay = params.getInt("reconnectDelay"); } Thread socketClientThread = new Thread(new SocketClientThread()); socketClientThread.start(); }
private CropTask( ReactContext context, String uri, int x, int y, int width, int height, Callback success, Callback error) { super(context); if (x < 0 || y < 0 || width <= 0 || height <= 0) { throw new JSApplicationIllegalArgumentException(String.format( "Invalid crop rectangle: [%d, %d, %d, %d]", x, y, width, height)); } mContext = context; mUri = uri; mX = x; mY = y; mWidth = width; mHeight = height; mSuccess = success; mError = error; }
void setup(ReactContext reactContext) { this.setOrientation(VERTICAL); this.reactViewPager = new ReactViewPager(reactContext); this.reactViewPager.setParentIdCallback(new ReactViewPager.ParentIdCallback() { @Override public int getParentId() { return getId(); } }); this.tabLayout = new TabLayout(reactContext); this.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); LayoutParams viewPagerParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1); LayoutParams tabParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); this.addView(tabLayout, tabParams); this.addView(reactViewPager, viewPagerParams); tabLayout.setupWithViewPager(reactViewPager); }
@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!"); catalystInstance.callFunction("JavaScriptVisibleToJava", "alert", params); } } }
@Override public void onDestroy() { super.onDestroy(); if (getReactNativeHost().hasInstance()) { ReactInstanceManager reactInstanceManager = getReactNativeHost().getReactInstanceManager(); ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext != null) { HeadlessJsTaskContext headlessJsTaskContext = HeadlessJsTaskContext.getInstance(reactContext); headlessJsTaskContext.removeTaskEventListener(this); } } if (sWakeLock != null) { sWakeLock.release(); } }
@Override protected void onSizeChanged(final int w, final int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (getChildCount() > 0) { final int viewTag = getChildAt(0).getId(); ReactContext reactContext = (ReactContext) getContext(); reactContext.runOnNativeModulesQueueThread( new GuardedRunnable(reactContext) { @Override public void runGuarded() { ((ReactContext) getContext()).getNativeModule(UIManagerModule.class) .updateNodeSize(viewTag, w, h); } }); } }
/** * Get the default Fresco configuration builder. * Allows adding of configuration options in addition to the default values. * * @return {@link ImagePipelineConfig.Builder} that has been initialized with default values */ public static ImagePipelineConfig.Builder getDefaultConfigBuilder(ReactContext context) { HashSet<RequestListener> requestListeners = new HashSet<>(); requestListeners.add(new SystraceRequestListener()); OkHttpClient client = OkHttpClientProvider.createClient(); // make sure to forward cookies for any requests via the okHttpClient // so that image requests to endpoints that use cookies still work CookieJarContainer container = (CookieJarContainer) client.cookieJar(); ForwardingCookieHandler handler = new ForwardingCookieHandler(context); container.setCookieJar(new JavaNetCookieJar(handler)); return OkHttpImagePipelineConfigFactory .newBuilder(context.getApplicationContext(), client) .setNetworkFetcher(new ReactOkHttpNetworkFetcher(client)) .setDownsampleEnabled(false) .setRequestListeners(requestListeners); }
public void shutDownContext() { if (mInstance != null) { final ReactContext contextToDestroy = mReactContext; mReactContext = null; mInstance = null; final SimpleSettableFuture<Void> semaphore = new SimpleSettableFuture<>(); UiThreadUtil.runOnUiThread(new Runnable() { @Override public void run() { if (contextToDestroy != null) { contextToDestroy.destroy(); } semaphore.set(null); } }); semaphore.getOrThrow(); } }
/** * 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); }
private void handleSuccess() { WritableMap evt = Arguments.createMap(); ReactContext ctx = (ReactContext) getContext(); ctx.getJSModule(RCTEventEmitter.class).receiveEvent( getId(), "onLoadSuccess", evt); }
@Override public void onSizeChanged(TweetView view, final int width, final int height) { Log.d(TAG, "TweetView changed size: " + width + ", " + height); ReactContext ctx = (ReactContext) view.getContext(); final UIManagerModule uiManager = ctx.getNativeModule(UIManagerModule.class); final int reactTag = view.getReactTag(); ctx.runOnNativeModulesQueueThread(new Runnable() { @Override public void run() { uiManager.updateNodeSize(reactTag, width, height); } }); }
@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); }
private void tearDownReactContext(ReactContext reactContext) { UiThreadUtil.assertOnUiThread(); if (mLifecycleState == LifecycleState.RESUMED) { reactContext.onHostPause(); } for (ReactRootView rootView : mAttachedRootViews) { detachViewFromInstance(rootView, reactContext.getCatalystInstance()); } reactContext.destroy(); mDevSupportManager.onReactInstanceDestroyed(reactContext); mMemoryPressureRouter.removeMemoryPressureListener(reactContext.getCatalystInstance()); }
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); }
@ReactMethod public void requestPermissions(String leancloudAppId, String leancloudAppKey) { ReactContext reactContext = getReactApplicationContext(); Intent AVService = new Intent(reactContext, RNPushNotificationRegistrationService.class); AVService.putExtra("leancloudAppId", leancloudAppId); AVService.putExtra("leancloudAppKey", leancloudAppKey); reactContext.startService(AVService); }
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); } }
public ReactViewPager(ReactContext reactContext) { super(reactContext); mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mIsCurrentItemFromJs = false; setOnPageChangeListener(new PageChangeListener()); setAdapter(new Adapter()); }
private GetBase64Task( ReactContext reactContext, String uri, Callback success, Callback error) { super(reactContext); mUri = uri; mSuccess = success; mError = error; }
/** * Propogates image load events to javascript if the hosting view is still alive. * * @param reactTag The view id. * @param imageLoadEvent The event type. */ public void dispatchImageLoadEvent(int reactTag, int imageLoadEvent) { FlatViewGroup view = get(); if (view == null) { return; } ReactContext reactContext = ((ReactContext) view.getContext()); UIManagerModule uiManagerModule = reactContext.getNativeModule(UIManagerModule.class); uiManagerModule.getEventDispatcher().dispatchEvent( new ImageLoadEvent(reactTag, imageLoadEvent)); }
@Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { ReactContext reactContext = (ReactContext) view.getContext(); @SuppressLint("DefaultLocale") String date = String.format("%d-%d-%d", year, monthOfYear+1, dayOfMonth); reactContext.getNativeModule(UIManagerModule.class) .getEventDispatcher() .dispatchEvent(new RNDatePickerComponentEvent(view.getId(), date)); }
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { if (reactContext.hasActiveCatalystInstance()) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } else { Log.i(TAG, "Waiting for CatalystInstance..."); } }
private void sendEvent(ReactContext reactContext, String eventName, WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getReactNativeHost().getReactInstanceManager().addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext context) { getWindow().getDecorView().setBackgroundColor(Color.WHITE); } }); }
public ReactTextInputTextWatcher( final ReactContext reactContext, final ReactEditText editText) { mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mEditText = editText; mPreviousText = null; }
private void dispatchJSTouchEvent(MotionEvent event) { 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; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class) .getEventDispatcher(); mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher); }
@Override public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { ReactContext reactContext = (ReactContext) seekbar.getContext(); reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( new ReactSliderEvent( seekbar.getId(), ((ReactSlider) seekbar).toRealProgress(progress), fromUser)); }
@Override public void onStopTrackingTouch(SeekBar seekbar) { ReactContext reactContext = (ReactContext) seekbar.getContext(); reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher().dispatchEvent( new ReactSlidingCompleteEvent( seekbar.getId(), ((ReactSlider) seekbar).toRealProgress(seekbar.getProgress()))); }
public void setShouldNotifyLoadEvents(boolean shouldNotify) { if (!shouldNotify) { mControllerListener = null; } else { final EventDispatcher mEventDispatcher = ((ReactContext) getContext()). getNativeModule(UIManagerModule.class).getEventDispatcher(); mControllerListener = new BaseControllerListener<ImageInfo>() { @Override public void onSubmit(String id, Object callerContext) { mEventDispatcher.dispatchEvent( new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_START)); } @Override public void onFinalImageSet( String id, @Nullable final ImageInfo imageInfo, @Nullable Animatable animatable) { if (imageInfo != null) { mEventDispatcher.dispatchEvent( new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD, mImageSource.getSource(), imageInfo.getWidth(), imageInfo.getHeight())); mEventDispatcher.dispatchEvent( new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_END)); } } @Override public void onFailure(String id, Throwable throwable) { mEventDispatcher.dispatchEvent( new ImageLoadEvent(getId(), ImageLoadEvent.ON_ERROR)); mEventDispatcher.dispatchEvent( new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_END)); } }; } mIsDirty = true; }