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

The following examples show how to use com.facebook.react.bridge.Promise. These examples are extracted from open source projects. 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 Project: react-native-google-fitness   Source File: GoogleFitModule.java    License: MIT License 8 votes vote down vote up
@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 Project: react-native-GPay   Source File: ImageLoaderModule.java    License: MIT License 7 votes vote down vote up
@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 Project: react-native-image-editor   Source File: ImageEditorModule.java    License: MIT License 6 votes vote down vote up
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 4
Source Project: react-native-GPay   Source File: ClipboardModule.java    License: 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 Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: ISC License 6 votes vote down vote up
/**
 * 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 6
Source Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: ISC License 6 votes vote down vote up
/**
 * 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 7
Source Project: react-native-select-contact   Source File: SelectContactModule.java    License: MIT License 6 votes vote down vote up
/**
 * 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 8
/**
 * 导出 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 9
Source Project: react-native-google-fitness   Source File: GoogleFitModule.java    License: MIT License 6 votes vote down vote up
@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 10
Source Project: react-native-GPay   Source File: CameraRollManager.java    License: MIT License 6 votes vote down vote up
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 11
Source Project: react-native-GPay   Source File: CameraRollManager.java    License: MIT License 6 votes vote down vote up
/**
 * 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 12
Source Project: react-native-jw-media-player   Source File: RNJWPlayerModule.java    License: 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 13
Source Project: react-native-GPay   Source File: FileReaderModule.java    License: MIT License 6 votes vote down vote up
@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 14
@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 15
/**
 * 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 16
Source Project: imsdk-android   Source File: QTalkLoaclSearch.java    License: 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 17
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 18
@ReactMethod
public void createNotificationChannel(ReadableMap channelConfig, Promise promise) {
    if (channelConfig == null) {
        promise.reject(ERROR_INVALID_CONFIG, "VIForegroundService: Channel config is invalid");
        return;
    }
    NotificationHelper.getInstance(getReactApplicationContext()).createNotificationChannel(channelConfig, promise);
}
 
Example 19
@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 20
@ReactMethod
public void openWifiSettings(final Promise primise) {
    try {
        SettingsUtil.openWifiSettings(getReactApplicationContext());
        primise.resolve(null);
    } catch (Throwable ex) {
        primise.reject(ex);
    }
}
 
Example 21
@ReactMethod
public void openCelularSettings(final Promise primise) {
    try {
        SettingsUtil.openCelularSettings(getReactApplicationContext());
        primise.resolve(null);
    } catch (Throwable ex) {
        primise.reject(ex);
    }
}
 
Example 22
Source Project: react-native-fitness   Source File: RNFitnessModule.java    License: MIT License 5 votes vote down vote up
@ReactMethod
public void getDistance(double startDate, double endDate, String interval, Promise promise){
  try {
    manager.getDistance(getCurrentActivity(), startDate, endDate, interval, promise);
  }catch(Error e){
    promise.reject(e);
  }
}
 
Example 23
@ReactMethod
public void getPlaylistWithReferenceId(String referenceId, 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.getPlaylistWithReferenceId(referenceId, promise);
}
 
Example 24
Source Project: ReactNative-AndAndroid   Source File: CommModule.java    License: MIT License 5 votes vote down vote up
/**
 * Promise
 * @param msg
 * @param promise
 */
@ReactMethod
public void rnCallNativeFromPromise(String msg, Promise promise) {


    // 1.处理业务逻辑...
    String result = "处理结果:" + msg;
    Log.e("---",result);
    // 2.回调RN,即将处理结果返回给RN
    promise.resolve(result);
}
 
Example 25
/**
 * Get all the payloads received by this device
 */
@ReactMethod
public void payloads(final Promise promise) {
	WritableArray result = Arguments.createArray();

	for (String key : mReceivedPayloads.keySet()) {
		// Explode key to get serviceId, endpointId, payloadId
		//result.pushMap(endpoint.toWritableMap());
	}

	promise.resolve(result);
}
 
Example 26
Source Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: 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 27
Source Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: 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 28
Source Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: 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 29
Source Project: react-native-fitness   Source File: RNFitnessModule.java    License: MIT License 5 votes vote down vote up
@ReactMethod
public void getHeartRate(double startDate, double endDate, String interval, Promise promise){
  try {
    manager.getHeartRate(getCurrentActivity(), startDate, endDate, interval, promise);
  }catch(Error e){
    promise.reject(e);
  }
}
 
Example 30
Source Project: react-native-wifi-reborn   Source File: RNWifiModule.java    License: ISC License 5 votes vote down vote up
/**
 * Returns the IP of the currently connected WiFi network.
 */
@ReactMethod
public void getIP(final Promise promise) {
    final WifiInfo info = wifi.getConnectionInfo();
    final String stringIP = longToIP(info.getIpAddress());
    promise.resolve(stringIP);
}