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

The following examples show how to use com.facebook.react.bridge.Promise#resolve() . 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: IntentModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Determine whether or not an installed app can handle a given URL.
 *
 * @param url the URL to open
 * @param promise a promise that is always resolved with a boolean argument
 */
@ReactMethod
public void canOpenURL(String url, Promise promise) {
  if (url == null || url.isEmpty()) {
    promise.reject(new JSApplicationIllegalArgumentException("Invalid URL: " + url));
    return;
  }

  try {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    // We need Intent.FLAG_ACTIVITY_NEW_TASK since getReactApplicationContext() returns
    // the ApplicationContext instead of the Activity context.
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    boolean canOpen =
        intent.resolveActivity(getReactApplicationContext().getPackageManager()) != null;
    promise.resolve(canOpen);
  } catch (Exception e) {
    promise.reject(new JSApplicationIllegalArgumentException(
        "Could not check if URL '" + url + "' can be opened: " + e.getMessage()));
  }
}
 
Example 2
Source File: QTalkLoaclSearch.java    From imsdk-android with MIT License 6 votes vote down vote up
@ReactMethod
public void search(
        String key,
        int length,
        int start,
        String groupId,
        Promise promise) {

    WritableMap map = Arguments.createMap();
    map.putBoolean("is_ok", true);

    try {
        List ret = NativeApi.localSearch(key, start, length, groupId);

        String jsonStr =  JsonUtils.getGson().toJson(ret);
        Logger.i("QTalkLoaclSearch->"+jsonStr);
        map.putString("data", jsonStr);
        promise.resolve(map);
    } catch (Exception e) {
        Logger.i("QTalkLoaclSearch-search>"+e.getLocalizedMessage());
        //map.putBoolean("is_ok", false);
        //map.putString("errorMsg", e.toString());
        promise.reject("500", e.toString(), e);
    }
}
 
Example 3
Source File: ReactNativeGetLocationModule.java    From react-native-get-location with MIT License 6 votes vote down vote up
@ReactMethod
public void openWifiSettings(final Promise primise) {
    try {
        SettingsUtil.openWifiSettings(getReactApplicationContext());
        primise.resolve(null);
    } catch (Throwable ex) {
        primise.reject(ex);
    }
}
 
Example 4
Source File: Manager.java    From react-native-fitness with MIT License 6 votes vote down vote up
public void subscribeToActivity(Context context, final Promise promise){
    final GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if(account == null){
        promise.resolve(false);
        return;
    }
    Fitness.getRecordingClient(context, account)
            .subscribe(DataType.TYPE_ACTIVITY_SAMPLES)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    promise.resolve(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.resolve(false);
                }
            });

}
 
Example 5
Source File: ReactNativeBiometrics.java    From react-native-biometrics with MIT License 5 votes vote down vote up
@ReactMethod
public void createKeys(Promise promise) {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            deleteBiometricKey();
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
            KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(biometricKeyAlias, KeyProperties.PURPOSE_SIGN)
                    .setDigests(KeyProperties.DIGEST_SHA256)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                    .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
                    .setUserAuthenticationRequired(true)
                    .build();
            keyPairGenerator.initialize(keyGenParameterSpec);

            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            byte[] encodedPublicKey = publicKey.getEncoded();
            String publicKeyString = Base64.encodeToString(encodedPublicKey, Base64.DEFAULT);
            publicKeyString = publicKeyString.replaceAll("\r", "").replaceAll("\n", "");

            WritableMap resultMap = new WritableNativeMap();
            resultMap.putString("publicKey", publicKeyString);
            promise.resolve(resultMap);
        } else {
            promise.reject("Cannot generate keys on android versions below 6.0", "Cannot generate keys on android versions below 6.0");
        }
    } catch (Exception e) {
        promise.reject("Error generating public private keys: " + e.getMessage(), "Error generating public private keys");
    }
}
 
Example 6
Source File: NotificationHelper.java    From react-native-foreground-service with MIT License 5 votes vote down vote up
void createNotificationChannel(ReadableMap channelConfig, Promise promise) {
    if (channelConfig == null) {
        Log.e("NotificationHelper", "createNotificationChannel: invalid config");
        promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel config is invalid");
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (!channelConfig.hasKey("id")) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel id is required");
            return;
        }
        String channelId = channelConfig.getString("id");
        if (!channelConfig.hasKey("name")) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel name is required");
            return;
        }
        String channelName = channelConfig.getString("name");
        String channelDescription = channelConfig.getString("description");
        int channelImportance = channelConfig.hasKey("importance") ?
                channelConfig.getInt("importance") : NotificationManager.IMPORTANCE_LOW;
        boolean enableVibration = channelConfig.hasKey("enableVibration") && channelConfig.getBoolean("enableVibration");
        if (channelId == null || channelName == null) {
            promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel id or name is not specified");
            return;
        }
        NotificationChannel channel = new NotificationChannel(channelId, channelName, channelImportance);
        channel.setDescription(channelDescription);
        channel.enableVibration(enableVibration);
        mNotificationManager.createNotificationChannel(channel);
        promise.resolve(null);
    } else {
        promise.reject(ERROR_ANDROID_VERSION, "VIForegroundService: Notification channel can be created on Android O+");
    }
}
 
