下面列出了怎么用com.facebook.react.bridge.ReactMethod的API类实例代码及写法,或者点击链接到github查看源代码。
@ReactMethod
public void installUpdate(){
pendingInstallUpdate = Terminal.getInstance().installUpdate(readerSoftwareUpdate,this, new Callback() {
@Override
public void onSuccess() {
sendEventWithName(EVENT_UPDATE_INSTALL,Arguments.createMap());
readerSoftwareUpdate = null;
}
@Override
public void onFailure(@Nonnull TerminalException e) {
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
sendEventWithName(EVENT_UPDATE_INSTALL,errorMap);
}
});
}
@ReactMethod
public void disconnectReader(){
if(Terminal.getInstance().getConnectedReader()==null){
sendEventWithName(EVENT_READER_DISCONNECTION_COMPLETION,Arguments.createMap());
}else{
Terminal.getInstance().disconnectReader(new Callback() {
@Override
public void onSuccess() {
sendEventWithName(EVENT_READER_DISCONNECTION_COMPLETION,Arguments.createMap());
}
@Override
public void onFailure(@Nonnull TerminalException e) {
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
sendEventWithName(EVENT_READER_DISCONNECTION_COMPLETION,errorMap);
}
});
}
}
@ReactMethod
public void processPayment(){
Terminal.getInstance().processPayment(lastPaymentIntent, new PaymentIntentCallback() {
@Override
public void onSuccess(@Nonnull PaymentIntent paymentIntent) {
lastPaymentIntent = paymentIntent;
WritableMap processPaymentMap = Arguments.createMap();
processPaymentMap.putMap(INTENT,serializePaymentIntent(paymentIntent,lastCurrency));
sendEventWithName(EVENT_PROCESS_PAYMENT,processPaymentMap);
}
@Override
public void onFailure(@Nonnull TerminalException e) {
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
errorMap.putInt(CODE,e.getErrorCode().ordinal());
errorMap.putString(DECLINE_CODE,e.getApiError().getDeclineCode());
errorMap.putMap(INTENT,serializePaymentIntent(lastPaymentIntent,lastCurrency));
sendEventWithName(EVENT_PROCESS_PAYMENT,errorMap);
}
});
}
@SuppressLint("StaticFieldLeak")
@SuppressWarnings("unused")
@ReactMethod
public void write(@NonNull final Integer cId, @NonNull final String base64String, @Nullable final Callback callback) {
new GuardedAsyncTask<Void, Void>(mReactContext.getExceptionHandler()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
TcpSocketClient socketClient = socketClients.get(cId);
if (socketClient == null) {
return;
}
try {
socketClient.write(Base64.decode(base64String, Base64.NO_WRAP));
if (callback != null) {
callback.invoke();
}
} catch (IOException e) {
if (callback != null) {
callback.invoke(e.toString());
}
onError(cId, e.toString());
}
}
}.executeOnExecutor(executorService);
}
@SuppressLint("StaticFieldLeak")
@SuppressWarnings("unused")
@ReactMethod
public void end(final Integer cId) {
new GuardedAsyncTask<Void, Void>(mReactContext.getExceptionHandler()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
TcpSocketClient socketClient = socketClients.get(cId);
if (socketClient == null) {
return;
}
socketClient.close();
socketClients.remove(cId);
}
}.executeOnExecutor(executorService);
}
@SuppressLint("StaticFieldLeak")
@SuppressWarnings("unused")
@ReactMethod
public void listen(final Integer cId, final ReadableMap options) {
new GuardedAsyncTask<Void, Void>(mReactContext.getExceptionHandler()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
TcpSocketServer server = new TcpSocketServer(socketClients, TcpSocketModule.this, cId, options);
socketClients.put(cId, server);
int port = options.getInt("port");
String host = options.getString("host");
onConnect(cId, host, port);
} catch (Exception uhe) {
onError(cId, uhe.getMessage());
}
}
}.executeOnExecutor(executorService);
}
@ReactMethod
public void cancelPaymentIntent(){
Terminal.getInstance().cancelPaymentIntent(lastPaymentIntent, new PaymentIntentCallback() {
@Override
public void onSuccess(@Nonnull PaymentIntent paymentIntent) {
WritableMap paymentIntentCancelMap = Arguments.createMap();
paymentIntentCancelMap.putMap(INTENT,serializePaymentIntent(paymentIntent,lastCurrency));
sendEventWithName(EVENT_PAYMENT_INTENT_CANCEL,paymentIntentCancelMap);
}
@Override
public void onFailure(@Nonnull TerminalException e) {
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
errorMap.putInt(CODE,e.getErrorCode().ordinal());
errorMap.putMap(INTENT,serializePaymentIntent(lastPaymentIntent,lastCurrency));
sendEventWithName(EVENT_PAYMENT_INTENT_CANCEL,errorMap);
}
});
}
@ReactMethod
public void collectPaymentMethod(){
pendingCreatePaymentIntent = Terminal.getInstance().collectPaymentMethod(lastPaymentIntent, this, new PaymentIntentCallback() {
@Override
public void onSuccess(@Nonnull PaymentIntent paymentIntent) {
pendingCreatePaymentIntent = null;
lastPaymentIntent = paymentIntent;
WritableMap collectPaymentMethodMap = Arguments.createMap();
collectPaymentMethodMap.putMap(INTENT,serializePaymentIntent(paymentIntent,lastCurrency));
sendEventWithName(EVENT_PAYMENT_METHOD_COLLECTION,collectPaymentMethodMap);
}
@Override
public void onFailure(@Nonnull TerminalException e) {
pendingCreatePaymentIntent = null;
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
errorMap.putInt(CODE,e.getErrorCode().ordinal());
errorMap.putMap(INTENT,serializePaymentIntent(lastPaymentIntent,lastCurrency));
sendEventWithName(EVENT_PAYMENT_METHOD_COLLECTION,errorMap);
}
});
}
@ReactMethod
public void abortCreatePayment(){
if(pendingCreatePaymentIntent!=null && !pendingCreatePaymentIntent.isCompleted()){
pendingCreatePaymentIntent.cancel(new Callback() {
@Override
public void onSuccess() {
pendingCreatePaymentIntent = null;
sendEventWithName(EVENT_ABORT_CREATE_PAYMENT_COMPLETION,Arguments.createMap());
}
@Override
public void onFailure(@Nonnull TerminalException e) {
WritableMap errorMap = Arguments.createMap();
errorMap.putString(ERROR,e.getErrorMessage());
sendEventWithName(EVENT_ABORT_CREATE_PAYMENT_COMPLETION,errorMap);
}
});
}else{
sendEventWithName(EVENT_ABORT_CREATE_PAYMENT_COMPLETION,Arguments.createMap());
}
}
/**
* Returns if the device is currently connected to a WiFi network.
*/
@ReactMethod
public void connectionStatus(final Promise promise) {
final ConnectivityManager connectivityManager = (ConnectivityManager) getReactApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager == null) {
promise.resolve(false);
return;
}
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiInfo == null) {
promise.resolve(false);
return;
}
promise.resolve(wifiInfo.isConnected());
}
@ReactMethod
public void setSpeed(final int reactTag, final float speed) {
try {
UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);
if (playerView != null && playerView.mPlayer != null) {
playerView.mPlayer.setPlaybackRate(speed);
}
}
});
} catch (IllegalViewOperationException e) {
throw e;
}
}
/**
* This method will remove the wifi network configuration.
* If you are connected to that network, it will disconnect.
*
* @param SSID wifi SSID to remove configuration for
*/
@ReactMethod
public void isRemoveWifiNetwork(final String SSID, final Promise promise) {
final boolean locationPermissionGranted = PermissionUtils.isLocationPermissionGranted(context);
if (!locationPermissionGranted) {
promise.reject(IsRemoveWifiNetworkErrorCodes.locationPermissionMissing.toString(), "Location permission (ACCESS_FINE_LOCATION) is not granted");
return;
}
final List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks();
final String comparableSSID = ('"' + SSID + '"'); //Add quotes because wifiConfig.SSID has them
for (WifiConfiguration wifiConfig : mWifiConfigList) {
if (wifiConfig.SSID.equals(comparableSSID)) {
promise.resolve(wifi.removeNetwork(wifiConfig.networkId));
wifi.saveConfiguration();
return;
}
}
promise.resolve(true);
}
@ReactMethod
public void stop(final int reactTag) {
try {
UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);
if (playerView != null && playerView.mPlayer != null) {
playerView.mPlayer.stop();
playerView.userPaused = true;
}
}
});
} catch (IllegalViewOperationException e) {
throw e;
}
}
@ReactMethod
public void play(final int reactTag) {
try {
UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);
if (playerView != null && playerView.mPlayer != null) {
playerView.mPlayer.play();
}
}
});
} catch (IllegalViewOperationException e) {
throw e;
}
}
@ReactMethod
public void seekTo(final int reactTag, final double time) {
try {
UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);
if (playerView != null && playerView.mPlayer != null) {
playerView.mPlayer.seek(time);
}
}
});
} catch (IllegalViewOperationException e) {
throw e;
}
}
@ReactMethod
public void setPrintingSize(String printingSize) {
int charsOnLine;
switch (printingSize) {
case EscPosModule.PRINTING_SIZE_80_MM:
charsOnLine = LayoutBuilder.CHARS_ON_LINE_80_MM;
break;
case EscPosModule.PRINTING_SIZE_58_MM:
default:
charsOnLine = LayoutBuilder.CHARS_ON_LINE_58_MM;
}
layoutBuilder.setCharsOnLine(charsOnLine);
}
@ReactMethod
public void setPrintingSize(String printingSize) {
int charsOnLine;
int printingWidth;
switch (printingSize) {
case PRINTING_SIZE_80_MM:
charsOnLine = LayoutBuilder.CHARS_ON_LINE_80_MM;
printingWidth = PrinterService.PRINTING_WIDTH_80_MM;
break;
case PRINTING_SIZE_58_MM:
default:
charsOnLine = LayoutBuilder.CHARS_ON_LINE_58_MM;
printingWidth = PrinterService.PRINTING_WIDTH_58_MM;
}
printerService.setCharsOnLine(charsOnLine);
printerService.setPrintingWidth(printingWidth);
}
@ReactMethod
public void toggleSpeed(final int reactTag) {
try {
UIManagerModule uiManager = mReactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
RNJWPlayerView playerView = (RNJWPlayerView) nvhm.resolveView(reactTag);
if (playerView != null && playerView.mPlayer != null) {
float rate = playerView.mPlayer.getPlaybackRate();
if (rate < 2) {
playerView.mPlayer.setPlaybackRate(rate += 0.5);
} else {
playerView.mPlayer.setPlaybackRate((float) 0.5);
}
}
}
});
} catch (IllegalViewOperationException e) {
throw e;
}
}
@ReactMethod
public void stopService(Promise promise) {
Intent intent = new Intent(getReactApplicationContext(), VIForegroundService.class);
intent.setAction(Constants.ACTION_FOREGROUND_SERVICE_STOP);
boolean stopped = getReactApplicationContext().stopService(intent);
if (stopped) {
promise.resolve(null);
} else {
promise.reject(ERROR_SERVICE_ERROR, "VIForegroundService: Foreground service failed to stop");
}
}
@ReactMethod
public void requestOverlayPermission(Promise promise) {
mPromise = promise;
/**
* Before android 6.0 Marshmallow you dont need to ask for canDrawOverlays permission,
* but in newer android versions this is mandatory
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this.reactContext)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + this.reactContext.getPackageName()));
this.reactContext.startActivityForResult(intent, DRAW_OVER_OTHER_APP_PERMISSION_REQUEST_CODE, null);
} else {
promise.resolve(true);
}
}
@ReactMethod
public void openWifiSettings(final Promise primise) {
try {
SettingsUtil.openWifiSettings(getReactApplicationContext());
primise.resolve(null);
} catch (Throwable ex) {
primise.reject(ex);
}
}
@ReactMethod
public void openCelularSettings(final Promise primise) {
try {
SettingsUtil.openCelularSettings(getReactApplicationContext());
primise.resolve(null);
} catch (Throwable ex) {
primise.reject(ex);
}
}
@ReactMethod
public void openAppSettings(final Promise promise) {
try {
SettingsUtil.openAppSettings(getReactApplicationContext());
promise.resolve(null);
} catch (Throwable ex) {
promise.reject(ex);
}
}
/**
* Crop an image. If all goes well, the promise will be resolved with the file:// URI of
* the new image as the only argument. This is a temporary file - consider using
* CameraRollManager.saveImageWithTag to save it in the gallery.
*
* @param uri the URI of the image to crop
* @param options crop parameters specified as {@code {offset: {x, y}, size: {width, height}}}.
* Optionally this also contains {@code {targetSize: {width, height}}}. If this is
* specified, the cropped image will be resized to that size.
* All units are in pixels (not DPs).
* @param promise Promise to be resolved when the image has been cropped; the only argument that
* is passed to this is the file:// URI of the new image
*/
@ReactMethod
public void cropImage(
String uri,
ReadableMap options,
Promise promise) {
ReadableMap offset = options.hasKey("offset") ? options.getMap("offset") : null;
ReadableMap size = options.hasKey("size") ? options.getMap("size") : null;
if (offset == null || size == null ||
!offset.hasKey("x") || !offset.hasKey("y") ||
!size.hasKey("width") || !size.hasKey("height")) {
throw new JSApplicationIllegalArgumentException("Please specify offset and size");
}
if (uri == null || uri.isEmpty()) {
throw new JSApplicationIllegalArgumentException("Please specify a URI");
}
CropTask cropTask = new CropTask(
getReactApplicationContext(),
uri,
(int) offset.getDouble("x"),
(int) offset.getDouble("y"),
(int) size.getDouble("width"),
(int) size.getDouble("height"),
promise);
if (options.hasKey("displaySize")) {
ReadableMap targetSize = options.getMap("displaySize");
cropTask.setTargetSize(
(int) targetSize.getDouble("width"),
(int) targetSize.getDouble("height"));
}
cropTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
/**
* Use this to connect with a wifi network.
* Example: wifi.findAndConnect(ssid, password, false);
* The promise will resolve with the message 'connected' when the user is connected on Android.
*
* @param SSID name of the network to connect with
* @param password password of the network to connect with
* @param isWep only for iOS
* @param promise to send success/error feedback
*/
@ReactMethod
public void connectToProtectedSSID(@NonNull final String SSID, @NonNull final String password, final boolean isWep, final Promise promise) {
final boolean locationPermissionGranted = PermissionUtils.isLocationPermissionGranted(context);
if (!locationPermissionGranted) {
promise.reject("location permission missing", "Location permission (ACCESS_FINE_LOCATION) is not granted");
return;
}
final boolean isLocationOn = LocationUtils.isLocationOn(context);
if (!isLocationOn) {
promise.reject("location off", "Location service is turned off");
return;
}
WifiUtils.withContext(context).connectWith(SSID, password).onConnectionResult(new ConnectionSuccessListener() {
@Override
public void success() {
promise.resolve("connected");
}
@Override
public void failed(@NonNull ConnectionErrorCode errorCode) {
promise.reject("failed", "Could not connect to network");
}
}).start();
}
/**
* This method will return current SSID
*
* @param promise to send error/result feedback
*/
@ReactMethod
public void getCurrentWifiSSID(final Promise promise) {
WifiInfo info = wifi.getConnectionInfo();
// This value should be wrapped in double quotes, so we need to unwrap it.
String ssid = info.getSSID();
if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
ssid = ssid.substring(1, ssid.length() - 1);
}
promise.resolve(ssid);
}
/**
* Returns the BSSID (basic service set identifier) of the currently connected WiFi network.
*/
@ReactMethod
public void getBSSID(final Promise promise) {
final WifiInfo info = wifi.getConnectionInfo();
final String bssid = info.getBSSID();
promise.resolve(bssid.toUpperCase());
}
/**
* Returns the frequency of the currently connected WiFi network.
*/
@ReactMethod
public void getFrequency(final Promise promise) {
final WifiInfo info = wifi.getConnectionInfo();
final int frequency = info.getFrequency();
promise.resolve(frequency);
}
/**
* Returns the IP of the currently connected WiFi network.
*/
@ReactMethod
public void getIP(final Promise promise) {
final WifiInfo info = wifi.getConnectionInfo();
final String stringIP = longToIP(info.getIpAddress());
promise.resolve(stringIP);
}
/**
* Similar to `loadWifiList` but it forcefully starts a new WiFi scan and only passes the results when the scan is done.
*/
@ReactMethod
public void reScanAndLoadWifiList(final Promise promise) {
final WifiScanResultReceiver wifiScanResultReceiver = new WifiScanResultReceiver(wifi, promise);
getReactApplicationContext().registerReceiver(wifiScanResultReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi.startScan();
}