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

The following are top voted examples for showing how to use com.facebook.react.bridge.Promise. 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: ShareModule.java   Source Code and License 7 votes vote down vote up
/**
 * 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 2
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License 7 votes vote down vote up
@ReactMethod
public void getAvailableVoices(Promise promise) {
	if(notReady(promise)) return;

	try {
		WritableArray voicesList = Arguments.createArray();
		Voice[] array = tts.getVoices().toArray(new Voice[tts.getVoices().size()]);
		for(Voice voice: array) {
			WritableMap newVoice = returnMapForVoice(voice);
			voicesList.pushMap(newVoice);
		}

		promise.resolve(voicesList);
	} catch(Exception e) {
		promise.reject("not_found", "Unable to retrieve voices for getAvailableVoices()", e);
	}
}
 
Example 3
Project: react-native-image-intent   File: ImageIntentModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void getImageIntentBase64(Promise promise) {
    if (getCurrentActivity() != null) {
        Intent intent = getCurrentActivity().getIntent();
        if (intent != null) {
            String action = intent.getAction();
            String type = intent.getType();

            if (Intent.ACTION_SEND.equals(action) && type != null) {
                if (type.startsWith("image/")) {
                    encodedImage = handleSendImage(intent); // Handle single image being sent
                }
            }
        }
    }

    if (encodedImage != null) {
        promise.resolve(encodedImage);
    } else {
        promise.reject("IMAGE_NOT_FOUND");
    }
}
 
Example 4
Project: react-native-system-setting   File: SystemSetting.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void getAppBrightness(Promise promise) {
    final Activity curActivity = getCurrentActivity();
    if(curActivity == null) {
        return;
    }
    try {
        float result = curActivity.getWindow().getAttributes().screenBrightness;
        if(result < 0){
            int val = Settings.System.getInt(getReactApplicationContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            promise.resolve(val * 1.0f / 255);
        }else{
            promise.resolve(result);
        }
    } catch (Exception e) {
        e.printStackTrace();
        promise.reject("-1", "get app's brightness fail", e);
    }
}
 
Example 5
Project: react-native-geth   File: RNGethModule.java   Source Code and License 6 votes vote down vote up
/**
 * Create and send transaction.
 *
 * @param passphrase Passphrase
 * @param nonce      Account nonce (use -1 to use last known nonce)
 * @param toAddress  Address destination
 * @param amount     Amount
 * @param gasLimit   Gas limit
 * @param gasPrice   Gas price
 * @param data
 * @param promise    Promise
 * @return Return String transaction
 */
@ReactMethod
public void createAndSendTransaction(String passphrase, double nonce, String toAddress,
                                     double amount, double gasLimit, double gasPrice,
                                     String data, Promise promise) {
    try {
        Account acc = GethHolder.getAccount();
        Address fromAddress = acc.getAddress();
        BigInt chain = new BigInt(GethHolder.getNodeConfig().getEthereumNetworkID());
        Context ctx = new Context();

        if (nonce == -1) {
          nonce = GethHolder.getNode().getEthereumClient().getPendingNonceAt(ctx, fromAddress);
        }

        Transaction tx = new Transaction(
                (long) nonce,
                new Address(toAddress),
                new BigInt((long) amount),
                new BigInt((long) gasLimit),
                new BigInt((long) gasPrice),
                data.getBytes("UTF8"));

        // Sign a transaction with a single authorization
        Transaction signed = GethHolder.getKeyStore().signTxPassphrase(acc, passphrase, tx, chain);
        // Send it out to the network.
        GethHolder.getNode().getEthereumClient().sendTransaction(ctx, signed);
        promise.resolve(tx.toString());
    } catch (Exception e) {
        promise.reject(NEW_TRANSACTION_ERROR, e);
    }
}
 
Example 6
Project: react-native-fingerprint-identify   File: RNFingerprintIdentifyModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void initFingerPrintIdentify(final Promise promise) {
  currentActivity = getCurrentActivity();
  if(currentActivity != null) {
    if(this.mFingerprintIdentify == null) {
      this.mFingerprintIdentify = new FingerprintIdentify(currentActivity, new BaseFingerprint.FingerprintIdentifyExceptionListener() {
        @Override
        public void onCatchException(Throwable exception) {
          Log.d("ReactNative", "ERROR FINGERPRINT: " + exception.getLocalizedMessage());
        }
      });
    }
    sendResponse("ok", null, promise);
  } else {
    sendResponse("failed", "ERROR_INITIALIZED", promise);
  }
}
 
