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

The following are top voted examples for showing how to use com.facebook.react.bridge.ReactMethod. 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: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   View source code 7 votes vote down vote up
@ReactMethod 
public void getAvailableLocales(Promise promise) {
	if(notReady(promise)) return;
	
	try {
		WritableArray localeList = Arguments.createArray();
		Locale[] localesArray = Locale.getAvailableLocales();
		for(Locale locale: localesArray) {
			int isAvailable = tts.isLanguageAvailable(locale);
			if(isAvailable == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
				WritableMap newLocale = returnMapForLocale(locale);
				localeList.pushMap(newLocale);
			}
		}

		promise.resolve(localeList);
	} catch(Exception e) {
		promise.reject("error", "Unable to retrieve locales for getAvailableLocales()", e);
	}
}
 
Example 2
Project: react-native-webrtc   File: WebRTCModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void mediaStreamTrackStop(final String id) {
    // Is this functionality equivalent to `mediaStreamTrackRelease()` ?
    // if so, we should merge this two and remove track from stream as well.
    MediaStreamTrack track = mMediaStreamTracks.get(id);
    if (track == null) {
        Log.d(TAG, "mediaStreamTrackStop() track is null");
        return;
    }
    track.setEnabled(false);
    if (track.kind().equals("video")) {
        removeVideoCapturer(id);
    }
    mMediaStreamTracks.remove(id);
    // What exactly does `detached` mean in doc?
    // see: https://www.w3.org/TR/mediacapture-streams/#track-detached
}
 
Example 3
Project: react-native-webrtc   File: WebRTCModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void mediaStreamTrackRelease(final String streamId, final String _trackId) {
    MediaStream stream = mMediaStreams.get(streamId);
    if (stream == null) {
        Log.d(TAG, "mediaStreamTrackRelease() stream is null");
        return;
    }
    MediaStreamTrack track = mMediaStreamTracks.get(_trackId);
    if (track == null) {
        Log.d(TAG, "mediaStreamTrackRelease() track is null");
        return;
    }
    track.setEnabled(false); // should we do this?
    mMediaStreamTracks.remove(_trackId);
    if (track.kind().equals("audio")) {
        stream.removeTrack((AudioTrack)track);
    } else if (track.kind().equals("video")) {
        stream.removeTrack((VideoTrack)track);
        removeVideoCapturer(_trackId);
    }
    imagePorcessingHandler.removeCallbacksAndMessages(null);
    imageProcessingThread.quit();
}
 
Example 4
Project: react-native-datecs-printer   File: RNDatecsPrinterModule.java   View source code 6 votes vote down vote up
/**
 * Get list of paired devices
 *
 * @param promise
 */
@ReactMethod
public void getPairedDevices(Promise promise){
	Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
	// it might need to be an react.bridge.WritableArray
	ArrayList list = new ArrayList();
	for(BluetoothDevice device : pairedDevices){
		list.add(device);
	}

	if(list.size() > 0){
		promise.resolve(list);
	}else{
		promise.reject("Nenhum dispositivo pareado.");
	}
}
 
Example 5
Project: react-native-ethereum   File: TestNative.java   View source code 6 votes vote down vote up
@ReactMethod
public void test(String message, Callback cb) {
    try {
        android.util.Log.d("before", "yay");
        NodeHolder nh = NodeHolder.getInstance();
        Node node = nh.getNode();
        Context ctx = new Context();
        if (node != null) {
            NodeInfo info = node.getNodeInfo();
            EthereumClient ethereumClient = node.getEthereumClient();
            Account newAcc = nh.getAcc();
            BigInt balanceAt = ethereumClient.getBalanceAt(ctx, new Address("0x22B84d5FFeA8b801C0422AFe752377A64Aa738c2"), -1);
            cb.invoke(balanceAt.toString() + " ether found address:" + newAcc.getAddress().getHex());
            return;
        }
        cb.invoke("node was null");
    } catch (Exception e) {
        android.util.Log.d("", e.getMessage());
        e.printStackTrace();
    }
}
 
