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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: RNLearn_Project1   File: LocationModule.java   Source Code and License 5 votes vote down vote up
private SingleUpdateRequest(
    LocationManager locationManager,
    String provider,
    long timeout,
    Callback success,
    Callback error) {
  mLocationManager = locationManager;
  mProvider = provider;
  mTimeout = timeout;
  mSuccess = success;
  mError = error;
}
 
Example 42
Project: RNLearn_Project1   File: LocationModule.java   Source Code and License 5 votes vote down vote up
/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and
 *        highAccuracy (boolean)
 */
@ReactMethod
public void getCurrentPosition(
    ReadableMap options,
    final Callback success,
    Callback error) {
  LocationOptions locationOptions = LocationOptions.fromReactMap(options);

  try {
    LocationManager locationManager =
        (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
    if (provider == null) {
      emitError(PositionError.PERMISSION_DENIED, "No location provider available.");
      return;
    }
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null &&
        SystemClock.currentTimeMillis() - location.getTime() < locationOptions.maximumAge) {
      success.invoke(locationToMap(location));
      return;
    }
    new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error)
        .invoke();
  } catch (SecurityException e) {
    throwLocationPermissionMissing(e);
  }
}
 
Example 43
Project: react-native-growingio   File: GrowingIOModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void setPeopleVariable(final String strVariableJson, Callback callback) {
    try {
        JSONObject jsonVariable = new JSONObject(strVariableJson);
        GrowingIO.getInstance().setPeopleVariable(jsonVariable);
        callback.invoke(CALLBACK_SUCCESS);
        LogUtil.d(TAG, "setEvarVariable success");
    } catch (JSONException e) {
        callback.invoke("the first parameter must be String of JSONObject");
        LogUtil.d(TAG, "setEvarVariable :" + e.getMessage());
    }
}
 
Example 44
Project: RNLearn_Project1   File: NativeAnimatedNodesManager.java   Source Code and License 5 votes vote down vote up
public void startAnimatingNode(
  int animationId,
  int animatedNodeTag,
  ReadableMap animationConfig,
  Callback endCallback) {
  AnimatedNode node = mAnimatedNodes.get(animatedNodeTag);
  if (node == null) {
    throw new JSApplicationIllegalArgumentException("Animated node with tag " + animatedNodeTag +
      " does not exists");
  }
  if (!(node instanceof ValueAnimatedNode)) {
    throw new JSApplicationIllegalArgumentException("Animated node should be of type " +
      ValueAnimatedNode.class.getName());
  }
  String type = animationConfig.getString("type");
  final AnimationDriver animation;
  if ("frames".equals(type)) {
    animation = new FrameBasedAnimationDriver(animationConfig);
  } else if ("spring".equals(type)) {
    animation = new SpringAnimation(animationConfig);
  } else if ("decay".equals(type)) {
    animation = new DecayAnimation(animationConfig);
  } else {
    throw new JSApplicationIllegalArgumentException("Unsupported animation type: " + type);
  }
  animation.mId = animationId;
  animation.mEndCallback = endCallback;
  animation.mAnimatedValue = (ValueAnimatedNode) node;
  mActiveAnimations.put(animationId, animation);
}
 
Example 45
Project: react-native-location-switch   File: Module.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void enableLocationService(int interval, boolean requestHighAccuracy,
                                  Callback successCallback, Callback errorCallback) {
    LocationSwitch.getInstance().setup(
            successCallback, errorCallback, interval, requestHighAccuracy);
    LocationSwitch.getInstance().displayLocationSettingsRequest(
            getCurrentActivity());
}
 
Example 46
Project: react-native-compress-image   File: ImageCompressModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void createCompressedImage(String imagePath, String directoryPath, final Callback successCb, final Callback failureCb) {
    try {
        createCompressedImageWithExceptions(imagePath, directoryPath, successCb, failureCb);
    } catch (IOException e) {
        failureCb.invoke(e.getMessage());
    }
}
 