Example 7
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void getSessionInfo(final Promise callback) {
    Taplytics.getSessionInfo(new SessionInfoRetrievedListener() {
        @Override
        public void sessionInfoRetrieved(HashMap hashMap) {
            WritableMap resultData = new WritableNativeMap();
            if(hashMap.containsKey("session_id")){
                resultData.putString("session_id", (String) hashMap.get("session_id"));
            }
            if(hashMap.containsKey("appUser_id")){
                resultData.putString("appUser_id", (String) hashMap.get("appUser_id"));
            }

            callback.resolve(resultData);
        }
    });
}
 
Example 8
Project: RNLearn_Project1   File: ImageLoaderModule.java   Source Code and License 6 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 9
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void toGraphDef(String id, Promise promise) {
    try {
        Graph graph = graphs.get(id);
        promise.resolve(Base64.encodeToString(graph.toGraphDef(), Base64.DEFAULT));
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example 10
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void close(String id, Promise promise) {
    try {
        Graph graph = graphs.get(id);
        graph.close();
        promise.resolve(true);
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example 11
Project: react-native-pgp   File: Module.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void signB64Data(final String privKeyData, final String password, final String b64Data, Promise promise) {
  try {
    // region Decode Base64
    byte[] data = Base64.decode(b64Data, Base64.DEFAULT);
    // endregion
    // region Decode Private Key
    PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData);
    PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password);
    // endregion
    // region Sign Data
    String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo);
    WritableMap resultMap = Arguments.createMap();
    resultMap.putString("asciiArmoredSignature", signature);
    resultMap.putString("hashingAlgo",  PGPUtils.hashAlgoToString(signatureAlgo));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint()));
    promise.resolve(resultMap);
    // endregion
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 12
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void getEnginesInfo(Promise promise) {
	if(notReady(promise)) return;

	try {
		WritableArray ttsInfo = Arguments.createArray();

		List<TextToSpeech.EngineInfo> engineList = tts.getEngines();
		Iterator iterator = engineList.iterator();
		while(iterator.hasNext()) {
			ttsInfo.pushString(iterator.next().toString());
		}

		promise.resolve(ttsInfo);
	} catch(Exception e) {
		promise.reject("error", "Unable to retrieve TTS Engine info for getEnginesInfo()", e);
	}
}
 
Example 13
Project: react-native-twilio-chat   File: RCTTwilioChatChannels.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void createChannel(ReadableMap options, final Promise promise) {
    final JSONObject attributes = RCTConvert.readableMapToJson(options.getMap("attributes"));
    final String uniqueName = options.getString("uniqueName");
    String friendlyName = options.getString("friendlyName");
    Channel.ChannelType type = (options.getString("type").compareTo("CHANNEL_TYPE_PRIVATE") == 0) ? Channel.ChannelType.PRIVATE : Channel.ChannelType.PUBLIC;

    channels().channelBuilder()
            .withUniqueName(uniqueName)
            .withFriendlyName(friendlyName)
            .withType(type)
            .withAttributes(attributes)
            .build(new CallbackListener<Channel>() {
                @Override
                public void onError(final ErrorInfo errorInfo) {
                    super.onError(errorInfo);
                    promise.reject("create-channel-error", "Error occurred while attempting to createChannel.");
                }

                @Override
                public void onSuccess(final Channel newChannel) {
                    promise.resolve(RCTConvert.Channel(newChannel));
                }
            });
}
 
Example 14
Project: RNLearn_Project1   File: ImageLoaderModule.java   Source Code and License 6 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 15
Project: RNLearn_Project1   File: IntentModule.java   Source Code and 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 16
Project: RNLearn_Project1   File: IntentModule.java   Source Code and License 6 votes vote down vote up
/**
 * Return the URL the activity was started with
 *
 * @param promise a promise which is resolved with the initial URL
 */
@ReactMethod
public void getInitialURL(Promise promise) {
  try {
    Activity currentActivity = getCurrentActivity();
    String initialURL = null;

    if (currentActivity != null) {
      Intent intent = currentActivity.getIntent();
      String action = intent.getAction();
      Uri uri = intent.getData();

      if (Intent.ACTION_VIEW.equals(action) && uri != null) {
        initialURL = uri.toString();
      }
    }

    promise.resolve(initialURL);
  } catch (Exception e) {
    promise.reject(new JSApplicationIllegalArgumentException(
        "Could not get the initial URL : " + e.getMessage()));
  }
}
 
Example 17
Project: react-native-pgp   File: Module.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void signData(final String privKeyData, final String password, final String data, Promise promise) {
  try {
    // region Decode Private Key
    PGPSecretKey secKey = PGPUtils.getSecretKey(privKeyData);
    PGPPrivateKey privKey = PGPUtils.decryptArmoredPrivateKey(secKey, password);
    // endregion
    // region Sign Data
    String signature = PGPUtils.signArmoredAscii(privKey, data, signatureAlgo);
    WritableMap resultMap = Arguments.createMap();
    resultMap.putString("asciiArmoredSignature", signature);
    resultMap.putString("hashingAlgo",  PGPUtils.hashAlgoToString(signatureAlgo));
    resultMap.putString("fingerPrint", Utils.bytesToHex(secKey.getPublicKey().getFingerprint()));
    promise.resolve(resultMap);
    // endregion
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 18
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   Source Code and License 6 votes vote down vote up
/**
    * Feed paper to the printer (roll out blank paper)
    *
    * @param linesQuantity
    * @param promise
    */
@ReactMethod
public void feedPaper(int linesQuantity, Promise promise) {
	if (linesQuantity < 0 || linesQuantity > 255) {
		promise.reject("AMOUNT_LINES_0_255");
		return;
	}
	try {
		mPrinter.feedPaper(linesQuantity);
		mPrinter.flush();

		promise.resolve("PAPER_FED");
	} catch (Exception e) {
		promise.reject("Erro: " + e.getMessage());
	}
}
 
Example 19
Project: react-native-huashi-100u   File: HsOtgModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void auth(Promise promise) {
    if (HSinterface == null){
        promise.reject("-1", "init failed");
        return;
    }
    int ret = HSinterface.Authenticate();
    WritableMap result = new WritableNativeMap();
    if (ret == 1){
        result.putString("code", ret+"");
        result.putString("msg", "success");
        promise.resolve(result);
    }else if (ret == 2){
        result.putString("code", ret+"");
        result.putString("msg", "auth failed");
        promise.resolve(result);
    }else if (ret == 0){
        promise.reject("0", "connect failed");
    }
}
 
Example 20
Project: react-native-camera-face-detector   File: RCTCameraModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void capture(final ReadableMap options, final Promise promise) {
    int orientation = options.hasKey("orientation") ? options.getInt("orientation") : RCTCamera.getInstance().getOrientation();
    if (orientation == RCT_CAMERA_ORIENTATION_AUTO) {
        _sensorOrientationChecker.onResume();
        _sensorOrientationChecker.registerOrientationListener(new RCTSensorOrientationListener() {
            @Override
            public void orientationEvent() {
                int deviceOrientation = _sensorOrientationChecker.getOrientation();
                _sensorOrientationChecker.unregisterOrientationListener();
                _sensorOrientationChecker.onPause();
                captureWithOrientation(options, promise, deviceOrientation);
            }
        });
    } else {
        captureWithOrientation(options, promise, orientation);
    }
}
 
Example 21
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   Source Code and License 5 votes vote down vote up
/**
 * Asks to enable location services.
 */
@ReactMethod
public void enableLocation(final Promise promise) {
  mGoogleApiClient = new GoogleApiClient.Builder(getReactApplicationContext())
          .addApi(LocationServices.API)
          .addConnectionCallbacks(this)
          .addOnConnectionFailedListener(this)
          .build();

  mGoogleApiClient.connect();

  promise.resolve(true);
}
 
Example 22
Project: RNLearn_Project1   File: PermissionsModule.java   Source Code and License 5 votes vote down vote up
/**
 * Check if the app has the permission given. successCallback is called with true if the
 * permission had been granted, false otherwise. See {@link Activity#checkSelfPermission}.
 */
@ReactMethod
public void checkPermission(final String permission, final Promise promise) {
  Context context = getReactApplicationContext().getBaseContext();
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    promise.resolve(context.checkPermission(permission, Process.myPid(), Process.myUid()) ==
      PackageManager.PERMISSION_GRANTED);
    return;
  }
  promise.resolve(context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
 
Example 23
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   Source Code and License 5 votes vote down vote up
/**
    * Print custom text
    *
    * @param text
    * @param promise
    */
@ReactMethod
public void printText(String text, Promise promise) {
	String charset = "ISO-8859-1";
	try {
		mPrinter.printTaggedText(text, charset);
		mPrinter.flush();

		promise.resolve("PRINTED");
	} catch (Exception e) {
		promise.reject("Erro: " + e.getMessage());
	}
}
 
Example 24
Project: react-native-alarm-notification   File: ANModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getScheduledAlarms(Promise promise) {
    ArrayList<Bundle> bundles = anHelper.getScheduledAlarms();
    WritableArray array = Arguments.createArray();
    for(Bundle bundle:bundles){
        array.pushMap(Arguments.fromBundle(bundle));
    }
    promise.resolve(array);
}
 
Example 25
Project: rnrecord   File: UpdateCommand.java   Source Code and License 5 votes vote down vote up
private void executeDbCallsAsync(final String tableName, final Promise promise, final ContentValues contentValues) {
    new GuardedAsyncTask(reactContext) {
        @Override
        protected void doInBackgroundGuarded(Object[] params) {
            SQLiteDatabase db = rnRecordSQLiteHelper.getWritableDatabase();

            promise.resolve(db.update(tableName, contentValues, "id = ?", new String[] {contentValues.getAsString("id")} ));

        }
    }.execute();
}
 
Example 26
Project: react-native-system-setting   File: SystemSetting.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getScreenMode(Promise promise) {
    try {
        int mode = Settings.System.getInt(getReactApplicationContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        promise.resolve(mode);
    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
        promise.reject("-1", "get screen mode fail", e);
    }
}
 
Example 27
Project: RNLearn_Project1   File: NetInfoModule.java   Source Code and 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 28
Project: react-native-geth   File: RNGethModule.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the default account at the given index in the listAccounts.
 *
 * @param accID   index in the listAccounts
 * @param promise Promise
 * @return Return true if sets.
 */
@ReactMethod
public void setAccount(Integer accID, Promise promise) {
    try {
        Account acc = GethHolder.getKeyStore().getAccounts().get(accID);
        GethHolder.setAccount(acc);
        //accounts.set(0, acc);
        promise.resolve(true);
    } catch (Exception e) {
        promise.reject(SET_ACCOUNT_ERROR, e);
    }
}
 
Example 29
Project: react-native-apptentive-module   File: RNApptentiveModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void addPersonDataNumber(final Number number, final String key, final Promise promise)
{
	if (!_initialised)
	{
		promise.reject(APPTENTIVE, "Apptentive is not initialised");
		return;
	}
	if (number == null)
	{
		promise.reject(APPTENTIVE, "Your number is empty");
		return;
	}
	if (key == null || key.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your key is empty");
		return;
	}

	Handler handler = new Handler(_application.getMainLooper());
	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			Apptentive.addCustomPersonData(key, number);
			promise.resolve(true);
		}
	};
	handler.post(runnable);
}
 
Example 30
Project: rnrecord   File: FindAllCommand.java   Source Code and License 5 votes vote down vote up
private void executeDbCallsAsync(final String tableName, final Promise promise) {
    new GuardedAsyncTask(reactContext) {
        @Override
        protected void doInBackgroundGuarded(Object[] params) {
            SQLiteDatabase db = rnRecordSQLiteHelper.getWritableDatabase();

            promise.resolve(transformQueryResults(db.rawQuery("select * from " + tableName, null)));

        }
    }.execute();
}
 
Example 31
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   Source Code and License 5 votes vote down vote up
/**
 * Asks to enable bluetooth
 */
@ReactMethod
public void enableBluetooth(final Promise promise) {
  try {
    if (!checkBluetooth()) {
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      getReactApplicationContext().startActivityForResult(enableBtIntent, NEAR_BLUETOOTH_SETTINGS_CODE, new Bundle());
    }

    promise.resolve(true);
  } catch (Exception e) {
    promise.reject("BLE_ACTIVATION_ERROR", e.getMessage());
  }
}
 
Example 32
Project: react-native-android-speech-recognizer   File: RNAndroidSpeechRecognizerModule.java   Source Code and License 5 votes vote down vote up
private void doCreateSpeechRecognizer(final Promise promise) {
  this.speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this.reactContext);
  this.speechRecognizer.setRecognitionListener(new ListenerMapRecognitionListener(
    this.enabledEvents,
    this.reactContext.getJSModule(RCTNativeAppEventEmitter.class),
    this.eventPrefix
  ));
  promise.resolve(null);
}
 
Example 33
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void _newSyncObject(String name, String defaultValue, Promise callback) {
    try {
        JSONObject object = new JSONObject(defaultValue);
        TaplyticsVar var = new TaplyticsVar<>(name, object);
        callback.resolve(((JSONObject) var.get()).toString());
    } catch (JSONException e) {
        callback.reject(tagName, e.getMessage());
    }
}
 
Example 34
Project: react-native-geth   File: RNGethModule.java   Source Code and License 5 votes vote down vote up
/**
 * Creates and configures a new Geth node.
 *
 * @param config  Json object configuration node
 * @param promise Promise
 * @return Return true if created and configured node
 */
@ReactMethod
public void nodeConfig(ReadableMap config, Promise promise) {
    try {
        NodeConfig nc = GethHolder.getNodeConfig();
        String nodeDir = ETH_DIR;
        String keyStoreDir = KEY_STORE_DIR;

        if (config.hasKey("enodes"))
            GethHolder.writeStaticNodesFile(config.getString("enodes"));
        if (config.hasKey("chainID")) nc.setEthereumNetworkID(config.getInt("chainID"));
        if (config.hasKey("maxPeers")) nc.setMaxPeers(config.getInt("maxPeers"));
        if (config.hasKey("genesis")) nc.setEthereumGenesis(config.getString("genesis"));
        if (config.hasKey("nodeDir")) nodeDir = config.getString("nodeDir");
        if (config.hasKey("keyStoreDir")) keyStoreDir = config.getString("keyStoreDir");

        Node nd = Geth.newNode(getReactApplicationContext()
                .getFilesDir() + "/" + nodeDir, nc);

        KeyStore ks = new KeyStore(getReactApplicationContext()
                .getFilesDir() + "/" + keyStoreDir, Geth.LightScryptN, Geth.LightScryptP);

        GethHolder.setNodeConfig(nc);
        GethHolder.setKeyStore(ks);
        GethHolder.setNode(nd);

        promise.resolve(true);
    } catch (Exception e) {
        promise.reject(CONFIG_NODE_ERROR, e);
    }
}
 
Example 35
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getRunningExperimentsAndVariations(final Promise callback) {
    Taplytics.getRunningExperimentsAndVariations(new TaplyticsRunningExperimentsListener() {
        @Override
        public void runningExperimentsAndVariation(Map<String, String> map) {
            callback.resolve(map);
        }
    });
}
 
Example 36
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void startNewSession(final Promise callback) {
    Taplytics.startNewSession(new TaplyticsNewSessionListener() {
        @Override
        public void onNewSession() {
            callback.resolve(null);
        }
    });
}
 
Example 37
Project: taplytics-react-native   File: TaplyticsReactModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void setPushSubscriptionEnabled(final boolean enabled, final Promise callback) {
    Taplytics.setPushSubscriptionEnabled(enabled, new TaplyticsPushSubscriptionChangedListener() {
        @Override
        public void success() {
            callback.resolve(null);
        }

        @Override
        public void failure() {
            callback.reject("Taplytics", "Failed to set push subscription enabled status");
        }
    });
}
 
Example 38
Project: react-native-settings   File: RNSettingsModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void openSetting(String setting, final Promise promise) {
  mSettingsPromise = promise;

  try {
    Activity currentActivity = getCurrentActivity();
    final Intent settingsIntent = new Intent(setting);
    currentActivity.startActivityForResult(settingsIntent, mOpenSettingToRequestCode.get(setting));
  } catch (Exception e) {
    mSettingsPromise.reject(E_FAILED_TO_OPEN_SETTINGS, e);
    mSettingsPromise = null;
  }
}
 
Example 39
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getDefaultLocale(Promise promise) {
	if(notReady(promise)) return;
	
	try {
		Locale defaultLocale;

		if(Build.VERSION.SDK_INT >= 21)	
			defaultLocale = tts.getDefaultVoice().getLocale();
		else 
			defaultLocale = tts.getDefaultLanguage();

		WritableMap map = returnMapForLocale(defaultLocale);
		promise.resolve(map);
	} catch(Exception e) {
		promise.reject("error", "Unable to retrieve locale for getDefaultLocale()", e);
	}
}
 
Example 40
Project: react-native-leancloud-sdk   File: RNPushNotificationModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getInitialNotification(Promise promise) {
    WritableMap params = Arguments.createMap();
    Activity activity = getCurrentActivity();
    if (activity != null) {
        Intent intent = activity.getIntent();
        Bundle bundle = intent.getBundleExtra("notification");
        if (bundle != null) {
            bundle.putBoolean("foreground", false);
            String bundleString = mJsDelivery.convertJSON(bundle);
            params.putString("dataJSON", bundleString);
        }
    }
    promise.resolve(params);
}
 
Example 41
Project: react-native-threads   File: RNThreadModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void startThread(final String jsFileName, final Promise promise) {
  Log.d(TAG, "Starting web thread - " + jsFileName);

  String jsFileSlug = jsFileName.contains("/") ? jsFileName.replaceAll("/", "_") : jsFileName;

  JSBundleLoader bundleLoader = getDevSupportManager().getDevSupportEnabled()
          ? createDevBundleLoader(jsFileName, jsFileSlug)
          : createReleaseBundleLoader(jsFileName, jsFileSlug);

  try {
    ArrayList<ReactPackage> threadPackages = new ArrayList<ReactPackage>(Arrays.asList(additionalThreadPackages));
    threadPackages.add(0, new ThreadBaseReactPackage(getReactInstanceManager()));

    ReactContextBuilder threadContextBuilder = new ReactContextBuilder(getReactApplicationContext())
            .setJSBundleLoader(bundleLoader)
            .setDevSupportManager(getDevSupportManager())
            .setReactInstanceManager(getReactInstanceManager())
            .setReactPackages(threadPackages);

    JSThread thread = new JSThread(jsFileSlug);
    thread.runFromContext(
            getReactApplicationContext(),
            threadContextBuilder
    );
    threads.put(thread.getThreadId(), thread);
    promise.resolve(thread.getThreadId());
  } catch (Exception e) {
    promise.reject(e);
    getDevSupportManager().handleException(e);
  }
}
 
Example 42
Project: react-native-cameraroll   File: RNCameraRollModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getAssets(final ReadableMap params, final Promise promise) {
    String start = params.hasKey("start") ? params.getString("start") : null;
    int limit = params.getInt("limit");
    String assetType = params.getString("assetType");

    new GetAssetsTask(
            getReactApplicationContext(),
            start,
            limit,
            assetType,
            promise)
            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 43
Project: react-native-cameraroll   File: RNCameraRollModule.java   Source Code and License 5 votes vote down vote up
private GetAssetsTask(
        ReactContext context,
        @Nullable String start,
        int limit,
        @Nullable String assetType,
        Promise promise) {
    super(context);
    mContext = context;
    mStart = start;
    mLimit = limit;
    mAssetType = assetType;
    mPromise = promise;
}
 
Example 44
Project: react-native-camera   File: RCTCameraModule.java   Source Code and License 5 votes vote down vote up
private void record(final ReadableMap options, final Promise promise) {
    if (mRecordingPromise != null) {
        return;
    }

    mCamera = RCTCamera.getInstance().acquireCameraInstance(options.getInt("type"));
    if (mCamera == null) {
        promise.reject(new RuntimeException("No camera found."));
        return;
    }

    Throwable prepareError = prepareMediaRecorder(options);
    if (prepareError != null) {
        promise.reject(prepareError);
        return;
    }

    try {
        mMediaRecorder.start();
        MRStartTime =  System.currentTimeMillis();
        mRecordingOptions = options;
        mRecordingPromise = promise;  // only got here if mediaRecorder started
    } catch (Exception ex) {
        Log.e(TAG, "Media recorder start error.", ex);
        promise.reject(ex);
    }
}
 
Example 45
Project: react-native-camera   File: RCTCameraModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void hasFlash(ReadableMap options, final Promise promise) {
    Camera camera = RCTCamera.getInstance().acquireCameraInstance(options.getInt("type"));
    if (null == camera) {
        promise.reject("No camera found.");
        return;
    }
    List<String> flashModes = camera.getParameters().getSupportedFlashModes();
    promise.resolve(null != flashModes && !flashModes.isEmpty());
}
 
Example 46
Project: react-native-geth   File: RNGethModule.java   Source Code and License 5 votes vote down vote up
/**
 * Changes the passphrase of current account.
 *
 * @param oldPassphrase Passphrase
 * @param newPassphrase New passphrase
 * @param promise       Promise
 * @return Return true if passphrase changed
 */
@ReactMethod
public void updateAccount(String oldPassphrase, String newPassphrase, Promise promise) {
    try {
        Account acc = GethHolder.getAccount();
        if (acc != null) {
            GethHolder.getKeyStore().updateAccount(acc, oldPassphrase, newPassphrase);
            promise.resolve(true);
        } else {
            promise.reject(UPDATE_ACCOUNT_ERROR, "call method setAccount() before");
        }
    } catch (Exception e) {
        promise.reject(UPDATE_ACCOUNT_ERROR, e);
    }
}
 
Example 47
Project: react-native-apptentive-module   File: RNApptentiveModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void addDeviceDataNumber(final Number number, final String key, final Promise promise)
{
	if (!_initialised)
	{
		promise.reject(APPTENTIVE, "Apptentive is not initialised");
		return;
	}
	if (number == null)
	{
		promise.reject(APPTENTIVE, "Your number is empty");
		return;
	}
	if (key == null || key.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your key is empty");
		return;
	}

	Handler handler = new Handler(_application.getMainLooper());
	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			Apptentive.addCustomDeviceData(key, number);
			promise.resolve(true);
		}
	};
	handler.post(runnable);
}
 
Example 48
Project: RNRxBluetooth   File: RNRxBluetoothModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void startDiscovery(Promise promise) {
    if (debug) {
        Log.d(TAG, "request discovery: start...");
    }
    boolean result = rxBluetooth.startDiscovery();
    if (result) {
        promise.resolve(null);
    } else {
        promise.reject(new RuntimeException("could not start discovery"));
    }
}
 
Example 49
Project: react-native-cafe-bazaar   File: CafeBazaar.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void consume(String sku,final Promise promise){
  if(userInvo!=null){
    if(userInvo.hasPurchase(sku)){
      mHelper.consumeAsync(userInvo.getPurchase(sku),
      new IabHelper.OnConsumeFinishedListener() {
      public void onConsumeFinished(Purchase purchase, IabResult result) {
        WritableMap params = Arguments.createMap();
         if (result.isSuccess()) {
            // provision the in-app purchase to the user
            promise.resolve(gson.toJson(purchase));
         }
         else {
            // handle error
            promise.reject(E_CONSUME_FAILURE,result.getMessage());
         }
        }
     });
    }
    else{
      promise.reject(E_CONSUME_ERROR,"user did not purchase item");
    }
  }
  else{
    promise.reject(E_CONSUME_INITIAL,"inventory not loaded!");
  }
}
 
Example 50
Project: react-native-telephony-apis   File: RNReactNativeTelephonyModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getPhoneNumber(Promise promise){
  TelephonyManager manager = (TelephonyManager) this.reactContext.getSystemService(Context.TELEPHONY_SERVICE);
  String phoneNumber = manager.getLine1Number();
  WritableMap map = Arguments.createMap();
  map.putString("phoneNumber", phoneNumber);

  promise.resolve(map);
}
 
Example 51
Project: react-native-cafe-bazaar   File: CafeBazaar.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void open(final Promise promise) {
    mHelper = new IabHelper(_reactContext, LICENSE_KEY);

    // enable debug logging (for a production application, you should set this to false).
    mHelper.enableDebugLogging(false);

    // Start setup. This is asynchronous and the specified listener
    // will be called once setup completes.
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {

            if (result.isSuccess()) {
              promise.resolve(gson.toJson(result));
            }
            else{
              // Have we been disposed of in the meantime? If so, quit.
              if (mHelper == null) {
                promise.reject(E_SETUP_DISCONNECT,"there no connection to cafe bazaar!");
              }
              else{
                // Oh noes, there was a problem.
                promise.reject(E_SETUP_ERROR,"There is a problem in cafe bazaar setup");
              }
            }
        }
    });
}
 
