Java Code Examples for com.facebook.react.bridge.Promise#reject()

The following examples show how to use com.facebook.react.bridge.Promise#reject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QTalkLoaclSearch.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
 * 给rn返回搜索地址
 * @param msg
 * @param promise
 */
@ReactMethod
public void searchUrl(String msg,Promise promise){
    WritableMap map = Arguments.createMap();
    map.putBoolean("is_ok", true);

    map.putString("data", QtalkNavicationService.getInstance().getSearchurl());
    map.putString("Msg",msg);
    Logger.i("QTalkLoaclSearch->"+QtalkNavicationService.getInstance().getSearchurl());
    try {
        promise.resolve(map);
    }catch (Exception e){
        Logger.i("QTalkLoaclSearch-searchUrl>"+e.getLocalizedMessage());
        promise.reject("500",e.toString(),e);
    }
}
 
Example 2
Source File: GoogleFitModule.java    From react-native-google-fitness with MIT License 6 votes vote down vote up
@ReactMethod
public void history_readDailyTotal(String jsonStatement, final Promise promise) {
    try {
        DataType dataType = (DataType) StatementFactory
                .fromJson(jsonStatement)
                .execute(new JavaContext(), null);

        getHistoryClient()
                .readDailyTotal(dataType)
                .addOnFailureListener(new SimpleFailureListener(promise))
                .addOnSuccessListener(new OnSuccessListener<DataSet>() {
                    @Override
                    public void onSuccess(DataSet dataSet) {
                        promise.resolve(JSONEncoder.convertDataSet(dataSet));
                    }
                });

    } catch (Exception e) {
        Log.e(TAG, "Error in history_readDailyTotal()", e);
        promise.reject(e);
    }
}
 
Example 3
Source File: RNJWPlayerModule.java    From react-native-jw-media-player with MIT License 6 votes vote down vote up
@ReactMethod
public void state(final int reactTag, final Promise promise) {
  try {
    UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
    uiManager.addUIBlock(new UIBlock() {
      public void execute (NativeViewHierarchyManager nvhm) {
        RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);

        if (playerView != null && playerView.mPlayer != null) {
          PlayerState playerState = playerView.mPlayer.getState();
          promise.resolve(stateToInt(playerState));
        } else {
          promise.reject("RNJW Error", "Player is null");
        }
      }
    });
  } catch (IllegalViewOperationException e) {
    promise.reject("RNJW Error", e);
  }
}
 
Example 4
Source File: ClipboardModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public void getString(Promise promise) {
  try {
    ClipboardManager clipboard = getClipboardService();
    ClipData clipData = clipboard.getPrimaryClip();
    if (clipData == null) {
      promise.resolve("");
    } else if (clipData.getItemCount() >= 1) {
      ClipData.Item firstItem = clipboard.getPrimaryClip().getItemAt(0);
      promise.resolve("" + firstItem.getText());
    } else {
      promise.resolve("");
    }
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 5
Source File: RNSecureStorageModule.java    From react-native-secure-storage with MIT License 6 votes vote down vote up
@ReactMethod
public void getAllKeys(String service, Promise promise) {
    try {
        service = getDefaultServiceIfNull(service);
        final PrefsStorage prefsStorage = new PrefsStorage(getReactApplicationContext(), service);
        String[] allKeys = prefsStorage.getAllKeys();
        WritableArray keyArray = new WritableNativeArray();
        for (String key : allKeys) {
            keyArray.pushString(key);
        }
        promise.resolve(keyArray);
        return;
    } catch (Exception e) {
        Log.e(SECURE_STORAGE_MODULE, e.getMessage());
        promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
    }
}
 
Example 6
Source File: BrightcovePlayerAccount.java    From react-native-brightcove-player with MIT License 5 votes vote down vote up
public void requestDownloadWithReferenceId(String referenceId, int bitRate, Promise promise) {
    if (this.hasOfflineVideoDownloadSessionWithReferenceId(referenceId)) {
        promise.reject(ERROR_CODE, ERROR_MESSAGE_DUPLICATE_SESSION);
        return;
    }
    OfflineVideoDownloadSession session = new OfflineVideoDownloadSession(this.context, this.accountId, this.policyKey, this);
    session.requestDownloadWithReferenceId(referenceId, bitRate, promise);
    this.offlineVideoDownloadSessions.add(session);
    this.listener.onOfflineStorageStateChanged(collectNativeOfflineVideoStatuses());
}
 
Example 7
Source File: BrightcovePlayerAccount.java    From react-native-brightcove-player with MIT License 5 votes vote down vote up
public void deleteOfflineVideo(final String videoId, final Promise promise) {
    try {
        if (videoId == null) throw new Exception();
        this.offlineCatalog.cancelVideoDownload(videoId);
        for (int i = this.offlineVideoDownloadSessions.size() - 1; i >= 0; i--) {
            OfflineVideoDownloadSession session = this.offlineVideoDownloadSessions.get(i);
            if (videoId.equals(session.videoId)) {
                this.offlineVideoDownloadSessions.remove(i);
            }
        }
        this.offlineCatalog.deleteVideo(videoId, new OfflineCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                promise.resolve(null);
                for (int i = allDownloadedVideos.size() - 1; i >= 0; i--) {
                    Video video = allDownloadedVideos.get(i);
                    if (videoId.equals(video.getId())) {
                        allDownloadedVideos.remove(i);
                    }
                }
                listener.onOfflineStorageStateChanged(collectNativeOfflineVideoStatuses());
            }

            @Override
            public void onFailure(Throwable throwable) {
                promise.reject(ERROR_CODE, ERROR_MESSAGE_DELETE);
            }
        });
    } catch (Exception e) {
        Log.e(DEBUG_TAG, e.getMessage());
        promise.reject(ERROR_CODE, e);
    }
}
 
