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

The following are top voted examples for showing how to use com.facebook.react.bridge.Callback. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: RNLearn_Project1   File: AsyncStorageModule.java   View source code 6 votes vote down vote up
/**
 * Clears the database.
 */
@ReactMethod
public void clear(final Callback callback) {
  new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
    @Override
    protected void doInBackgroundGuarded(Void... params) {
      if (!mReactDatabaseSupplier.ensureDatabase()) {
        callback.invoke(AsyncStorageErrorUtil.getDBError(null));
        return;
      }
      try {
        mReactDatabaseSupplier.clear();
        callback.invoke();
      } catch (Exception e) {
        FLog.w(ReactConstants.TAG, e.getMessage(), e);
        callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()));
      }
    }
  }.execute();
}
 
Example 2
Project: react-native-udesk   File: UdeskModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void createCommodity (final ReadableMap options, final Callback callback) { // 都是必传的(productDetail 可选)
    cleanResponse();
    if (!hasAndNotEmpty(options, "productTitle")) {
        invokeError(callback, "title is empty");
        return;
    }
    if (!hasAndNotEmpty(options, "productImageUrl")) {
        invokeError(callback, "imageUrl is empty");
        return;
    }
    if (!hasAndNotEmpty(options, "productURL")) {
        invokeError(callback, "productUrl is empty");
        return;
    }
    UdeskCommodityItem item = new UdeskCommodityItem();
    item.setTitle(options.getString("productTitle"));// 商品主标题
    if (hasAndNotEmpty(options, "productDetail")) {
        item.setSubTitle(options.getString("productDetail"));//商品副标题
    }
    item.setThumbHttpUrl(options.getString("productImageUrl"));// 左侧图片
    item.setCommodityUrl(options.getString("productURL"));// 商品网络链接
    UdeskSDKManager.getInstance().setCommodity(item);
    UdeskSDKManager.getInstance().toLanuchChatAcitvity(mReactContext.getApplicationContext());
}
 
Example 3
Project: RNLearn_Project1   File: FlatUIViewOperationQueue.java   View source code 6 votes vote down vote up
private MeasureVirtualView(
    int reactTag,
    float scaledX,
    float scaledY,
    float scaledWidth,
    float scaledHeight,
    boolean relativeToWindow,
    Callback callback) {
  mReactTag = reactTag;
  mScaledX = scaledX;
  mScaledY = scaledY;
  mScaledWidth = scaledWidth;
  mScaledHeight = scaledHeight;
  mCallback = callback;
  mRelativeToWindow = relativeToWindow;
}
 
Example 4
Project: RNLearn_Project1   File: UIImplementation.java   View source code 6 votes vote down vote up
/**
 * Measures the view specified by tag relative to the given ancestorTag. This means that the
 * returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
 * given outputBuffer. We allow ancestor view and measured view to be the same, in which case
 * the position always will be (0, 0) and method will only measure the view dimensions.
 */
public void measureLayout(
    int tag,
    int ancestorTag,
    Callback errorCallback,
    Callback successCallback) {
  try {
    measureLayout(tag, ancestorTag, mMeasureBuffer);
    float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]);
    float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]);
    float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]);
    float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]);
    successCallback.invoke(relativeX, relativeY, width, height);
  } catch (IllegalViewOperationException e) {
    errorCallback.invoke(e.getMessage());
  }
}
 
Example 5
Project: react-native-simple-download-manager   File: ReactNativeDownloadManagerModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void attachOnCompleteListener(String downloadId, Callback onComplete) {
    try {
        long dloadId = Long.parseLong(downloadId);
        appDownloads.put(dloadId, onComplete);
        WritableMap status = downloader.checkDownloadStatus(Long.parseLong(downloadId));
        ArrayList<String> alreadyDoneStatuses = new ArrayList<>(Arrays.asList("STATUS_SUCCESSFUL", "STATUS_FAILED"));
        String currentStatus = status.getString("status");
        if (alreadyDoneStatuses.contains(currentStatus)) {
            appDownloads.remove(dloadId);
            onComplete.invoke(null, status);
        }
    } catch (Exception e) {
        onComplete.invoke(e.getMessage(), null);
    }
}
 
