java类com.facebook.react.bridge.WritableMap的实例源码

NfcReactNativeSimpleModule.java 文件源码 项目:nfc-react-native-simple 阅读 31 收藏 0 点赞 0 评论 0
@Override
    public void onNewIntent(Intent intent) 
    {
          String action = intent.getAction();
//      Log.i("!intent! ", action);

          Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        byte[] id = tag.getId();
        String serialNumber = bytesToHex(id);
        WritableMap idData = Arguments.createMap();
        idData.putString("id", serialNumber);

        sendEvent(this.reactContext, "NFCCardID", idData);

    }
HeadlessTaskService.java 文件源码 项目:react-native-background-task 阅读 32 收藏 0 点赞 0 评论 0
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
    Bundle extras = intent.getExtras();
    // If extras have been passed to the intent, pass them on into the JS as taskData
    // which can be accessed as the first param.
    WritableMap data = /* extras != null ? Arguments.fromBundle(extras) : */ Arguments.createMap();

    int timeout = extras.getInt("timeout");

    Log.d(TAG, String.format("Returning HeadlessJsTaskConfig, timeout=%s ms", timeout));
    return new HeadlessJsTaskConfig(
            // The the task was registered with in JS - must match
            "BackgroundTask",
            data,
            TimeUnit.SECONDS.toMillis(timeout)
    );
}
RCTConvert.java 文件源码 项目:react-native-twilio-chat 阅读 35 收藏 0 点赞 0 评论 0
public static WritableMap Message(Message message) {
    WritableMap map = Arguments.createMap();

    map.putString("sid", message.getSid());
    map.putInt("index", (int) message.getMessageIndex());
    map.putString("author", message.getAuthor());
    map.putString("body", message.getMessageBody());
    map.putString("timestamp", message.getTimeStamp());

    WritableMap attributes = Arguments.createMap();
    try {
        attributes = jsonToWritableMap(message.getAttributes());
    }
    catch (JSONException e) {}
    map.putMap("attributes", attributes);
    return map;
}
FusedLocationModule.java 文件源码 项目:react-native-fused-location 阅读 31 收藏 0 点赞 0 评论 0
private WritableMap convertLocationToJSON(Location l) {
    WritableMap params = new WritableNativeMap();
    params.putDouble("latitude", l.getLatitude());
    params.putDouble("longitude", l.getLongitude());
    params.putDouble("accuracy", l.getAccuracy());
    params.putDouble("altitude", l.getAltitude());
    params.putDouble("bearing", l.getBearing());
    params.putString("provider", l.getProvider());
    params.putDouble("speed", l.getSpeed());
    params.putString("timestamp", Long.toString(l.getTime()));
    boolean isMock = false;
    if (android.os.Build.VERSION.SDK_INT >= 18) {
        isMock = l.isFromMockProvider();
    } else {
        isMock = !Settings.Secure.getString(getReactApplicationContext().getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
    }
    params.putBoolean("mocked", isMock);
    return params;
}
DatePickerDialogTestCase.java 文件源码 项目:RNLearn_Project1 阅读 39 收藏 0 点赞 0 评论 0
public void testCallback() throws Throwable {
  final WritableMap options = new WritableNativeMap();
  options.putDouble("date", getDateInMillis(2020, 5, 6));

  final DialogFragment datePickerFragment = showDialog(options);

  runTestOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          ((DatePickerDialog) datePickerFragment.getDialog())
              .getButton(DialogInterface.BUTTON_POSITIVE).performClick();
        }
      });

  getInstrumentation().waitForIdleSync();
  waitForBridgeAndUIIdle();

  assertEquals(0, mRecordingModule.getErrors());
  assertEquals(1, mRecordingModule.getDates().size());
  assertEquals(2020, (int) mRecordingModule.getDates().get(0)[0]);
  assertEquals(5, (int) mRecordingModule.getDates().get(0)[1]);
  assertEquals(6, (int) mRecordingModule.getDates().get(0)[2]);
}
JsonConvert.java 文件源码 项目:react-native-nfc-manager 阅读 39 收藏 0 点赞 0 评论 0
public static WritableMap jsonToReact(JSONObject jsonObject) throws JSONException {
    WritableMap writableMap = Arguments.createMap();
    Iterator iterator = jsonObject.keys();
    while(iterator.hasNext()) {
        String key = (String) iterator.next();
        Object value = jsonObject.get(key);
        if (value instanceof Float || value instanceof Double) {
            writableMap.putDouble(key, jsonObject.getDouble(key));
        } else if (value instanceof Number) {
            writableMap.putInt(key, jsonObject.getInt(key));
        } else if (value instanceof String) {
            writableMap.putString(key, jsonObject.getString(key));
        } else if (value instanceof JSONObject) {
            writableMap.putMap(key,jsonToReact(jsonObject.getJSONObject(key)));
        } else if (value instanceof JSONArray){
            writableMap.putArray(key, jsonToReact(jsonObject.getJSONArray(key)));
        } else if (value == JSONObject.NULL){
            writableMap.putNull(key);
        }
    }

    return writableMap;
}
ShareModule.java 文件源码 项目:RNLearn_Project1 阅读 43 收藏 0 点赞 0 评论 0
/**
 * 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");
  }
}
ReactWebViewManager.java 文件源码 项目:RNLearn_Project1 阅读 33 收藏 0 点赞 0 评论 0
@Override
public void onReceivedError(
    WebView webView,
    int errorCode,
    String description,
    String failingUrl) {
  super.onReceivedError(webView, errorCode, description, failingUrl);
  mLastLoadFailed = true;

  // In case of an error JS side expect to get a finish event first, and then get an error event
  // Android WebView does it in the opposite way, so we need to simulate that behavior
  emitFinishEvent(webView, failingUrl);

  WritableMap eventData = createWebViewEvent(webView, failingUrl);
  eventData.putDouble("code", errorCode);
  eventData.putString("description", description);

  dispatchEvent(
      webView,
      new TopLoadingErrorEvent(webView.getId(), eventData));
}
StepCounter.java 文件源码 项目:react-native-google-fit 阅读 27 收藏 0 点赞 0 评论 0
@Override
public void onDataPoint(DataPoint dataPoint) {
    DataType type = dataPoint.getDataType();
    Log.i(TAG, "Detected DataPoint type: " + type);

    for (final Field field : type.getFields()) {
        final Value value = dataPoint.getValue(field);
        Log.i(TAG, "Detected DataPoint field: " + field.getName());
        Log.i(TAG, "Detected DataPoint value: " + value);


   /*     activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mReactContext.getApplicationContext(), "Field: " + field.getName() + " Value: " + value, Toast.LENGTH_SHORT).show();
            }
        });*/

        if(type.equals(DataType.TYPE_STEP_COUNT_CUMULATIVE)) {
            WritableMap map = Arguments.createMap();
            map.putDouble("steps", value.asInt());
            sendEvent(this.mReactContext, "StepChangedEvent", map);
        }

    }
}
CallStateListenerTest.java 文件源码 项目:react-native-call-events 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void onCallStateChanged_CALL_STATE_IDLE_returnOnEndTrue() {
    CallStateListener instance = getInstance(false, true, mockReactContext);

    instance.onCallStateChanged(TelephonyManager.CALL_STATE_IDLE, "8675309");

    //always set the return flags
    verify(mockIntent).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Should always fire the event back to Javascript
    WritableMap expected = new MockWritableMap();
    expected.putString("phonenumber", "8675309");
    expected.putString("state", "CALL_STATE_END");
    verify(mockEmitter).emit("callStatusUpdate", expected);

    //should launch the app
    verify(mockApplicationContext).startActivity(mockIntent);
}
CallStateListenerTest.java 文件源码 项目:react-native-call-events 阅读 32 收藏 0 点赞 0 评论 0
@Test
public void onCallStateChanged_CALL_STATE_RINGING_returnOnCallFalse() {
    CallStateListener instance = getInstance(false, true, mockReactContext);

    instance.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, "8675309");

    //always set the return flags
    verify(mockIntent).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Should always fire the event back to Javascript
    WritableMap expected = new MockWritableMap();
    expected.putString("phonenumber", "8675309");
    expected.putString("state", "CALL_STATE_RINGING");
    verify(mockEmitter).emit("callStatusUpdate", expected);

    //should not attempt to launch the app
    verify(mockApplicationContext, never()).startActivity(any(Intent.class));
}
Peripheral.java 文件源码 项目:react-native-blue-manager 阅读 51 收藏 0 点赞 0 评论 0
public WritableMap asWritableMap() {

        WritableMap map = Arguments.createMap();

        try {
            map.putString("name", device.getName());
            map.putBoolean("connected", connected);
            map.putString("id", device.getAddress()); // mac address
            map.putMap("advertising", byteArrayToWritableMap(advertisingData));
            map.putInt("rssi", advertisingRSSI);
        } catch (Exception e) { // this shouldn't happen
            e.printStackTrace();
        }

        return map;
    }