Example 47
Project: RNLearn_Project1   File: UIViewOperationQueue.java   Source Code and License 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 48
Project: react-native-compress-image   File: ImageCompressModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void createCustomCompressedImage(String imagePath, String directoryPath, int maxWidth, int maxHeight, int quality, final Callback successCb, final Callback failureCb) {
    try {
        createCustomCompressedImageWithExceptions(imagePath, directoryPath, maxWidth, maxHeight, quality, successCb, failureCb);
    } catch (IOException e) {
        failureCb.invoke(e.getMessage());
    }
}
 
Example 49
Project: RNLearn_Project1   File: UIManagerModule.java   Source Code and License 5 votes vote down vote up
/**
 * Find the touch target child native view in  the supplied root view hierarchy, given a react
 * target location.
 *
 * This method is currently used only by Element Inspector DevTool.
 *
 * @param reactTag the tag of the root view to traverse
 * @param point an array containing both X and Y target location
 * @param callback will be called if with the identified child view react ID, and measurement
 *        info. If no view was found, callback will be invoked with no data.
 */
@ReactMethod
public void findSubviewIn(
    final int reactTag,
    final ReadableArray point,
    final Callback callback) {
  mUIImplementation.findSubviewIn(
    reactTag,
    Math.round(PixelUtil.toPixelFromDIP(point.getDouble(0))),
    Math.round(PixelUtil.toPixelFromDIP(point.getDouble(1))),
    callback);
}
 
Example 50
Project: react-native-ble-quick-sdk   File: CommAdminBleRNI.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void native_IsDeviceConnnected( String deviceUUID,  Callback resultCallback,  Callback failCallback)

{
	//NSLog(@"native_IsDeviceConnnected entered");
	Log.d(LOG_TAG,"native_IsDeviceConnnected entered");
	//[mBleAdmin checkPeripheralState:deviceUUID resultCallback:resultCallback failCallback:failCallback ];
	mBleAdmin.checkPeripheralState(deviceUUID, resultCallback,failCallback) ;
}
 
Example 51
Project: react-native-ble-quick-sdk   File: CommAdminBleRNI.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void native_write_string(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Callback successCallback, Callback failCallback) {
	//NSLog(@"native_write entered");
	Log.d(LOG_TAG,"native_write_string entered");
	//[mBleAdmin writeAsString:deviceUUID serviceUUID:serviceUUID characteristicUUID:characteristicUUID message:message successCallback: successCallback failCallback: failCallback];
	mBleAdmin.writeAsString( deviceUUID, serviceUUID, characteristicUUID , message , successCallback, failCallback);

}
 
Example 52
Project: RNLearn_Project1   File: ForwardingCookieHandler.java   Source Code and License 5 votes vote down vote up
public CookieSaver() {
  mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
      if (msg.what == MSG_PERSIST_COOKIES) {
        persistCookies();
        return true;
      } else {
        return false;
      }
    }
  });
}
 
Example 53
Project: react-native-udesk   File: UdeskModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void setUserInfo(final ReadableMap options, final Callback callback) {
    Map<String, String> info = new HashMap<>();
    if (!hasAndNotEmpty(options, "sdk_token")) {
        return;
    }
    String token = options.getString("sdk_token");
    if (token == null) {
        token = UUID.randomUUID().toString();
    }
    //token 必填
    info.put(UdeskConst.UdeskUserInfo.USER_SDK_TOKEN, token);
    //以下信息是可选
    if (hasAndNotEmpty(options, "nick_name")) {
        info.put(UdeskConst.UdeskUserInfo.NICK_NAME, options.getString("nick_name"));
    }
    if (hasAndNotEmpty(options, "email")) {
        info.put(UdeskConst.UdeskUserInfo.EMAIL, options.getString("email"));
    }
    if (hasAndNotEmpty(options, "cellphone")) {
        info.put(UdeskConst.UdeskUserInfo.CELLPHONE, options.getString("cellphone"));
    }
    if (hasAndNotEmpty(options, "description")) {
        info.put(UdeskConst.UdeskUserInfo.DESCRIPTION, options.getString("description"));
    }
    ReadableMap field = options.getMap("customer_field");
    if (field!= null && field.hasKey("TextField_10075")) {
        Map<String, String> fields = new HashMap<>();
        fields.put("TextField_10075", field.getString("TextField_10075"));
        UdeskSDKManager.getInstance().setUserInfo(mReactContext.getApplicationContext(), token, info, fields);
    } else {
        UdeskSDKManager.getInstance().setUserInfo(mReactContext.getApplicationContext(), token, info);
    }
}
 