Example 6
Project: RNLearn_Project1   File: FlatUIViewOperationQueue.java   View source code 6 votes vote down vote up
public void enqueueMeasureVirtualView(
    int reactTag,
    float scaledX,
    float scaledY,
    float scaledWidth,
    float scaledHeight,
    boolean relativeToWindow,
    Callback callback) {
  enqueueUIOperation(new MeasureVirtualView(
      reactTag,
      scaledX,
      scaledY,
      scaledWidth,
      scaledHeight,
      relativeToWindow,
      callback));
}
 
Example 7
Project: RNLearn_Project1   File: NativeAnimatedModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void startAnimatingNode(
    final int animationId,
    final int animatedNodeTag,
    final ReadableMap animationConfig,
    final Callback endCallback) {
  mOperations.add(new UIThreadOperation() {
    @Override
    public void execute(NativeAnimatedNodesManager animatedNodesManager) {
      animatedNodesManager.startAnimatingNode(
        animationId,
        animatedNodeTag,
        animationConfig,
        endCallback);
    }
  });
}
 
Example 8
Project: RNLearn_Project1   File: ForwardingCookieHandler.java   View source code 6 votes vote down vote up
public void clearCookies(final Callback callback) {
  if (USES_LEGACY_STORE) {
    new GuardedResultAsyncTask<Boolean>(mContext) {
      @Override
      protected Boolean doInBackgroundGuarded() {
        getCookieManager().removeAllCookie();
        mCookieSaver.onCookiesModified();
        return true;
      }

      @Override
      protected void onPostExecuteGuarded(Boolean result) {
        callback.invoke(result);
      }
    }.execute();
  } else {
    clearCookiesAsync(callback);
  }
}
 
Example 9
Project: react-native-pybwifiparam   File: PybWifiParamModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void getWifiSSID(Callback callback){
    String SSID;
    Context context = this.getReactApplicationContext();
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if(networkInfo != null && networkInfo.isConnected()){
        WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        SSID = wifiInfo.getSSID();
        if(SSID.startsWith("\"") && SSID.endsWith("\""))
            SSID = SSID.substring(1, SSID.length()-1);
        callback.invoke(null, SSID);
    }
    else{
        callback.invoke("Error: unable to retrieve SSID.", null);
    }
}
 
Example 10
Project: RNLearn_Project1   File: ImageEditingManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: RNLearn_Project1   File: ImageEditingManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: RNLearn_Project1   File: ForwardingCookieHandler.java   View source code 6 votes vote down vote up
public void clearCookies(final Callback callback) {
  if (USES_LEGACY_STORE) {
    new GuardedResultAsyncTask<Boolean>(mContext) {
      @Override
      protected Boolean doInBackgroundGuarded() {
        getCookieManager().removeAllCookie();
        mCookieSaver.onCookiesModified();
        return true;
      }

      @Override
      protected void onPostExecuteGuarded(Boolean result) {
        callback.invoke(result);
      }
    }.execute();
  } else {
    clearCookiesAsync(callback);
  }
}
 
Example 13
Project: RNLearn_Project1   File: UIImplementation.java   View source code 6 votes vote down vote up
/**
 * Measures the view specified by tag relative to the given ancestorTag. This means that the
 * returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
 * given outputBuffer. We allow ancestor view and measured view to be the same, in which case
 * the position always will be (0, 0) and method will only measure the view dimensions.
 */
public void measureLayout(
    int tag,
    int ancestorTag,
    Callback errorCallback,
    Callback successCallback) {
  try {
    measureLayout(tag, ancestorTag, mMeasureBuffer);
    float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]);
    float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]);
    float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]);
    float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]);
    successCallback.invoke(relativeX, relativeY, width, height);
  } catch (IllegalViewOperationException e) {
    errorCallback.invoke(e.getMessage());
  }
}
 