Example 8
Source File: NetInfoModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
@ReactMethod
public void getCurrentConnectivity(Promise promise) {
  if (mNoNetworkPermission) {
    promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
    return;
  }
  promise.resolve(createConnectivityEventMap());
}
 
Example 9
Source File: IntentModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * Starts a corresponding external activity for the given URL.
 *
 * For example, if the URL is "https://www.facebook.com", the system browser will be opened,
 * or the "choose application" dialog will be shown.
 *
 * @param url the URL to open
 */
@ReactMethod
public void openURL(String url, Promise promise) {
  if (url == null || url.isEmpty()) {
    promise.reject(new JSApplicationIllegalArgumentException("Invalid URL: " + url));
    return;
  }

  try {
    Activity currentActivity = getCurrentActivity();
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url).normalizeScheme());

    String selfPackageName = getReactApplicationContext().getPackageName();
    ComponentName componentName = intent.resolveActivity(
      getReactApplicationContext().getPackageManager());
    String otherPackageName = (componentName != null ? componentName.getPackageName() : "");

    // If there is no currentActivity or we are launching to a different package we need to set
    // the FLAG_ACTIVITY_NEW_TASK flag
    if (currentActivity == null || !selfPackageName.equals(otherPackageName)) {
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    if (currentActivity != null) {
      currentActivity.startActivity(intent);
    } else {
      getReactApplicationContext().startActivity(intent);
    }

    promise.resolve(true);
  } catch (Exception e) {
    promise.reject(new JSApplicationIllegalArgumentException(
        "Could not open URL '" + url + "': " + e.getMessage()));
  }
}
 
Example 10
Source File: ClipboardModule.java    From clipboard with MIT License 5 votes vote down vote up
@ReactMethod
public void getString(Promise promise) {
  try {
    ClipboardManager clipboard = getClipboardService();
    ClipData clipData = clipboard.getPrimaryClip();
    if (clipData != null && clipData.getItemCount() >= 1) {
      ClipData.Item firstItem = clipboard.getPrimaryClip().getItemAt(0);
      promise.resolve("" + firstItem.getText());
    } else {
      promise.resolve("");
    }
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 11
Source File: BrightcovePlayerUtil.java    From react-native-brightcove-player with MIT License 5 votes vote down vote up
@ReactMethod
public void deleteOfflineVideo(String accountId, String policyKey, String videoId, Promise promise) {
    BrightcovePlayerAccount account = this.getBrightcovePlayerAccount(accountId, policyKey);
    if (account == null) {
        promise.reject(ERROR_CODE, ERROR_MESSAGE_MISSING_ARGUMENTS);
        return;
    }
    account.deleteOfflineVideo(videoId, promise);
}
 
Example 12
Source File: RNFitnessModule.java    From react-native-fitness with MIT License 5 votes vote down vote up
@ReactMethod
public void requestPermissions(ReadableArray permissions, Promise promise){
  final Activity activity = getCurrentActivity();
  if(activity != null) {
    manager.requestPermissions(activity,createRequestFromReactArray(permissions), promise);
  }else{
    promise.reject(new Throwable());
  }
}
 
Example 13
Source File: RNI18nModule.java    From imsdk-android with MIT License 5 votes vote down vote up
@ReactMethod
public void getLanguages(Promise promise) {
  try {
    promise.resolve(this.getLocaleList());
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 14
Source File: RNWifiModule.java    From react-native-wifi-reborn with ISC License 5 votes vote down vote up
/**
 * Use this to execute api calls to a wifi network that does not have internet access.
 *
 * Useful for commissioning IoT devices.
 *
 * This will route all app network requests to the network (instead of the mobile connection).
 * It is important to disable it again after using as even when the app disconnects from the wifi
 * network it will keep on routing everything to wifi.
 *
 * @param useWifi boolean to force wifi off or on
 */
@ReactMethod
public void forceWifiUsage(final boolean useWifi, final Promise promise) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null) {
        promise.reject(ForceWifiUsageErrorCodes.couldNotGetConnectivityManager.toString(), "Failed to get the ConnectivityManager.");
        return;
    }

    if (useWifi) {
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .build();
        connectivityManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull final Network network) {
                super.onAvailable(network);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    connectivityManager.bindProcessToNetwork(network);
                } else {
                    ConnectivityManager.setProcessDefaultNetwork(network);
                }

                connectivityManager.unregisterNetworkCallback(this);

                promise.resolve(null);
            }
        });
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            connectivityManager.bindProcessToNetwork(null);
        } else {
            ConnectivityManager.setProcessDefaultNetwork(null);
        }

        promise.resolve(null);
    }
}
 