Example 6
Project: react-native-sync-adapter   File: SyncAdapterModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void syncImmediately(int syncInterval, int syncFlexTime) {
    boolean allowForeground = Boolean.valueOf(getReactApplicationContext().getString(R.string.rnsb_allow_foreground));

    if (!allowForeground && HeadlessService.isAppOnForeground(getReactApplicationContext())) {
        if (getCurrentActivity() != null) {
            Toast.makeText(
                    getCurrentActivity(),
                    "This sync task has not been configured to run on the foreground!",
                    Toast.LENGTH_SHORT)
                    .show();
        }
        return;
    }

    SyncAdapter.syncImmediately(getReactApplicationContext(), syncInterval, syncFlexTime);
}
 
Example 7
Project: RNLearn_Project1   File: LocationModule.java   View source code 6 votes vote down vote up
/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and
 *        highAccuracy (boolean)
 */
@ReactMethod
public void getCurrentPosition(
    ReadableMap options,
    final Callback success,
    Callback error) {
  LocationOptions locationOptions = LocationOptions.fromReactMap(options);

  try {
    LocationManager locationManager =
        (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
    if (provider == null) {
      error.invoke(PositionError.buildError(
              PositionError.PERMISSION_DENIED,
              "No location provider available."));
      return;
    }
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null &&
        SystemClock.currentTimeMillis() - location.getTime() < locationOptions.maximumAge) {
      success.invoke(locationToMap(location));
      return;
    }
    new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error)
        .invoke();
  } catch (SecurityException e) {
    throwLocationPermissionMissing(e);
  }
}
 
Example 8
Project: react-native-apptentive-module   File: RNApptentiveModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void register(final String appKey, final String signature, final Promise promise)
{
	if (_initialised)
	{
		promise.reject(APPTENTIVE, "Apptentive is already initialised");
		return;
	}
	if (appKey == null || appKey.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your appKey is empty");

		return;
	}
	if (signature == null || signature.isEmpty())
	{
		promise.reject(APPTENTIVE, "Your signature is empty");
		return;
	}

	Handler handler = new Handler(_application.getMainLooper());
	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			Apptentive.register(_application, appKey, signature);
			promise.resolve(true);
			_initialised = true;
		}
	};
	handler.post(runnable);
}
 
Example 9
Project: react-native-twilio-chat   File: RCTTwilioChatPaginator.java   View source code 6 votes vote down vote up
@ReactMethod
public void requestNextPageChannelDescriptors(String sid, final Promise promise) {
    final RCTTwilioChatPaginator tmp = RCTTwilioChatPaginator.getInstance();
    Paginator<ChannelDescriptor> _paginator = (Paginator<ChannelDescriptor>)tmp.paginators.get(sid);

    _paginator.requestNextPage(new CallbackListener<Paginator<ChannelDescriptor>>() {
        @Override
        public void onError(ErrorInfo errorInfo) {
            super.onError(errorInfo);
            promise.reject("request-next-page", "Error occurred while attempting to request the next page. Error Message: " + errorInfo.getErrorText());
        }

        @Override
        public void onSuccess(Paginator<ChannelDescriptor> paginator) {
            String uuid = RCTTwilioChatPaginator.setPaginator(paginator);
            promise.resolve(RCTConvert.Paginator(paginator, uuid, "ChannelDescriptor"));
        }
    });
}
 
Example 10
Project: react-native-sunmi-inner-printer   File: SunmiInnerPrinterModule.java   View source code 6 votes vote down vote up
/**
 * 退出缓冲模式
 *
 * @param commit: 是否打印出缓冲区内容
 */