CallStateListenerTest.java 文件源码 项目:react-native-call-events 阅读 28 收藏 0 点赞 0 评论 0
@Test
public void onCallStateChanged_CALL_STATE_OFFHOOK_returnOnCallFalse() {
    CallStateListener instance = getInstance(false, true, mockReactContext);

    instance.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, "8675309");

    //always set the return flags
    verify(mockIntent).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Should always fire the event back to Javascript
    WritableMap expected = new MockWritableMap();
    expected.putString("phonenumber", "8675309");
    expected.putString("state", "CALL_STATE_OFFHOOK");
    verify(mockEmitter).emit("callStatusUpdate", expected);

    //should not attempt to launch the app
    verify(mockApplicationContext, never()).startActivity(any(Intent.class));
}
RNAndroidTextToSpeechModule.java 文件源码 项目:react-native-android-text-to-speech 阅读 26 收藏 0 点赞 0 评论 0
private WritableMap returnMapForVoice(Voice voice) {
    WritableMap voiceData = Arguments.createMap();
    voiceData.putString("voiceName", voice.getName());
    voiceData.putString("languageName", voice.getLocale().getDisplayLanguage());
    voiceData.putString("languageCode", voice.getLocale().getISO3Language());
    voiceData.putString("languageString", voice.getLocale().toString());
    voiceData.putString("countryName", voice.getLocale().getDisplayCountry());
    voiceData.putString("countryCode", voice.getLocale().getISO3Country());

    return voiceData;
}
DatePickerDialogModule.java 文件源码 项目:RNLearn_Project1 阅读 32 收藏 0 点赞 0 评论 0
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
  if (!mPromiseResolved && getReactApplicationContext().hasActiveCatalystInstance()) {
    WritableMap result = new WritableNativeMap();
    result.putString("action", ACTION_DATE_SET);
    result.putInt("year", year);
    result.putInt("month", month);
    result.putInt("day", day);
    mPromise.resolve(result);
    mPromiseResolved = true;
  }
}
CameraRollManager.java 文件源码 项目:RNLearn_Project1 阅读 42 收藏 0 点赞 0 评论 0
private static void putBasicNodeInfo(
    Cursor photos,
    WritableMap node,
    int mimeTypeIndex,
    int groupNameIndex,
    int dateTakenIndex) {
  node.putString("type", photos.getString(mimeTypeIndex));
  node.putString("group_name", photos.getString(groupNameIndex));
  node.putDouble("timestamp", photos.getLong(dateTakenIndex) / 1000d);
}
ResponseUtil.java 文件源码 项目:RNLearn_Project1 阅读 32 收藏 0 点赞 0 评论 0
public static void onResponseReceived(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  int statusCode,
  WritableMap headers,
  String url) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushInt(statusCode);
  args.pushMap(headers);
  args.pushString(url);

  eventEmitter.emit("didReceiveNetworkResponse", args);
}
ReactVideoView.java 文件源码 项目:react-native-videoplayer 阅读 31 收藏 0 点赞 0 评论 0
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {

    WritableMap error = Arguments.createMap();
    error.putInt(EVENT_PROP_WHAT, what);
    error.putInt(EVENT_PROP_EXTRA, extra);
    WritableMap event = Arguments.createMap();
    event.putMap(EVENT_PROP_ERROR, error);
    mEventEmitter.receiveEvent(getId(), Events.EVENT_ERROR.toString(), event);
    return true;
}
ScanditBarcodeHelpers.java 文件源码 项目:react-native-scandit 阅读 50 收藏 0 点赞 0 评论 0
static public WritableMap rectToWritableMap(RectF rect) {
    WritableMap map = Arguments.createMap();
    map.putDouble("x", rect.left);
    map.putDouble("y", rect.top);
    map.putDouble("width", rect.width());
    map.putDouble("height", rect.height());
    return map;
}
PeerConnectionObserver.java 文件源码 项目:react-native-webrtc 阅读 34 收藏 0 点赞 0 评论 0
@Override
public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
    WritableMap params = Arguments.createMap();
    params.putInt("id", id);
    params.putString("iceConnectionState", iceConnectionStateString(iceConnectionState));

    webRTCModule.sendEvent("peerConnectionIceConnectionChanged", params);
}
AsyncStorageErrorUtil.java 文件源码 项目:RNLearn_Project1 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Create Error object to be passed back to the JS callback.
 */