Example 52
Project: react-native-twilio-chat   File: RCTTwilioChatChannels.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getChannel(String sid, final Promise promise) {
    loadChannelFromSid(sid, new CallbackListener<Channel>() {
        @Override
        public void onError(final ErrorInfo errorInfo) {
            super.onError(errorInfo);
            promise.reject("get-channel-error", "Error occurred while attempting to getChannel.");
        }

        @Override
        public void onSuccess(final Channel channel) {
            promise.resolve(RCTConvert.Channel(channel));
        }
    });
}
 
Example 53
Project: rnrecord   File: DeleteCommand.java   Source Code and License 5 votes vote down vote up
private void executeDbCallsAsync(final String tableName, final Promise promise, final int id) {
    new GuardedAsyncTask(reactContext) {
        @Override
        protected void doInBackgroundGuarded(Object[] params) {
            SQLiteDatabase db = rnRecordSQLiteHelper.getWritableDatabase();

            promise.resolve(db.delete(tableName, "id = ?", new String[] {String.valueOf(id)} ));

        }
    }.execute();
}
 
Example 54
Project: react-native-secure-key-store   File: RNSecureKeyStoreModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void remove(String alias, Promise promise) {
  Storage.resetValues(getContext(), new String[] { 
    Constants.SKS_DATA_FILENAME + alias, 
    Constants.SKS_KEY_FILENAME + alias, 
  });
  promise.resolve("cleared alias");
}
 