Example 14
Project: RNLearn_Project1   File: NativeViewHierarchyManager.java   View source code 6 votes vote down vote up
/**
 * Show a {@link PopupMenu}.
 *
 * @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this
 *        needs to be the tag of a native view (shadow views can not be anchors)
 * @param items the menu items as an array of strings
 * @param success will be called with the position of the selected item as the first argument, or
 *        no arguments if the menu is dismissed
 */
public void showPopupMenu(int reactTag, ReadableArray items, Callback success) {
  UiThreadUtil.assertOnUiThread();
  View anchor = mTagsToViews.get(reactTag);
  if (anchor == null) {
    throw new JSApplicationIllegalArgumentException("Could not find view with tag " + reactTag);
  }
  PopupMenu popupMenu = new PopupMenu(getReactContextForView(reactTag), anchor);

  Menu menu = popupMenu.getMenu();
  for (int i = 0; i < items.size(); i++) {
    menu.add(Menu.NONE, Menu.NONE, i, items.getString(i));
  }

  PopupMenuCallbackHandler handler = new PopupMenuCallbackHandler(success);
  popupMenu.setOnMenuItemClickListener(handler);
  popupMenu.setOnDismissListener(handler);

  popupMenu.show();
}
 
Example 15
Project: react-native-webrtc   File: WebRTCModule.java   View source code 5 votes vote down vote up
private synchronized void processPicture(byte[] jpeg, int captureTarget, double maxJpegQuality,
                                         int maxSize, int orientation, List<String> paths,
                                         Callback successCallback, Callback errorCallback,
                                         String streamId, int totalPictures) {

    Log.d(TAG, "Processing picture");
    try {
        String path = savePicture(jpeg, captureTarget, maxJpegQuality, maxSize, orientation);

        Log.d(TAG, "Saved picture to " + path);

        paths.add(path);

        if (paths.size() == totalPictures) {
            WritableArray pathsArray = Arguments.createArray();
            for (String p : paths) {
                pathsArray.pushString(p);
            }
            successCallback.invoke(pathsArray);
            imagePorcessingHandler.removeCallbacksAndMessages(null);
        }
    } catch (IOException e) {
        String message = "Could not save picture for stream id " + streamId;
        Log.d(TAG, message, e);
        errorCallback.invoke(message);
        imagePorcessingHandler.removeCallbacksAndMessages(null);
    }
}
 
Example 16
Project: RNLearn_Project1   File: UIViewOperationQueue.java   View source code 5 votes vote down vote up
private FindTargetForTouchOperation(
    final int reactTag,
    final float targetX,
    final float targetY,
    final Callback callback) {
  super();
  mReactTag = reactTag;
  mTargetX = targetX;
  mTargetY = targetY;
  mCallback = callback;
}
 
Example 17
Project: FingerPrint-Authentication-With-React-Native-Android   File: BiometricModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void retrieveUserSettings(String key, Callback successCallbackUserSettings) {

    if (key.equalsIgnoreCase(AppConstants.LOCK_FINGERPRINT)) {
        successCallbackUserSettings.invoke(PreferenceHelper.getPrefernceHelperInstace().getBoolean(AppContext,
                key, true));
    } else {
        successCallbackUserSettings.invoke(PreferenceHelper.getPrefernceHelperInstace().getBoolean(AppContext,
                key, false));
    }

}
 
Example 18
Project: RNLearn_Project1   File: AsyncStorageModuleTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiRemove() {
  final String key1 = "foo1";
  final String key2 = "foo2";
  final String value1 = "bar1";
  final String value2 = "bar2";

  JavaOnlyArray keyValues = new JavaOnlyArray();
  keyValues.pushArray(getArray(key1, value1));
  keyValues.pushArray(getArray(key2, value2));
  mStorage.multiSet(keyValues, mock(Callback.class));

  JavaOnlyArray keys = new JavaOnlyArray();
  keys.pushString(key1);
  keys.pushString(key2);

  Callback getCallback = mock(Callback.class);
  mStorage.multiRemove(keys, getCallback);
  Mockito.verify(getCallback, Mockito.times(1)).invoke();

  Callback getAllCallback = mock(Callback.class);
  mStorage.getAllKeys(getAllCallback);
  Mockito.verify(getAllCallback, Mockito.times(1)).invoke(null, mEmptyArray);

  mStorage.multiSet(keyValues, mock(Callback.class));

  keys.pushString("fakeKey");
  Callback getCallback2 = mock(Callback.class);
  mStorage.multiRemove(keys, getCallback2);
  Mockito.verify(getCallback2, Mockito.times(1)).invoke();

  Callback getAllCallback2 = mock(Callback.class);
  mStorage.getAllKeys(getAllCallback2);
  Mockito.verify(getAllCallback2, Mockito.times(1)).invoke(null, mEmptyArray);
}
 