@ReactMethod
public void exitPrinterBuffer(boolean commit) {
    final IWoyouService ss = woyouService;
    Log.i(TAG, "come: " + commit + " ss:" + ss);
    final boolean com = commit;
    ThreadPoolManager.getInstance().executeTask(new Runnable() {
        @Override
        public void run() {
            try {
                ss.exitPrinterBuffer(com);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "ERROR: " + e.getMessage());
            }
        }
    });
}
 
Example 11
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 12
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 13
Project: FingerPrint-Authentication-With-React-Native-Android   File: BiometricModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void retrieveCredentials(Callback errorCallbackCred, Callback successCallbackCred) {

    //Read encrypted JSON from file system
    String encryptedJSONFromFile = readFromFile();

    //decrypt data from file system
    String decryptedJSON = decryptText(encryptedJSONFromFile);

    if (null != decryptedJSON) {
        try {
            JSONObject decryptedJSONObject = new JSONObject(decryptedJSON);
            successCallbackCred.invoke(decryptedJSONObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
            errorCallbackCred.invoke("Failed to retrieve Credentials");
        }
    } else {
        errorCallbackCred.invoke("Failed to retrieve Credentials");
    }
}
 
Example 14
Project: react-native-touch-id-android   File: FingerprintModule.java   View source code 6 votes vote down vote up
@ReactMethod
public void isSensorAvailable(final Promise promise) {
    
    response = Arguments.createMap();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(mReactContext, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            sendResponse("failed", "You haven't allow this app to use your fingerprint sensor", promise);
            return;
        }
        
        if (mReactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT) ||
            ((FingerprintManager) mReactContext.getSystemService(Context.FINGERPRINT_SERVICE)).isHardwareDetected()) {
            if (((FingerprintManager) mReactContext.getSystemService(Context.FINGERPRINT_SERVICE)).hasEnrolledFingerprints()) {
                sendResponse("ok", null, promise);
            } else {
                sendResponse("failed", "You have fingerprint sensor, but you should set it enabled in your settings to use with this app", promise);
            }
        } else {
            sendResponse("failed", "You don\'t have appropriate hardware", promise);
        }
    } else {
        sendResponse("failed", "You don\'t have appropriate hardware", promise);
    }
}
 
Example 15
Project: RNLearn_Project1   File: CameraRollManager.java   View source code 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>
 *        </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;
  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,
        promise)
        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 16
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 17
Project: react-native-andorid-shadow   File: RNReactNativeAndoridShadowModule.java   View source code 6 votes vote down vote up
@ReactMethod
    public void applyShadowForView(final Integer tag, final ReadableMap param) {
        Log.d(TAG,"AndroidShadowManager applyShadowForView! tag: " + tag);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return;
        }
        UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
        uiManager.addUIBlock(new UIBlock() {

            @Override
            public void execute(NativeViewHierarchyManager nvhm) {
                ReactViewGroup targetView = (ReactViewGroup) nvhm.resolveView(tag);
                Log.d(TAG,"AndroidShadowManager view w = " + targetView.getWidth() + " h = " + targetView.getHeight());
//                targetView.setBackgroundColor(Color.CYAN);
                targetView.getViewTreeObserver().addOnGlobalLayoutListener(new OutlineAdjuster(targetView,param));

            }
        });
    }
 
Example 18
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 19
Project: react-native-sunmi-inner-printer   File: SunmiInnerPrinterModule.java   View source code 6 votes vote down vote up
/**
 * 进入缓冲模式,所有打印调用将缓存,调用commitPrinterBuffe()后打印
 *
 * @param clean: 是否清除缓冲区内容
 */
@ReactMethod
public void enterPrinterBuffer(boolean clean) {
    final IWoyouService ss = woyouService;
    Log.i(TAG, "come: " + clean + " ss:" + ss);
    final boolean c = clean;
    ThreadPoolManager.getInstance().executeTask(new Runnable() {
        @Override
        public void run() {
            try {
                ss.enterPrinterBuffer(c);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "ERROR: " + e.getMessage());
            }
        }
    });
}
 
