com.facebook.react.bridge.Promise Java Examples
The following examples show how to use
com.facebook.react.bridge.Promise.
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: GoogleFitModule.java From react-native-google-fitness with MIT License | 8 votes |
@ReactMethod public void hasPermissions(String fitnessOptionJsonStr, Promise promise) { if (GoogleSignIn.getLastSignedInAccount(mReactContext) == null) { promise.resolve(false); return; } try { FitnessOptions fitnessOptions = (FitnessOptions) StatementFactory .fromJson(fitnessOptionJsonStr) .execute(new JavaContext(), null); promise.resolve(GoogleSignIn.hasPermissions(getLastSignedInAccountSafely(), fitnessOptions)); } catch (Exception e) { Log.e(TAG, "Failed to create FitnessOptions", e); promise.reject(e); } }
Example #2
Source File: ImageLoaderModule.java From react-native-GPay with MIT License | 7 votes |
@ReactMethod public void queryCache(final ReadableArray uris, final Promise promise) { // perform cache interrogation in async task as disk cache checks are expensive new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { WritableMap result = Arguments.createMap(); ImagePipeline imagePipeline = Fresco.getImagePipeline(); for (int i = 0; i < uris.size(); i++) { String uriString = uris.getString(i); final Uri uri = Uri.parse(uriString); if (imagePipeline.isInBitmapMemoryCache(uri)) { result.putString(uriString, "memory"); } else if (imagePipeline.isInDiskCacheSync(uri)) { result.putString(uriString, "disk"); } } promise.resolve(result); } }.executeOnExecutor(GuardedAsyncTask.THREAD_POOL_EXECUTOR); }
Example #3
Source File: FileReaderModule.java From react-native-GPay with MIT License | 6 votes |
@ReactMethod public void readAsText(ReadableMap blob, String encoding, Promise promise) { byte[] bytes = getBlobModule().resolve( blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size")); if (bytes == null) { promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid"); return; } try { promise.resolve(new String(bytes, encoding)); } catch (Exception e) { promise.reject(e); } }
Example #4
Source File: RNTextSizeModule.java From react-native-text-size with BSD 2-Clause "Simplified" License | 6 votes |
/** * See https://material.io/design/typography/#type-scale */ @SuppressWarnings("unused") @ReactMethod public void specsForTextStyles(final Promise promise) { WritableMap result = Arguments.createMap(); result.putMap("h1", makeFontSpecs("-light", 96, -1.5)); result.putMap("h2", makeFontSpecs("-light", 60, -0.5)); result.putMap("h3", makeFontSpecs(null, 48, 0)); result.putMap("h4", makeFontSpecs(null, 34, 0.25)); result.putMap("h5", makeFontSpecs(null, 24, 0)); result.putMap("h6", makeFontSpecs("-medium", 20, 0.15)); result.putMap("subtitle1", makeFontSpecs(null, 16, 0.15)); result.putMap("subtitle2", makeFontSpecs("-medium", 14, 0.1)); result.putMap("body1", makeFontSpecs(null, 16, 0.5)); result.putMap("body2", makeFontSpecs(null, 14, 0.25)); result.putMap("button", makeFontSpecs("-medium", 14, 0.75, true)); result.putMap("caption", makeFontSpecs(null, 12, 0.4)); result.putMap("overline", makeFontSpecs(null, 10, 1.5, true)); promise.resolve(result); }
Example #5
Source File: ReactNativeGetLocationModule.java From react-native-get-location with MIT License | 6 votes |
@ReactMethod public void openWifiSettings(final Promise primise) { try { SettingsUtil.openWifiSettings(getReactApplicationContext()); primise.resolve(null); } catch (Throwable ex) { primise.reject(ex); } }
Example #6
Source File: RNSecureStorageModule.java From react-native-secure-storage with MIT License | 6 votes |
@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 #7
Source File: QTalkLoaclSearch.java From imsdk-android with MIT License | 6 votes |
@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 #8
Source File: ImageEditorModule.java From react-native-image-editor with MIT License | 6 votes |
private CropTask( ReactContext context, String uri, int x, int y, int width, int height, Promise promise) { 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; mPromise = promise; }
Example #9
Source File: ClipboardModule.java From react-native-GPay with MIT License | 6 votes |
@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 #10
Source File: RNJWPlayerModule.java From react-native-jw-media-player with MIT License | 6 votes |
@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 #11
Source File: RNWifiModule.java From react-native-wifi-reborn with ISC License | 6 votes |
/** * This method will remove the wifi network configuration. * If you are connected to that network, it will disconnect. * * @param SSID wifi SSID to remove configuration for */ @ReactMethod public void isRemoveWifiNetwork(final String SSID, final Promise promise) { final boolean locationPermissionGranted = PermissionUtils.isLocationPermissionGranted(context); if (!locationPermissionGranted) { promise.reject(IsRemoveWifiNetworkErrorCodes.locationPermissionMissing.toString(), "Location permission (ACCESS_FINE_LOCATION) is not granted"); return; } final List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks(); final String comparableSSID = ('"' + SSID + '"'); //Add quotes because wifiConfig.SSID has them for (WifiConfiguration wifiConfig : mWifiConfigList) { if (wifiConfig.SSID.equals(comparableSSID)) { promise.resolve(wifi.removeNetwork(wifiConfig.networkId)); wifi.saveConfiguration(); return; } } promise.resolve(true); }
Example #12
Source File: RNWifiModule.java From react-native-wifi-reborn with ISC License | 6 votes |
/** * Returns if the device is currently connected to a WiFi network. */ @ReactMethod public void connectionStatus(final Promise promise) { final ConnectivityManager connectivityManager = (ConnectivityManager) getReactApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivityManager == null) { promise.resolve(false); return; } NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo == null) { promise.resolve(false); return; } promise.resolve(wifiInfo.isConnected()); }
Example #13
Source File: SelectContactModule.java From react-native-select-contact with MIT License | 6 votes |
/** * Lanch the contact picker, with the specified requestCode for returned data. * * @param contactsPromise - promise passed in from React Native. * @param requestCode - request code to specify what contact data to return */ private void launchPicker(Promise contactsPromise, int requestCode) { Cursor cursor = this.contentResolver.query(Contacts.CONTENT_URI, null, null, null, null); if (cursor != null) { mContactsPromise = contactsPromise; Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(Contacts.CONTENT_TYPE); Activity activity = getCurrentActivity(); if (intent.resolveActivity(activity.getPackageManager()) != null) { activity.startActivityForResult(intent, requestCode); } cursor.close(); } else { mContactsPromise.reject(E_CONTACT_PERMISSION, "no permission"); } }
Example #14
Source File: RNSensorsAnalyticsModule.java From react-native-sensors-analytics with Apache License 2.0 | 6 votes |
/** * 导出 getDistinctIdPromise 方法给 RN 使用. * <p> * Promise 方式,获取 distinctId * <p> * RN 中使用示例: * async getDistinctIdPromise() { * var distinctId = await RNSensorsAnalyticsModule.getDistinctIdPromise() * }; */ @ReactMethod public void getDistinctIdPromise(Promise promise) { try { String mLoginId = SensorsDataAPI.sharedInstance().getLoginId(); if (!TextUtils.isEmpty(mLoginId)) { promise.resolve(mLoginId); } else { promise.resolve(SensorsDataAPI.sharedInstance().getAnonymousId()); } } catch (Exception e) { e.printStackTrace(); Log.e(LOGTAG, e.toString() + ""); promise.reject("getDistinctId fail", e); } }
Example #15
Source File: CameraRollManager.java From react-native-GPay with MIT License | 6 votes |
private GetPhotosTask( ReactContext context, int first, @Nullable String after, @Nullable String groupName, @Nullable ReadableArray mimeTypes, @Nullable String assetType, Promise promise) { super(context); mContext = context; mFirst = first; mAfter = after; mGroupName = groupName; mMimeTypes = mimeTypes; mPromise = promise; mAssetType = assetType; }
Example #16
Source File: GoogleFitModule.java From react-native-google-fitness with MIT License | 6 votes |
@ReactMethod public void disableFit(Promise promise) { try { Fitness .getConfigClient(mReactContext, getLastSignedInAccountSafely()) .disableFit() .continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) throws Exception { GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build(); return GoogleSignIn .getClient(mReactContext, options) .signOut(); } }) .addOnFailureListener(new SimpleFailureListener(promise)) .addOnSuccessListener(new SimpleSuccessListener(promise)); } catch (Exception e) { promise.reject(e); } }
Example #17
Source File: CameraRollManager.java From react-native-GPay with MIT License | 6 votes |
/** * Get photos from {@link MediaStore.Images}, most recent first. * * @param params a map containing the following keys: * <ul> * <li>first (mandatory): a number representing the number of photos to fetch</li> * <li> * after (optional): a cursor that matches page_info[end_cursor] returned by a * previous call to {@link #getPhotos} * </li> * <li>groupName (optional): an album name</li> * <li> * mimeType (optional): restrict returned images to a specific mimetype (e.g. * image/jpeg) * </li> * <li> * assetType (optional): chooses between either photos or videos from the camera roll. * Valid values are "Photos" or "Videos". Defaults to photos. * </li> * </ul> * @param promise the Promise to be resolved when the photos are loaded; for a format of the * parameters passed to this callback, see {@code getPhotosReturnChecker} in CameraRoll.js */ @ReactMethod public void getPhotos(final ReadableMap params, final Promise promise) { int first = params.getInt("first"); String after = params.hasKey("after") ? params.getString("after") : null; String groupName = params.hasKey("groupName") ? params.getString("groupName") : null; String assetType = params.hasKey("assetType") ? params.getString("assetType") : null; ReadableArray mimeTypes = params.hasKey("mimeTypes") ? params.getArray("mimeTypes") : null; if (params.hasKey("groupTypes")) { throw new JSApplicationIllegalArgumentException("groupTypes is not supported on Android"); } new GetPhotosTask( getReactApplicationContext(), first, after, groupName, mimeTypes, assetType, promise) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
Example #18
Source File: RNKakaoLinkModule.java From react-native-kakao-links with MIT License | 5 votes |
private void sendDefault(TemplateParams params, Promise promise, Map<String, String> serverCallbackArgsMap) { KakaoLinkService service = KakaoLinkService.getInstance(); if (serverCallbackArgsMap == null) service.sendDefault(this.getCurrentActivity(), params, new co.jootopia.kakao.link.RNKakaoLinkModule.BasicResponseCallback<KakaoLinkResponse>(promise)); else service.sendDefault(this.getCurrentActivity(), params, serverCallbackArgsMap, new co.jootopia.kakao.link.RNKakaoLinkModule.BasicResponseCallback<KakaoLinkResponse>(promise)); }
Example #19
Source File: BrightcovePlayerUtil.java From react-native-brightcove-player with MIT License | 5 votes |
@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 #20
Source File: RNLBarCodeModule.java From react-native-barcode with MIT License | 5 votes |
@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 #21
Source File: Web3WebviewModule.java From react-native-web3-webview with MIT License | 5 votes |
@ReactMethod public void isFileUploadSupported(final Promise promise) { Boolean result = false; int current = Build.VERSION.SDK_INT; if (current >= Build.VERSION_CODES.LOLLIPOP) { result = true; } if (current >= Build.VERSION_CODES.JELLY_BEAN && current <= Build.VERSION_CODES.JELLY_BEAN_MR2) { result = true; } promise.resolve(result); }
Example #22
Source File: EscPosModule.java From react-native-esc-pos with MIT License | 5 votes |
@ReactMethod public void printSample(Promise promise) { try { printerService.printSample(); promise.resolve(true); } catch (IOException e) { promise.reject(e); } }
Example #23
Source File: CookieManagerModule.java From imsdk-android with MIT License | 5 votes |
@ReactMethod public void set(ReadableMap options, final Promise promise) throws Exception { String name = null; String value = null; String domain = null; String origin = null; String path = null; String expiration = null; if (options.hasKey(OPTIONS_NAME)) { name = options.getString(OPTIONS_NAME); } if (options.hasKey(OPTIONS_VALUE)) { value = options.getString(OPTIONS_VALUE); } if (options.hasKey(OPTIONS_DOMAIN)) { domain = options.getString(OPTIONS_DOMAIN); } if (options.hasKey(OPTIONS_ORIGIN)) { origin = options.getString(OPTIONS_ORIGIN); } if (options.hasKey(OPTIONS_PATH)) { path = options.getString(OPTIONS_PATH); } if (options.hasKey(OPTIONS_EXPIRATION)) { expiration = options.getString(OPTIONS_EXPIRATION); } CookieManager.getInstance().setCookie(origin, name + "=" + value + ";" + OPTIONS_PATH + "=" + path + ";" + OPTIONS_EXPIRATION + "=" + expiration + ";" + OPTIONS_DOMAIN + "=" + domain); // throw new Exception("Cannot call on android, try setFromResponse"); }
Example #24
Source File: RNTextSizeModule.java From react-native-text-size with BSD 2-Clause "Simplified" License | 5 votes |
@Nullable private RNTextSizeConf getConf(final ReadableMap specs, final Promise promise, boolean forText) { if (specs == null) { promise.reject(E_MISSING_PARAMETER, "Missing parameter object."); return null; } return new RNTextSizeConf(specs, forText); }
Example #25
Source File: EscPosModule.java From react-native-esc-pos with MIT License | 5 votes |
@ReactMethod public void printImage(String filePath, Promise promise) { try { printerService.printImage(filePath); promise.resolve(true); } catch (IOException e) { promise.reject(e); } }
Example #26
Source File: ShareModule.java From react-native-GPay with MIT License | 5 votes |
/** * Open a chooser dialog to send text content to other apps. * * Refer http://developer.android.com/intl/ko/training/sharing/send.html * * @param content the data to send * @param dialogTitle the title of the chooser dialog */ @ReactMethod public void share(ReadableMap content, String dialogTitle, Promise promise) { if (content == null) { promise.reject(ERROR_INVALID_CONTENT, "Content cannot be null"); return; } try { Intent intent = new Intent(Intent.ACTION_SEND); intent.setTypeAndNormalize("text/plain"); if (content.hasKey("title")) { intent.putExtra(Intent.EXTRA_SUBJECT, content.getString("title")); } if (content.hasKey("message")) { intent.putExtra(Intent.EXTRA_TEXT, content.getString("message")); } Intent chooser = Intent.createChooser(intent, dialogTitle); chooser.addCategory(Intent.CATEGORY_DEFAULT); Activity currentActivity = getCurrentActivity(); if (currentActivity != null) { currentActivity.startActivity(chooser); } else { getReactApplicationContext().startActivity(chooser); } WritableMap result = Arguments.createMap(); result.putString("action", ACTION_SHARED); promise.resolve(result); } catch (Exception e) { promise.reject(ERROR_UNABLE_TO_OPEN_DIALOG, "Failed to open share dialog"); } }
Example #27
Source File: EscPosModule.java From react-native-esc-pos with MIT License | 5 votes |
@ReactMethod public void printBarcode(String code, String bc, int width, int height, String pos, String font, Promise promise) { try { printerService.printBarcode(code, bc, width, height, pos, font); promise.resolve(true); } catch (BarcodeSizeError e) { promise.reject(e); } }
Example #28
Source File: NotificationHelper.java From react-native-foreground-service with MIT License | 5 votes |
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 #29
Source File: GoogleFitModule.java From react-native-google-fitness with MIT License | 5 votes |
@ReactMethod public void history_updateData(String jsonStatement, final Promise promise) { try { DataUpdateRequest updateRequest = (DataUpdateRequest) StatementFactory .fromJson(jsonStatement) .execute(new JavaContext(), null); getHistoryClient() .updateData(updateRequest) .addOnFailureListener(new SimpleFailureListener(promise)) .addOnSuccessListener(new SimpleSuccessListener(promise)); } catch (Exception e) { Log.e(TAG, "Error in history_updateData()", e); promise.reject(e); } }
Example #30
Source File: EscPosModule.java From react-native-esc-pos with MIT License | 5 votes |
@ReactMethod public void printLn(String text, Promise promise) { try { printerService.printLn(text); promise.resolve(true); } catch (UnsupportedEncodingException e) { promise.reject(e); } }