Example 7
Source File: NetInfoModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
@ReactMethod
public void isConnectionMetered(Promise promise) {
  if (mNoNetworkPermission) {
    promise.reject(ERROR_MISSING_PERMISSION, MISSING_PERMISSION_MESSAGE, null);
    return;
  }
  promise.resolve(ConnectivityManagerCompat.isActiveNetworkMetered(mConnectivityManager));
}
 
Example 8
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 9
Source File: QTalkLoaclSearch.java    From imsdk-android with MIT License 5 votes vote down vote up
/**
 * 给Rn返回客户端版本号
 * @param msg
 * @param promise
 */
@ReactMethod
public void getVersion(String msg,Promise promise){
    WritableMap map = Arguments.createMap();
    map.putBoolean("is_ok", true);
    map.putString("data", QunarIMApp.getQunarIMApp().getVersion()+"");
    map.putString("Msg",msg);

    try {
        promise.resolve(map);
    }catch (Exception e){
        promise.reject("500",e.toString(),e);
    }
}
 
Example 10
Source File: RNWifiModule.java    From react-native-wifi-reborn with ISC License 5 votes vote down vote up
/**
 * Returns the BSSID (basic service set identifier) of the currently connected WiFi network.
 */
@ReactMethod
public void getBSSID(final Promise promise) {
    final WifiInfo info = wifi.getConnectionInfo();
    final String bssid = info.getBSSID();
    promise.resolve(bssid.toUpperCase());
}
 
Example 11
Source File: RNWifiModule.java    From react-native-wifi-reborn with ISC License 5 votes vote down vote up
/**
 * This method will return current SSID
 *
 * @param promise to send error/result feedback
 */
@ReactMethod
public void getCurrentWifiSSID(final Promise promise) {
    WifiInfo info = wifi.getConnectionInfo();

    // This value should be wrapped in double quotes, so we need to unwrap it.
    String ssid = info.getSSID();
    if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
        ssid = ssid.substring(1, ssid.length() - 1);
    }

    promise.resolve(ssid);
}
 
Example 12
Source File: RNWifiModule.java    From react-native-wifi-reborn with ISC License 5 votes vote down vote up
/**
 * Method to check if wifi is enabled.
 */
@ReactMethod
public void isEnabled(final Promise promise) {
    if (this.wifi == null) {
        promise.reject(IsEnabledErrorCodes.couldNotGetWifiManager.toString(), "Failed to initialize the WifiManager.");
        return;
    }

    promise.resolve(wifi.isWifiEnabled());
}
 
Example 13
Source File: ReactNativeGetLocationModule.java    From react-native-get-location with MIT License 5 votes vote down vote up
@ReactMethod
public void openAppSettings(final Promise promise) {
    try {
        SettingsUtil.openAppSettings(getReactApplicationContext());
        promise.resolve(null);
    } catch (Throwable ex) {
        promise.reject(ex);
    }
}
 
Example 14
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 15
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 16
Source File: LayoutBuilderModule.java    From react-native-esc-pos with MIT License 4 votes vote down vote up
@ReactMethod
public void createMenuItem(String key, String value, String space, Promise promise) {
    promise.resolve(layoutBuilder.createMenuItem(key, value, space.charAt(0)));
}
 
Example 17
Source File: RNFitnessModule.java    From react-native-fitness with MIT License 4 votes vote down vote up
@ReactMethod
public void isAuthorized(ReadableArray permissions, Promise promise){
  promise.resolve(manager.isAuthorized(getCurrentActivity(), createRequestFromReactArray(permissions)));
}
 
Example 18
Source File: AuthorizationModule.java    From react-native-square-reader-sdk with Apache License 2.0 4 votes vote down vote up
@ReactMethod
public void isAuthorizationInProgress(Promise promise) {
    promise.resolve(ReaderSdk.authorizationManager().getAuthorizationState().isAuthorizationInProgress());
}
 
Example 19
Source File: RNCallKeepModule.java    From react-native-callkeep with ISC License 4 votes vote down vote up
@ReactMethod
public void hasPhoneAccount(Promise promise) {
    promise.resolve(hasPhoneAccount());
}
 
Example 20
Source File: EscPosModule.java    From react-native-esc-pos with MIT License 4 votes vote down vote up
@ReactMethod
public void kickCashDrawerPin2(Promise promise) {
    printerService.kickCashDrawerPin2();
    promise.resolve(true);
}