/* package */ static WritableMap getError(@Nullable String key, String errorMessage) {
  WritableMap errorMap = Arguments.createMap();
  errorMap.putString("message", errorMessage);
  if (key != null) {
    errorMap.putString("key", key);
  }
  return errorMap;
}
TouchesHelper.java 文件源码 项目:RNLearn_Project1 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Creates catalyst pointers array in format that is expected by RCTEventEmitter JS module from
 * given {@param event} instance. This method use {@param reactTarget} parameter to set as a
 * target view id associated with current gesture.
 */
private static WritableArray createsPointersArray(int reactTarget, TouchEvent event) {
  WritableArray touches = Arguments.createArray();
  MotionEvent motionEvent = event.getMotionEvent();

  // Calculate the coordinates for the target view.
  // The MotionEvent contains the X,Y of the touch in the coordinate space of the root view
  // The TouchEvent contains the X,Y of the touch in the coordinate space of the target view
  // Subtracting them allows us to get the coordinates of the target view's top left corner
  // We then use this when computing the view specific touches below
  // Since only one view is actually handling even multiple touches, the values are all relative
  // to this one target view.
  float targetViewCoordinateX = motionEvent.getX() - event.getViewX();
  float targetViewCoordinateY = motionEvent.getY() - event.getViewY();

  for (int index = 0; index < motionEvent.getPointerCount(); index++) {
    WritableMap touch = Arguments.createMap();
    // pageX,Y values are relative to the RootReactView
    // the motionEvent already contains coordinates in that view
    touch.putDouble(PAGE_X_KEY, PixelUtil.toDIPFromPixel(motionEvent.getX(index)));
    touch.putDouble(PAGE_Y_KEY, PixelUtil.toDIPFromPixel(motionEvent.getY(index)));
    // locationX,Y values are relative to the target view
    // To compute the values for the view, we subtract that views location from the event X,Y
    float locationX = motionEvent.getX(index) - targetViewCoordinateX;
    float locationY = motionEvent.getY(index) - targetViewCoordinateY;
    touch.putDouble(LOCATION_X_KEY, PixelUtil.toDIPFromPixel(locationX));
    touch.putDouble(LOCATION_Y_KEY, PixelUtil.toDIPFromPixel(locationY));
    touch.putInt(TARGET_KEY, reactTarget);
    touch.putDouble(TIMESTAMP_KEY, event.getTimestampMs());
    touch.putDouble(POINTER_IDENTIFIER_KEY, motionEvent.getPointerId(index));
    touches.pushMap(touch);
  }

  return touches;
}
MapUtil.java 文件源码 项目:react-native-batch 阅读 39 收藏 0 点赞 0 评论 0
public static WritableMap toWritableMap(Map<String, Object> map) {
    WritableMap writableMap = Arguments.createMap();
    Iterator iterator = map.entrySet().iterator();

    while (iterator.hasNext()) {
        Map.Entry pair = (Map.Entry) iterator.next();
        Object value = pair.getValue();

        if (value == null) {
            writableMap.putNull((String) pair.getKey());
        } else if (value instanceof Boolean) {
            writableMap.putBoolean((String) pair.getKey(), (Boolean) value);
        } else if (value instanceof Double) {
            writableMap.putDouble((String) pair.getKey(), (Double) value);
        } else if (value instanceof Integer) {
            writableMap.putInt((String) pair.getKey(), (Integer) value);
        } else if (value instanceof String) {
            writableMap.putString((String) pair.getKey(), (String) value);
        } else if (value instanceof Map) {
            writableMap.putMap((String) pair.getKey(), MapUtil.toWritableMap((Map<String, Object>) value));
        } else if (value.getClass() != null && value.getClass().isArray()) {
            writableMap.putArray((String) pair.getKey(), ArrayUtil.toWritableArray((Object[]) value));
        }

        iterator.remove();
    }

    return writableMap;
}
SGScanditPicker.java 文件源码 项目:react-native-scandit 阅读 33 收藏 0 点赞 0 评论 0
public PromiseSender(WritableMap promiseResponse) {
    this.promiseResponse = promiseResponse;
    if (promiseResponse.hasKey("commandid")) {
        addResponse();
        nativeAppEventEmitter.emit(COMMAND_DONE_EVENT_NAME, promiseResponse);
    }
}
ReactSliderEvent.java 文件源码 项目:RNLearn_Project1 阅读 26 收藏 0 点赞 0 评论 0
private WritableMap serializeEventData() {
  WritableMap eventData = Arguments.createMap();
  eventData.putInt("target", getViewTag());
  eventData.putDouble("value", getValue());
  eventData.putBoolean("fromUser", isFromUser());
  return eventData;
}
ReactRootView.java 文件源码 项目:RNLearn_Project1 阅读 25 收藏 0 点赞 0 评论 0
private void emitOrientationChanged(final int newRotation) {
  String name;
  double rotationDegrees;
  boolean isLandscape = false;

  switch (newRotation) {
    case Surface.ROTATION_0:
      name = "portrait-primary";
      rotationDegrees = 0.0;
      break;
    case Surface.ROTATION_90:
      name = "landscape-primary";
      rotationDegrees = -90.0;
      isLandscape = true;
      break;
    case Surface.ROTATION_180:
      name = "portrait-secondary";
      rotationDegrees = 180.0;
      break;
    case Surface.ROTATION_270:
      name = "landscape-secondary";
      rotationDegrees = 90.0;
      isLandscape = true;
      break;
    default:
      return;
  }
  WritableMap map = Arguments.createMap();
  map.putString("name", name);
  map.putDouble("rotationDegrees", rotationDegrees);
  map.putBoolean("isLandscape", isLandscape);

  sendEvent("namedOrientationDidChange", map);
}
SpeechRecognitionListener.java 文件源码 项目:react-native-stt 阅读 30 收藏 0 点赞 0 评论 0
@Override
public void onReadyForSpeech(Bundle params) {
  Logger.debug(TAG, "onReadyForSpeech: " + params);
  WritableMap data = Arguments.createMap();
  data.putMap("params", Arguments.fromBundle(params));
  emit(SPEECH_TO_TEXT, data);
}
ReactRootView.java 文件源码 项目:RNLearn_Project1 阅读 29 收藏 0 点赞 0 评论 0
private void sendEvent(String eventName, @Nullable WritableMap params) {
  if (mReactInstanceManager != null) {
    mReactInstanceManager.getCurrentReactContext()
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(eventName, params);
  }
}
BeaconsAndroidModule.java 文件源码 项目:react-native-ibeacons 阅读 41 收藏 0 点赞 0 评论 0
@ReactMethod
public void getMonitoredRegions(Callback callback) {
    WritableArray array = new WritableNativeArray();
    for (Region region: mBeaconManager.getMonitoredRegions()) {
        WritableMap map = new WritableNativeMap();
        map.putString("identifier", region.getUniqueId());
        map.putString("uuid", region.getId1().toString());
        map.putInt("major", region.getId2() != null ? region.getId2().toInt() : 0);
        map.putInt("minor", region.getId3() != null ? region.getId3().toInt() : 0);
        array.pushMap(map);
    }
    callback.invoke(array);
}
MercadoPagoCheckoutEventListener.java 文件源码 项目:react-native-mercadopago-checkout 阅读 25 收藏 0 点赞 0 评论 0
private WritableMap paymentToMap(@NonNull Payment payment) {
    final String paymentId = payment.getId().toString();
    final String paymentStatus = payment.getStatus();

    final WritableMap map = Arguments.createMap();

    map.putString(PAYMENT_ID, paymentId);
    map.putString(PAYMENT_STATUS, paymentStatus);

    return map;
}


问题


面经


文章

微信
公众号

扫码关注公众号