Example 15
Source File: ReactNativeBiometrics.java    From react-native-biometrics with MIT License 5 votes vote down vote up
@ReactMethod
public void biometricKeysExist(Promise promise) {
    try {
        boolean doesBiometricKeyExist = doesBiometricKeyExist();
        WritableMap resultMap = new WritableNativeMap();
        resultMap.putBoolean("keysExist", doesBiometricKeyExist);
        promise.resolve(resultMap);
    } catch (Exception e) {
        promise.reject("Error checking if biometric key exists: " + e.getMessage(), "Error checking if biometric key exists: " + e.getMessage());
    }
}
 
Example 16
Source File: RNLBarCodeModule.java    From react-native-barcode with MIT License 5 votes vote down vote up
@ReactMethod
public void decode(ReadableMap option, final Promise promise) {
    int decoderID = option.getInt("decoder");
    Decoder decoder = RNLBarCodeUtils.getDecoderByID(decoderID);
    if (decoder == null) {
        promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                "Device doesn't support this decoder");
        return;
    }
    decoder.setFormats(option.getArray("formats"));
    Bitmap image = null;
    if (option.getBoolean("screenshot")) {
        image = RNLBarCodeUtils.takeScreenshot(getCurrentActivity());
        if (image == null) {
            promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                    "Can't take screenshot");
        }
    } else {
        try {
            image = RNLBarCodeUtils.parseImageStr(option.getString("data"));
        } catch (Exception e) {
            promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                    "Parse image failed, reason: " + e.getMessage());
        }
    }
    if (image != null) {
        promise.resolve(decoder.decodeRGBBitmap(image));
    }
    decoder.release();
}
 
Example 17
Source File: BrightcovePlayerUtil.java    From react-native-brightcove-player with MIT License 5 votes vote down vote up
@ReactMethod
public void getPlaylistWithPlaylistId(String playlistId, String accountId, String policyKey, Promise promise) {
    BrightcovePlayerAccount account = this.getBrightcovePlayerAccount(accountId, policyKey);
    if (account == null) {
        promise.reject(ERROR_CODE, ERROR_MESSAGE_MISSING_ARGUMENTS);
        return;
    }
    account.getPlaylistWithPlaylistId(playlistId, promise);
}
 
Example 18
Source File: VIForegroundServiceModule.java    From react-native-foreground-service with MIT License 5 votes vote down vote up
@ReactMethod
public void stopService(Promise promise) {
    Intent intent = new Intent(getReactApplicationContext(), VIForegroundService.class);
    intent.setAction(Constants.ACTION_FOREGROUND_SERVICE_STOP);
    boolean stopped = getReactApplicationContext().stopService(intent);
    if (stopped) {
        promise.resolve(null);
    } else {
        promise.reject(ERROR_SERVICE_ERROR, "VIForegroundService: Foreground service failed to stop");
    }
}
 
Example 19
Source File: EscPosModule.java    From react-native-esc-pos with MIT License 5 votes vote down vote up
@ReactMethod
public void printImage(String filePath, Promise promise) {
    try {
        printerService.printImage(filePath);
        promise.resolve(true);
    } catch (IOException e) {
        promise.reject(e);
    }
}
 
Example 20
Source File: EscPosModule.java    From react-native-esc-pos with MIT License 5 votes vote down vote up
@ReactMethod
public void disconnect(Promise promise) {
    try {
        printerService.close();
        promise.resolve(true);
    } catch (IOException e) {
        promise.reject(e);
    }
}