Example 54
Project: RNLearn_Project1   File: AsyncStorageModule.java   Source Code and License 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 55
Project: RNLearn_Project1   File: NativeAnimatedNodeTraversalTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNodeValueListenerIfListening() {
  int nodeId = 1;

  createSimpleAnimatedViewWithOpacity(1000, 0d);
  JavaOnlyArray frames = JavaOnlyArray.of(0d, 0.2d, 0.4d, 0.6d, 0.8d, 1d);

  Callback animationCallback = mock(Callback.class);
  AnimatedNodeValueListener valueListener = mock(AnimatedNodeValueListener.class);

  mNativeAnimatedNodesManager.startListeningToAnimatedNodeValue(nodeId, valueListener);
  mNativeAnimatedNodesManager.startAnimatingNode(
    1,
    nodeId,
    JavaOnlyMap.of("type", "frames", "frames", frames, "toValue", 1d),
    animationCallback);

  mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
  verify(valueListener).onValueUpdate(eq(0d));

  for (int i = 0; i < frames.size(); i++) {
    reset(valueListener);
    mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
    verify(valueListener).onValueUpdate(eq(frames.getDouble(i)));
  }

  reset(valueListener);
  mNativeAnimatedNodesManager.runUpdates(nextFrameTime());
  verifyNoMoreInteractions(valueListener);
}
 
Example 56
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getMonitoredRegions(Callback callback) {
    WritableArray array = new WritableNativeArray();
    for (Region region: mBeaconManager.getMonitoredRegions()) {
        WritableMap map = new WritableNativeMap();
        map.putString("identifier", region.getUniqueId());
        map.putString("uuid", region.getId1().toString());
        map.putInt("major", region.getId2() != null ? region.getId2().toInt() : 0);
        map.putInt("minor", region.getId3() != null ? region.getId3().toInt() : 0);
        array.pushMap(map);
    }
    callback.invoke(array);
}
 
Example 57
Project: RNLearn_Project1   File: UIViewOperationQueue.java   Source Code and License 5 votes vote down vote up
private MeasureOperation(
    final int reactTag,
    final Callback callback) {
  super();
  mReactTag = reactTag;
  mCallback = callback;
}
 
Example 58
Project: react-native-ibeacons   File: BeaconsAndroidModule.java   Source Code and License 5 votes vote down vote up
/***********************************************************************************************
 * Monitoring
 **********************************************************************************************/
@ReactMethod
public void startMonitoring(String regionId, String beaconUuid, int minor, int major, Callback resolve, Callback reject) {
    Log.d(LOG_TAG, "startMonitoring, monitoringRegionId: " + regionId + ", monitoringBeaconUuid: " + beaconUuid + ", minor: " + minor + ", major: " + major);
    try {
        Region region = createRegion(regionId, beaconUuid, minor, major);
        mBeaconManager.startMonitoringBeaconsInRegion(region);
        resolve.invoke();
    } catch (Exception e) {
        Log.e(LOG_TAG, "startMonitoring, error: ", e);
        reject.invoke(e.getMessage());
    }
}
 
Example 59
Project: RNLearn_Project1   File: AppStateModule.java   Source Code and License 4 votes vote down vote up
@ReactMethod
public void getCurrentAppState(Callback success, Callback error) {
  success.invoke(createAppStateEventMap());
}
 
Example 60
Project: react-native-webrtc   File: WebRTCModule.java   Source Code and License 4 votes vote down vote up
@ReactMethod
public void getLanguage(Callback callback){
    String language = getCurrentLanguage();
    System.out.println("The current language is "+language);
    callback.invoke(null, language);
}