Example 19
Project: RNLearn_Project1   File: UIViewOperationQueue.java   View source code 5 votes vote down vote up
public void enqueueShowPopupMenu(
    int reactTag,
    ReadableArray items,
    Callback error,
    Callback success) {
  mOperations.add(new ShowPopupMenuOperation(reactTag, items, success));
}
 
Example 20
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void setTaplyticsPushTokenListener(final Callback callback) {
    Taplytics.setTaplyticsPushTokenListener(new TaplyticsPushTokenListener() {
        @Override
        public void pushTokenReceived(String s) {
            callback.invoke(s);
        }
    });
}
 
Example 21
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void propertiesLoadedCallback(final Callback callback) {
    Taplytics.getRunningExperimentsAndVariations(new TaplyticsRunningExperimentsListener() {
        @Override
        public void runningExperimentsAndVariation(Map<String, String> map) {
            callback.invoke();
        }
    });
}
 
Example 22
Project: RNLearn_Project1   File: AsyncStorageModule.java   View source code 5 votes vote down vote up
/**
 * Returns an array with all keys from the database.
 */
@ReactMethod
public void getAllKeys(final Callback callback) {
  new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
    @Override
    protected void doInBackgroundGuarded(Void... params) {
      if (!ensureDatabase()) {
        callback.invoke(AsyncStorageErrorUtil.getDBError(null), null);
        return;
      }
      WritableArray data = Arguments.createArray();
      String[] columns = {KEY_COLUMN};
      Cursor cursor = mReactDatabaseSupplier.get()
          .query(TABLE_CATALYST, columns, null, null, null, null, null);
      try {
        if (cursor.moveToFirst()) {
          do {
            data.pushString(cursor.getString(0));
          } while (cursor.moveToNext());
        }
      } catch (Exception e) {
        FLog.w(ReactConstants.TAG, e.getMessage(), e);
        callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()), null);
        return;
      } finally {
        cursor.close();
      }
      callback.invoke(null, data);
    }
  }.execute();
}
 
Example 23
Project: RNLearn_Project1   File: ReactActivityDelegate.java   View source code 5 votes vote down vote up
public void onRequestPermissionsResult(
  final int requestCode,
  final String[] permissions,
  final int[] grantResults) {
  mPermissionsCallback = new Callback() {
    @Override
    public void invoke(Object... args) {
      if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
        mPermissionListener = null;
      }
    }
  };
}
 