Example 55
Project: react-native-network-connection-class   File: Module.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void getSamplingState(Promise promise) {
  try {
    Boolean samplingState = mDeviceBandwidthSampler.isSampling();
    promise.resolve(samplingState);
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example 56
Project: react-native-twilio-chat   File: RCTTwilioChatClient.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void createClient(String token, ReadableMap props, final Promise promise) {
    final RCTTwilioChatClient tmp = RCTTwilioChatClient.getInstance();
    ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();

    if (props != null) {
        if (props.hasKey("initialMessageCount")) {
            builder.setInitialMessageCount(props.getInt("initialMessageCount"));
        }
        if (props.hasKey("synchronizationStrategy")) {
            builder.setSynchronizationStrategy(ChatClient.SynchronizationStrategy.valueOf(props.getString("synchronizationStrategy")));
        }
    }

    ChatClient.create(reactContext, token, builder.createProperties(), new CallbackListener<ChatClient>() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            super.onError(errorInfo);
            promise.reject("create-client-error", "Error occurred while attempting to create the client. Error Message: " + errorInfo.getErrorText());
        }

        @Override
        public void onSuccess(ChatClient twilioChatClient) {
            tmp.client = twilioChatClient;
            tmp.client.setListener(tmp);
            promise.resolve(RCTConvert.ChatClient(tmp.client));
        }
    });
}
 