Example 20
Project: react-native-stt   File: RNSpeechToText.java   View source code 6 votes vote down vote up
@ReactMethod
public void createSpeechRecognizer(final Promise promise) {
  if (reactContext == null)
    throw new IllegalArgumentException("ReactApplicationContext must be defined!");

  if (mSpeechRecognizer != null) {
    mSpeechRecognizer.destroy();
    mSpeechRecognizer = null;
  }

  if (SpeechRecognizer.isRecognitionAvailable(reactContext)) {
    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(reactContext);
    mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener(
        this.reactContext.getJSModule(RCTNativeAppEventEmitter.class)
    ));
    promise.resolve(null);
  } else{
    promise.reject("error", "SpeechRecognizer not available");
  }
}
 
Example 21
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void setDefaultSpeechRate(float speechRate, Promise promise) {
	if(notReady(promise)) return;

	int result = tts.setSpeechRate(speechRate);
	if(result == TextToSpeech.SUCCESS) {
		WritableMap map = Arguments.createMap();
		map.putString("status", "Success");
		map.putDouble("speechRate", (double)speechRate);
		promise.resolve(map);
	} else {
		promise.reject("error", "Unable to set speech rate");
	}
}
 
Example 22
Project: RNLearn_Project1   File: NativeAnimatedModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void extractAnimatedNodeOffset(final int tag) {
  mOperations.add(new UIThreadOperation() {
    @Override
    public void execute(NativeAnimatedNodesManager animatedNodesManager) {
      animatedNodesManager.extractAnimatedNodeOffset(tag);
    }
  });
}
 
Example 23
Project: ReactNativeAndroidAudioConverter   File: ReactNativeAndroidAudioConverterModule.java   View source code 5 votes vote down vote up
/**
 * Function to convert a given audio file to MP3 format
 *
 * @param fileName        - input file name
 * @param errorCallback   - function called if the file could not be converted
 * @param successCallback - function called if the conversion was successful
 */
@ReactMethod
public void convertAudioFile(String fileName,
                             final Callback errorCallback,
                             final Callback successCallback) {
    File flacFile = new File(Environment.getExternalStorageDirectory(), fileName);
    Log.d("Output file location", Environment.getExternalStorageDirectory().toString() + fileName);


    IConvertCallback callback = new IConvertCallback() {
        @Override
        public void onSuccess(File convertedFile) {
            // So fast? Love it!
            Log.d("rnaac notice", "convert success");
            successCallback.invoke("convert success");
        }

        @Override
        public void onFailure(Exception error) {
            // Oops! Something went wrong
            errorCallback.invoke("convert failure: " + error.toString());
            Log.d("rnaac notice", error.toString());
            error.printStackTrace();
        }
    };
    AndroidAudioConverter.with(this.getReactApplicationContext())
            // Your current audio file
            .setFile(flacFile)

            // Your desired audio format
            .setFormat(AudioFormat.MP3)

            // An callback to know when conversion is finished
            .setCallback(callback)

            // Start conversion
            .convert();
}
 
Example 24
Project: react-native-webrtc   File: WebRTCModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void mediaStreamTrackSwitchCamera(final String id) {
    MediaStreamTrack track = mMediaStreamTracks.get(id);
    if (track != null) {
        VideoCapturer videoCapturer = mVideoCapturers.get(id);
        if (videoCapturer != null) {
            CameraVideoCapturer cameraVideoCapturer
                = (CameraVideoCapturer) videoCapturer;
            cameraVideoCapturer.switchCamera(null);
        }
    }
}
 
Example 25
Project: react-native-get-sms-android   File: SmsModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void delete(Integer id, final Callback errorCallback, final Callback successCallback) {
    try {
        int res = context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
        if (res > 0) {
            successCallback.invoke("OK");
        } else {
            errorCallback.invoke("SMS not found");
        }
        return;
    } catch (Exception e) {
        errorCallback.invoke(e.getMessage());
        return;
    }
}
 