Example 24
Project: react-native-google-fit   File: GoogleFitModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void getDailyCalorieSamples(double startDate,
                                   double endDate,
                                   Callback errorCallback,
                                   Callback successCallback) {
    
    try {
        successCallback.invoke(mGoogleFitManager.getCalorieHistory().aggregateDataByDate((long)startDate, (long)endDate));
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}
 
Example 25
Project: react-native-google-fit   File: GoogleFitModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void saveWeight(ReadableMap weightSample,
                       Callback errorCallback,
                       Callback successCallback) {
    
    try {
        successCallback.invoke(mGoogleFitManager.getWeightsHistory().saveWeight(weightSample));
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}
 
Example 26
Project: RNLearn_Project1   File: UIManagerModuleTest.java   View source code 5 votes vote down vote up
@Test
public void testAddAndRemoveAnimation() {
  UIManagerModule uiManagerModule = getUIManagerModule();
  TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManagerModule);

  AnimationPropertyUpdater mockPropertyUpdater = mock(AnimationPropertyUpdater.class);
  Animation mockAnimation = spy(new AnimationStub(1000, mockPropertyUpdater));
  Callback callbackMock = mock(Callback.class);

  int rootTag = hierarchy.rootView;
  uiManagerModule.createView(
      hierarchy.rootView,
      ReactViewManager.REACT_CLASS,
      rootTag,
      JavaOnlyMap.of("collapsable", false));

  uiManagerModule.registerAnimation(mockAnimation);
  uiManagerModule.addAnimation(hierarchy.rootView, 1000, callbackMock);
  uiManagerModule.removeAnimation(hierarchy.rootView, 1000);

  uiManagerModule.onBatchComplete();
  executePendingFrameCallbacks();

  verify(callbackMock, times(1)).invoke(false);
  verify(mockAnimation).run();
  verify(mockAnimation).cancel();
}
 
Example 27
Project: react-native-google-fit   File: GoogleFitModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void isAvailable(Callback errorCallback, Callback successCallback) { // true if GoogleFit installed
    try {
        successCallback.invoke(isAvailableCheck());
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}
 
Example 28
Project: react-native-google-fit   File: GoogleFitModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void isEnabled(Callback errorCallback, Callback successCallback) { // true if permission granted
    try {
        successCallback.invoke(isEnabledCheck());
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}
 
Example 29
Project: RNLearn_Project1   File: ImageEditingManager.java   View source code 5 votes vote down vote up
/**
 * Crop an image. If all goes well, the success callback will be called with the file:// URI of
 * the new image as the only argument. This is a temporary file - consider using
 * CameraRollManager.saveImageWithTag to save it in the gallery.
 *
 * @param uri the MediaStore URI of the image to crop
 * @param options crop parameters specified as {@code {offset: {x, y}, size: {width, height}}}.
 *        Optionally this also contains  {@code {targetSize: {width, height}}}. If this is
 *        specified, the cropped image will be resized to that size.
 *        All units are in pixels (not DPs).
 * @param success callback to be invoked when the image has been cropped; the only argument that
 *        is passed to this callback is the file:// URI of the new image
 * @param error callback to be invoked when an error occurs (e.g. can't create file etc.)
 */
@ReactMethod
public void cropImage(
    String uri,
    ReadableMap options,
    final Callback success,
    final Callback error) {
  ReadableMap offset = options.hasKey("offset") ? options.getMap("offset") : null;
  ReadableMap size = options.hasKey("size") ? options.getMap("size") : null;
  if (offset == null || size == null ||
      !offset.hasKey("x") || !offset.hasKey("y") ||
      !size.hasKey("width") || !size.hasKey("height")) {
    throw new JSApplicationIllegalArgumentException("Please specify offset and size");
  }
  if (uri == null || uri.isEmpty()) {
    throw new JSApplicationIllegalArgumentException("Please specify a URI");
  }

  CropTask cropTask = new CropTask(
      getReactApplicationContext(),
      uri,
      (int) offset.getDouble("x"),
      (int) offset.getDouble("y"),
      (int) size.getDouble("width"),
      (int) size.getDouble("height"),
      success,
      error);
  if (options.hasKey("displaySize")) {
    ReadableMap targetSize = options.getMap("displaySize");
    cropTask.setTargetSize(targetSize.getInt("width"), targetSize.getInt("height"));
  }
  cropTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 30
Project: react-native-android-activity   File: ActivityStarterModule.java   View source code 5 votes vote down vote up
@ReactMethod
void getActivityName(@Nonnull Callback callback) {
    Activity activity = getCurrentActivity();
    if (activity != null) {
        callback.invoke(activity.getClass().getSimpleName());
    }
}
 
Example 31
Project: react-native-asset-resize-to-base64   File: RNAssetResizeToBase64Module.java   View source code 5 votes vote down vote up
@ReactMethod
public void assetToResizedBase64(String uri, int width, int height, Callback callback)
{
	try
	{
		Bitmap image = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), Uri.parse(uri));
		if (image == null)
			callback.invoke("FAIL : uri: " + uri);
		else
			callback.invoke(null, makeConversion(image, width, height));
	}
	catch (IOException e)
	{
	}
 }
 
Example 32
Project: RNLearn_Project1   File: UIImplementation.java   View source code 5 votes vote down vote up
/**
 * Determines the location on screen, width, and height of the given view relative to the root
 * view and returns the values via an async callback.
 */
public void measure(int reactTag, Callback callback) {
  // This method is called by the implementation of JS touchable interface (see Touchable.js for
  // more details) at the moment of touch activation. That is after user starts the gesture from
  // a touchable view with a given reactTag, or when user drag finger back into the press
  // activation area of a touchable view that have been activated before.
  mOperationsQueue.enqueueMeasure(reactTag, callback);
}
 
Example 33
Project: RNLearn_Project1   File: NativeAnimatedNodeTraversalTest.java   View source code 5 votes vote down vote up
@Test
public void testFramesAnimation() {
  createSimpleAnimatedViewWithOpacity(1000, 0d);

  JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d);
  Callback animationCallback = mock(Callback.class);
  mNativeAnimatedNodesManager.startAnimatingNode(
    1,
    1,
    JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d),
    animationCallback);

  ArgumentCaptor<ReactStylesDiffMap> stylesCaptor =
      ArgumentCaptor.forClass(ReactStylesDiffMap.class);

  reset(mUIImplementationMock);
  mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
  verify(mUIImplementationMock).synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture());
  assertThat(stylesCaptor.getValue().getDouble("opacity", Double.NaN)).isEqualTo(0);

  for (int i = 0; i < frames.size(); i++) {
    reset(mUIImplementationMock);
    mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
    verify(mUIImplementationMock)
        .synchronouslyUpdateViewOnUIThread(eq(1000), stylesCaptor.capture());
    assertThat(stylesCaptor.getValue().getDouble("opacity", Double.NaN))
        .isEqualTo(frames.getDouble(i));
  }

  reset(mUIImplementationMock);
  mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
  verifyNoMoreInteractions(mUIImplementationMock);
}
 