Example 57
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void stop(Promise promise) {
	if(notReady(promise)) return;

	int result = tts.stop();
	if(result == TextToSpeech.SUCCESS) {
		promise.resolve("success");
	} else {
		promise.reject("error", "Unknown error code at stop()");
	}
}
 
Example 58
Project: react-native-sunmi-inner-printer   File: SunmiInnerPrinterModule.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化打印机,重置打印机的逻辑程序,但不清空缓存区数据,因此
 * 未完成的打印作业将在重置后继续
 *
 * @return
 */
@ReactMethod
public void printerInit(final Promise p) {
    final IWoyouService printerService = woyouService;
    ThreadPoolManager.getInstance().executeTask(new Runnable() {
        @Override
        public void run() {
            try {
                printerService.printerInit(new ICallback.Stub() {
                    @Override
                    public void onRunResult(boolean isSuccess) {
                        if (isSuccess) {
                            p.resolve(null);
                        } else {
                            p.reject("0", isSuccess + "");
                        }
                    }

                    @Override
                    public void onReturnString(String result) {
                        p.resolve(result);
                    }

                    @Override
                    public void onRaiseException(int code, String msg) {
                        p.reject("" + code, msg);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "ERROR: " + e.getMessage());
                p.reject("" + 0, e.getMessage());
            }
        }
    });
}
 
Example 59
Project: react-native-apptentive-module   File: RNApptentiveModule.java   Source Code and License 5 votes vote down vote up
@ReactMethod
public void addPersonDataString(final String string, final String key, final Promise promise)
{
	if (!_initialised)
	{
		promise.reject(APPTENTIVE, "Apptentive is not initialised");
		return;
	}
	if (string == null || string.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your string is empty");
		return;
	}
	if (key == null || key.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your key is empty");
		return;
	}

	Handler handler = new Handler(_application.getMainLooper());
	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			Apptentive.addCustomPersonData(key, string);
			promise.resolve(true);
		}
	};
	handler.post(runnable);
}
 
Example 60
Project: react-native-touch-id-android   File: FingerprintModule.java   Source Code and License 5 votes vote down vote up
private void sendResponse(String status, String message, Promise promise) {
    Reprint.cancelAuthentication();
    response = Arguments.createMap();
    response.putString("status", status);
    response.putString("error", message);
    promise.resolve(response);
}