Example 26
Project: react-native-ble-quick-sdk   File: CommAdminBleRNI.java   View source code 5 votes vote down vote up
@ReactMethod
public void native_connect(String peripheralUUID, Callback successCallback, Callback failCallback) {
	//NSLog(@"native_connect entered");
	Log.d(LOG_TAG,"native_connect entered");

	//[mBleAdmin connect:peripheralUUID  successCallback: successCallback failCallback: failCallback];
	mBleAdmin.connect(peripheralUUID, successCallback, failCallback);
}
 
Example 27
Project: RNLearn_Project1   File: NativeAnimatedModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void setAnimatedNodeOffset(final int tag, final double value) {
  mOperations.add(new UIThreadOperation() {
    @Override
    public void execute(NativeAnimatedNodesManager animatedNodesManager) {
      animatedNodesManager.setAnimatedNodeOffset(tag, value);
    }
  });
}
 
Example 28
Project: react-native-webrtc   File: WebRTCModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void createDataChannel(final int peerConnectionId, String label, ReadableMap config) {
    // Forward to PeerConnectionObserver which deals with DataChannels
    // because DataChannel is owned by PeerConnection.
    PeerConnectionObserver pco
        = mPeerConnectionObservers.get(peerConnectionId);
    if (pco == null || pco.getPeerConnection() == null) {
        Log.d(TAG, "createDataChannel() peerConnection is null");
    } else {
        pco.createDataChannel(label, config);
    }
}
 
Example 29
Project: react-native-orientation-locker   File: OrientationModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void lockToLandscapeLeft() {
    final Activity activity = getCurrentActivity();
    if (activity == null) return;
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    this.isLocked = true;
}
 
Example 30
Project: react-native-audio   File: RCTAudio.java   View source code 5 votes vote down vote up
@ReactMethod
public void stop(final Integer key) {
  MediaPlayer player = this.playerPool.get(key);
  if (player != null && player.isPlaying()) {
    player.stop();
  }
}
 
Example 31
Project: react-native-leancloud-sdk   File: RNPushNotificationModule.java   View source code 5 votes vote down vote up
@ReactMethod
/**
 * Cancel scheduled notifications, and removes notifications from the notification centre.
 *
 * Note - as we are trying to achieve feature parity with iOS, this method cannot be used
 * to remove specific alerts from the notification centre.
 *
 * @see <a href="https://facebook.github.io/react-native/docs/pushnotificationios.html">RN docs</a>
 */
public void cancelLocalNotifications(ReadableMap userInfo) {
    mRNPushNotificationHelper.cancelScheduledNotification(userInfo);
}
 
Example 32
Project: react-native-android-text-to-speech   File: RNAndroidTextToSpeechModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void setDefaultPitch(float pitch, Promise promise) {
	if(notReady(promise)) return;

	int result = tts.setPitch(pitch);
	if(result == TextToSpeech.SUCCESS) {
		WritableMap map = Arguments.createMap();
		map.putString("status", "Success");
		map.putDouble("pitch", (double)pitch);
		promise.resolve(map);
	} else {
		promise.reject("error", "Unable to set pitch");
	}
}
 
Example 33
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 34
Project: react-native-app-settings   File: OpenAppSettingsModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void open() {
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", reactContext.getPackageName(), null);
    intent.setData(uri);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    reactContext.startActivity(intent);
}
 
Example 35
Project: react-native-sunmi-inner-printer   File: SunmiInnerPrinterModule.java   View source code 5 votes vote down vote up
/**
 * 打印机自检,打印机会打印自检页
 *
 * @param callback 回调
 */