Example 34
Project: RNLearn_Project1   File: FlatUIViewOperationQueue.java   View source code 5 votes vote down vote up
@Override
public void enqueueFindTargetForTouch(
    final int reactTag,
    final float targetX,
    final float targetY,
    final Callback callback) {
  enqueueUIOperation(
      new FindTargetForTouchOperation(reactTag, targetX, targetY, callback));
}
 
Example 35
Project: react-native-simple-download-manager   File: ReactNativeDownloadManagerModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void checkStatus(String downloadId, Callback onStatus) {
    try {
        WritableMap status = downloader.checkDownloadStatus(Long.parseLong(downloadId));
        onStatus.invoke(null, status);
    } catch (Exception e) {
        onStatus.invoke(e.getMessage(), null);
    }
}
 
Example 36
Project: react-native-bottomsheet   File: RNBottomSheet.java   View source code 5 votes vote down vote up
@ReactMethod
public void showShareBottomSheetWithOptions(ReadableMap options, Callback failureCallback, Callback successCallback) {
    String url = options.getString("url");
    String message = options.getString("message");
    String subject = options.getString("subject");

    List<String> items = new ArrayList<>();
    if (message != null && !message.isEmpty()) {
        items.add(message);
    }

    final Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    Uri uri = Uri.parse(url);
    if (uri != null) {
        if (uri.getScheme() != null && "data".equals(uri.getScheme().toLowerCase())) {
            shareIntent.setType("*/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        } else {
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_EMAIL, url);
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
            shareIntent.putExtra(Intent.EXTRA_TEXT, message);
        }
    }

    this.shareSuccessCallback = successCallback;
    this.shareFailureCallback = failureCallback;

    if (shareIntent.resolveActivity(this.getCurrentActivity().getPackageManager()) != null) {
        this.getCurrentActivity().startActivity(Intent.createChooser(shareIntent, "Share To"));
    } else {
        failureCallback.invoke(new Exception("The app you want to share is not installed."));
    }
}
 
