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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   View source code 6 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 9
Project: RNLearn_Project1   File: ImageLoaderModule.java   View source code 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 10
Project: react-native-pgp   File: Module.java   View source code 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 11
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   View source code 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 12
Project: react-native-twilio-chat   File: RCTTwilioChatChannels.java   View source code 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 13
Project: RNLearn_Project1   File: ImageLoaderModule.java   View source code 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 14
Project: RNLearn_Project1   File: IntentModule.java   View source code 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 15
Project: RNLearn_Project1   File: IntentModule.java   View source code 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 16
Project: react-native-pgp   File: Module.java   View source code 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 17
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   View source code 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 18
Project: react-native-huashi-100u   File: HsOtgModule.java   View source code 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 19
Project: react-native-camera-face-detector   File: RCTCameraModule.java   View source code 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 20
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   View source code 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 21
Project: RNLearn_Project1   File: PermissionsModule.java   View source code 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 22
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   View source code 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 23
Project: react-native-alarm-notification   File: ANModule.java   View source code 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 24
Project: rnrecord   File: UpdateCommand.java   View source code 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 25
Project: react-native-system-setting   File: SystemSetting.java   View source code 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 26
Project: RNLearn_Project1   File: NetInfoModule.java   View source code 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 27
Project: react-native-geth   File: RNGethModule.java   View source code 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 28
Project: react-native-apptentive-module   File: RNApptentiveModule.java   View source code 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 29
Project: rnrecord   File: FindAllCommand.java   View source code 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 30
Project: react-native-connectivity-status   File: RNConnectivityStatusModule.java   View source code 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 31
Project: react-native-android-speech-recognizer   File: RNAndroidSpeechRecognizerModule.java   View source code 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 32
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 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 33
Project: react-native-geth   File: RNGethModule.java   View source code 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 34
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 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 35
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 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 36
Project: taplytics-react-native   File: TaplyticsReactModule.java   View source code 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 37
Project: react-native-settings   File: RNSettingsModule.java   View source code 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 38
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   View source code 5 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 39
Project: react-native-tensorflow   File: RNTensorFlowGraphModule.java   View source code 5 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 40
Project: react-native-leancloud-sdk   File: RNPushNotificationModule.java   View source code 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);
}