@ReactMethod
public void printerSelfChecking(final Promise p) {
    final IWoyouService printerService = woyouService;
    ThreadPoolManager.getInstance().executeTask(new Runnable() {
        @Override
        public void run() {
            try {
                printerService.printerSelfChecking(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 36
Project: react-native-geth   File: RNGethModule.java   View source code 5 votes vote down vote up
/**
 * Exports as a JSON key, encrypted with new passphrase.
 *
 * @param creationPassphrase Passphrase
 * @param exportPassphrase   New passphrase
 * @param promise            Promise
 * @return Return key string
 */
@ReactMethod
public void exportKey(String creationPassphrase, String exportPassphrase, Promise promise) {
    try {
        Account acc = GethHolder.getAccount();
        if (acc != null) {
            byte[] key = GethHolder.getKeyStore().exportKey(acc, creationPassphrase, exportPassphrase);
            promise.resolve(key);
        } else {
            promise.reject(EXPORT_KEY_ERROR, "call method setAccount('accountId') before");
        }
    } catch (Exception e) {
        promise.reject(EXPORT_KEY_ERROR, e);
    }
}
 
Example 37
Project: RNLearn_Project1   File: UIManagerModule.java   View source code 5 votes vote down vote up
/**
 * Interface for adding/removing/moving views within a parent view from JS.
 *
 * @param viewTag the view tag of the parent view
 * @param moveFrom a list of indices in the parent view to move views from
 * @param moveTo parallel to moveFrom, a list of indices in the parent view to move views to
 * @param addChildTags a list of tags of views to add to the parent
 * @param addAtIndices parallel to addChildTags, a list of indices to insert those children at
 * @param removeFrom a list of indices of views to permanently remove. The memory for the
 *        corresponding views and data structures should be reclaimed.
 */
@ReactMethod
public void manageChildren(
    int viewTag,
    @Nullable ReadableArray moveFrom,
    @Nullable ReadableArray moveTo,
    @Nullable ReadableArray addChildTags,
    @Nullable ReadableArray addAtIndices,
    @Nullable ReadableArray removeFrom) {
  if (DEBUG) {
    FLog.d(
        ReactConstants.TAG,
        "(UIManager.manageChildren) tag: " + viewTag +
        ", moveFrom: " + moveFrom +
        ", moveTo: " + moveTo +
        ", addTags: " + addChildTags +
        ", atIndices: " + addAtIndices +
        ", removeFrom: " + removeFrom);
  }
  mUIImplementation.manageChildren(
      viewTag,
      moveFrom,
      moveTo,
      addChildTags,
      addAtIndices,
      removeFrom);
}
 
Example 38
Project: RNLearn_Project1   File: LocationModule.java   View source code 5 votes vote down vote up
/**
 * Stop listening for location updates.
 *
 * NB: this is not balanced with {@link #startObserving}: any number of calls to that method will
 * be canceled by just one call to this one.
 */
@ReactMethod
public void stopObserving() {
  LocationManager locationManager =
      (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
  locationManager.removeUpdates(mLocationListener);
  mWatchedProvider = null;
}
 
Example 39
Project: react-native-udesk   File: UdeskModule.java   View source code 5 votes vote down vote up
@ReactMethod
public void initSDK(String appDomain, String appKey, String appId) {
    this.appDomain = appDomain;
    this.appKey = appKey;
    this.appId = appId;
    UdeskSDKManager.getInstance().initApiKey(mReactContext.getApplicationContext(), this.appDomain, this.appKey, this.appId);
    UdeskConfig.udeskTitlebarBgResId = cn.udesk.R.color.udesk_titlebar_bg;
}
 
Example 40
Project: react-native-system-setting   File: SystemSetting.java   View source code 5 votes vote down vote up
@ReactMethod
public void setVolume(float val, String type) {
    mContext.unregisterReceiver(volumeBR);
    int volType = getVolType(type);
    am.setStreamVolume(volType, (int) (val * am.getStreamMaxVolume(volType)), AudioManager.FLAG_PLAY_SOUND);
    mContext.registerReceiver(volumeBR, filter);
}