Example 37
Project: RNLearn_Project1   File: ForwardingCookieHandler.java   View source code 5 votes vote down vote up
private void clearCookiesAsync(final Callback callback) {
  getCookieManager().removeAllCookies(
      new ValueCallback<Boolean>() {
        @Override
        public void onReceiveValue(Boolean value) {
          mCookieSaver.onCookiesModified();
          callback.invoke(value);
        }
      });
}
 
Example 38
Project: RNLearn_Project1   File: ImageStoreManager.java   View source code 5 votes vote down vote up
private GetBase64Task(
    ReactContext reactContext,
    String uri,
    Callback success,
    Callback error) {
  super(reactContext);
  mUri = uri;
  mSuccess = success;
  mError = error;
}
 
Example 39
Project: RNLearn_Project1   File: ImageEditingManager.java   View source code 5 votes vote down vote up
/**
 * Crop an image. If all goes well, the success callback will be called with the file:// URI of
 * the new image as the only argument. This is a temporary file - consider using
 * CameraRollManager.saveImageWithTag to save it in the gallery.
 *
 * @param uri the MediaStore URI of the image to crop
 * @param options crop parameters specified as {@code {offset: {x, y}, size: {width, height}}}.
 *        Optionally this also contains  {@code {targetSize: {width, height}}}. If this is
 *        specified, the cropped image will be resized to that size.
 *        All units are in pixels (not DPs).
 * @param success callback to be invoked when the image has been cropped; the only argument that
 *        is passed to this callback is the file:// URI of the new image
 * @param error callback to be invoked when an error occurs (e.g. can't create file etc.)
 */
@ReactMethod
public void cropImage(
    String uri,
    ReadableMap options,
    final Callback success,
    final Callback error) {
  ReadableMap offset = options.hasKey("offset") ? options.getMap("offset") : null;
  ReadableMap size = options.hasKey("size") ? options.getMap("size") : null;
  if (offset == null || size == null ||
      !offset.hasKey("x") || !offset.hasKey("y") ||
      !size.hasKey("width") || !size.hasKey("height")) {
    throw new JSApplicationIllegalArgumentException("Please specify offset and size");
  }
  if (uri == null || uri.isEmpty()) {
    throw new JSApplicationIllegalArgumentException("Please specify a URI");
  }

  CropTask cropTask = new CropTask(
      getReactApplicationContext(),
      uri,
      (int) offset.getDouble("x"),
      (int) offset.getDouble("y"),
      (int) size.getDouble("width"),
      (int) size.getDouble("height"),
      success,
      error);
  if (options.hasKey("displaySize")) {
    ReadableMap targetSize = options.getMap("displaySize");
    cropTask.setTargetSize(targetSize.getInt("width"), targetSize.getInt("height"));
  }
  cropTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 40
Project: RNLearn_Project1   File: AsyncStorageModuleTest.java   View source code 5 votes vote down vote up
@Test
public void testMultiSetMultiGet() {
  final String key1 = "foo1";
  final String key2 = "foo2";
  final String fakeKey = "fakeKey";
  final String value1 = "bar1";
  final String value2 = "bar2";
  JavaOnlyArray keyValues = new JavaOnlyArray();
  keyValues.pushArray(getArray(key1, value1));
  keyValues.pushArray(getArray(key2, value2));

  Callback setCallback = mock(Callback.class);
  mStorage.multiSet(keyValues, setCallback);
  Mockito.verify(setCallback, Mockito.times(1)).invoke();

  JavaOnlyArray keys = new JavaOnlyArray();
  keys.pushString(key1);
  keys.pushString(key2);

  Callback getCallback = mock(Callback.class);
  mStorage.multiGet(keys, getCallback);
  Mockito.verify(getCallback, Mockito.times(1)).invoke(null, keyValues);

  keys.pushString(fakeKey);
  JavaOnlyArray row3 = new JavaOnlyArray();
  row3.pushString(fakeKey);
  row3.pushString(null);
  keyValues.pushArray(row3);

  Callback getCallback2 = mock(Callback.class);
  mStorage.multiGet(keys, getCallback2);
  Mockito.verify(getCallback2, Mockito.times(1)).invoke(null, keyValues);
}