下面列出了com.facebook.react.bridge.Arguments#createArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ReactMethod
public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) {
Log.d(LOG_TAG, "Get connected peripherals");
WritableArray map = Arguments.createArray();
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
List<BluetoothDevice> periperals = getBluetoothManager().getConnectedDevices(GATT);
for (BluetoothDevice entry : periperals) {
Peripheral peripheral = savePeripheral(entry);
WritableMap jsonBundle = peripheral.asWritableMap();
map.pushMap(jsonBundle);
}
callback.invoke(null, map);
}
public static WritableArray convertJsonToWritableArray(JSONArray jsonArray) throws JSONException {
WritableArray array = Arguments.createArray();
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
array.pushMap(MapUtil.convertJsonToWritableMap((JSONObject) value));
} else if (value instanceof JSONArray) {
array.pushArray(convertJsonToWritableArray((JSONArray) value));
} else if (value instanceof Boolean) {
array.pushBoolean((Boolean) value);
} else if (value instanceof Integer) {
array.pushInt((Integer) value);
} else if (value instanceof Double) {
array.pushDouble((Double) value);
} else if (value instanceof String) {
array.pushString((String) value);
}
}
return array;
}
/**
* Marshalls a function call to the javascript layer, via our NativeModule.
*
* @param context The context needed to execute this in.
* @param name The function to execute. e.g. "Math.Pow"
* @param args The arguments to pass to the function, or null.
* @param cb The completion callback for the result, or null.
* @param event The name of the event that our NativeModule is listening for.
*/
private static void callFunction(ReactContext context, String name, @Nullable Object[] args, @Nullable EvaluatorCallback cb, String event) {
String callId = UUID.randomUUID().toString();
if (null != cb) {
callbacks.put(callId, cb);
}
WritableArray arguments = args != null ? Arguments.fromJavaArgs(args) : Arguments.createArray();
if (arguments.size() == 0) {
arguments.pushNull();
}
WritableMap eventParams = Arguments.createMap();
eventParams.putString("name", name);
eventParams.putArray("args", arguments);
eventParams.putString("callId", callId);
// TODO: move to AppEventEmitter once App events are supported on android.
context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(event, eventParams);
}
public ReadableArray getHistory(long startTime, long endTime) {
DateFormat dateFormat = DateFormat.getDateInstance();
DataReadRequest readRequest = new DataReadRequest.Builder()
.read(this.dataType)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();
DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest)
.await(1, TimeUnit.MINUTES);
WritableArray map = Arguments.createArray();
if (dataReadResult.getDataSets().size() > 0) {
for (DataSet dataSet : dataReadResult.getDataSets()) {
processDataSet(dataSet, map);
}
}
return map;
}
@ReactMethod
public void getBondedPeripherals(Callback callback) {
Log.d(LOG_TAG, "Get bonded peripherals");
WritableArray map = Arguments.createArray();
Set<BluetoothDevice> deviceSet = getBluetoothAdapter().getBondedDevices();
for (BluetoothDevice device : deviceSet) {
Peripheral peripheral;
if (Build.VERSION.SDK_INT >= LOLLIPOP && !forceLegacy) {
peripheral = new LollipopPeripheral(device, reactContext);
} else {
peripheral = new Peripheral(device, reactContext);
}
WritableMap jsonBundle = peripheral.asWritableMap();
map.pushMap(jsonBundle);
}
callback.invoke(null, map);
}
private static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException {
WritableArray array = Arguments.createArray();
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
array.pushMap(convertJsonToMap((JSONObject) value));
} else if (value instanceof JSONArray) {
array.pushArray(convertJsonToArray((JSONArray) value));
} else if (value instanceof Boolean) {
array.pushBoolean((Boolean) value);
} else if (value instanceof Integer) {
array.pushInt((Integer) value);
} else if (value instanceof Double) {
array.pushDouble((Double) value);
} else if (value instanceof String) {
array.pushString((String) value);
}
}
return array;
}
private static void putIntoArray(WritableArray writableArray, Object value) {
if (value instanceof String) {
writableArray.pushString((String) value);
} else if (value instanceof Boolean) {
writableArray.pushBoolean((Boolean) value);
} else if (value instanceof Double) {
writableArray.pushDouble((Double) value);
} else if (value instanceof Integer) {
writableArray.pushInt((Integer) value);
} else if (value == null) {
writableArray.pushNull();
} else if (value.getClass().isArray()) {
WritableArray array = Arguments.createArray();
for (int i = 0, size = Array.getLength(value); i < size; ++i) {
putIntoArray(array, Array.get(value, i));
}
writableArray.pushArray(array);
} else if (value instanceof Collection) {
writableArray.pushArray(toWritableArray((Collection<?>) value));
} else if (value instanceof Map) {
//noinspection unchecked
writableArray.pushMap(toWritableMap((Map<String, ?>) value));
} else {
throw new IllegalArgumentException();
}
}
@Override
public void onUpdateDiscoveredReaders(@Nonnull List<? extends Reader> list) {
discoveredReadersList = list;
WritableArray readersDiscoveredArr = Arguments.createArray();
for(Reader reader : list){
if(reader!=null){
readersDiscoveredArr.pushMap(serializeReader(reader));
}
}
sendEventWithName(EVENT_READERS_DISCOVERED,readersDiscoveredArr);
}
private WritableArray processCloudResult(FirebaseVisionText firebaseVisionText) {
WritableArray data = Arguments.createArray();
WritableMap info = Arguments.createMap();
WritableMap coordinates = Arguments.createMap();
List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
if (blocks.size() == 0) {
return data;
}
for (int i = 0; i < blocks.size(); i++) {
List<FirebaseVisionText.Line> lines = blocks.get(i).getLines();
info = Arguments.createMap();
coordinates = Arguments.createMap();
Rect boundingBox = blocks.get(i).getBoundingBox();
coordinates.putInt("top", boundingBox.top);
coordinates.putInt("left", boundingBox.left);
coordinates.putInt("width", boundingBox.width());
coordinates.putInt("height", boundingBox.height());
info.putMap("blockCoordinates", coordinates);
info.putString("blockText", blocks.get(i).getText());
for (int j = 0; j < lines.size(); j++) {
List<FirebaseVisionText.Element> elements = lines.get(j).getElements();
info.putString("lineText", lines.get(j).getText());
for (int k = 0; k < elements.size(); k++) {
info.putString("elementText", elements.get(k).getText());
}
}
data.pushMap(info);
}
return data;
}
public static WritableArray toWritableArray(Object[] array) {
WritableArray writableArray = Arguments.createArray();
for (int i = 0; i < array.length; i++) {
Object value = array[i];
if (value == null) {
writableArray.pushNull();
}
if (value instanceof Boolean) {
writableArray.pushBoolean((Boolean) value);
}
if (value instanceof Double) {
writableArray.pushDouble((Double) value);
}
if (value instanceof Integer) {
writableArray.pushInt((Integer) value);
}
if (value instanceof String) {
writableArray.pushString((String) value);
}
if (value instanceof Map) {
writableArray.pushMap(MapUtil.toWritableMap((Map<String, Object>) value));
}
if (value.getClass().isArray()) {
writableArray.pushArray(ArrayUtil.toWritableArray((Object[]) value));
}
}
return writableArray;
}
@NonNull
private WritableArray getEmailAddressesFromContact(int contactId) {
WritableArray emailAddresses = Arguments.createArray();
Cursor emailAddressesCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,
null,
null);
while (emailAddressesCursor.moveToNext()) {
WritableMap emailAddress = Arguments.createMap();
String value = getStringFromCursor( emailAddressesCursor, ContactsContract.CommonDataKinds.Email.ADDRESS );
String label = getStringFromCursor( emailAddressesCursor, ContactsContract.CommonDataKinds.Email.LABEL );
int typeInt = getIntFromCursor( emailAddressesCursor, ContactsContract.CommonDataKinds.Email.TYPE );
String type = String.valueOf(ContactsContract.CommonDataKinds.Email.getTypeLabel(getCurrentActivity().getResources(), typeInt, ""));
// NOTE: label is only set for custom Types, so to keep things consistent between iOS and Android
// and to essentially give the user what they really want, which is the label, put type into label if it's null.
if (label == null) label = type;
emailAddress.putString("value", value); // TODO: Consider standardizing on "address" instead of "value".
emailAddress.putString("address", value); // Added in case Android devs are used to accessing it like this.
emailAddress.putString("label", label);
emailAddress.putString("type", type);
emailAddresses.pushMap(emailAddress);
}
emailAddressesCursor.close();
return emailAddresses;
}
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);
}
private void onRequestComplete(int requestId, @Nullable String error) {
WritableArray args = Arguments.createArray();
args.pushInt(requestId);
args.pushString(error);
getEventEmitter().emit("didCompleteNetworkResponse", args);
}
public static WritableArray toWritableArray(Collection<?> map) {
WritableArray writableArray = Arguments.createArray();
for (Object obj : map) {
putIntoArray(writableArray, obj);
}
return writableArray;
}
public static void onDataSend(
RCTDeviceEventEmitter eventEmitter,
int requestId,
long progress,
long total) {
WritableArray args = Arguments.createArray();
args.pushInt(requestId);
args.pushInt((int) progress);
args.pushInt((int) total);
eventEmitter.emit("didSendNetworkData", args);
}
@ReactMethod
public void createTimer(
final int callbackID,
final int duration,
final double jsSchedulingTime,
final boolean repeat) {
long deviceTime = SystemClock.currentTimeMillis();
long remoteTime = (long) jsSchedulingTime;
// If the times on the server and device have drifted throw an exception to warn the developer
// that things might not work or results may not be accurate. This is required only for
// developer builds.
if (mDevSupportManager.getDevSupportEnabled()) {
long driftTime = Math.abs(remoteTime - deviceTime);
if (driftTime > 60000) {
getReactApplicationContext().getJSModule(JSTimers.class)
.emitTimeDriftWarning(
"Debugger and device times have drifted by more than 60s. Please correct this by " +
"running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine.");
}
}
// Adjust for the amount of time it took for native to receive the timer registration call
long adjustedDuration = Math.max(0, remoteTime - deviceTime + duration);
if (duration == 0 && !repeat) {
WritableArray timerToCall = Arguments.createArray();
timerToCall.pushInt(callbackID);
getReactApplicationContext().getJSModule(JSTimers.class)
.callTimers(timerToCall);
return;
}
long initialTargetTime = SystemClock.nanoTime() / 1000000 + adjustedDuration;
Timer timer = new Timer(callbackID, initialTargetTime, duration, repeat);
synchronized (mTimerGuard) {
mTimers.add(timer);
mTimerIdsToTimers.put(callbackID, timer);
}
}
/**
* Method which takes a container tag and then releases all subviews for that container upon
* receipt.
* TODO: The method name is incorrect and will be renamed, #6033872
* @param containerTag the tag of the container for which the subviews must be removed
*/
public void removeSubviewsFromContainerWithID(int containerTag) {
ReactShadowNode containerNode = mShadowNodeRegistry.getNode(containerTag);
if (containerNode == null) {
throw new IllegalViewOperationException(
"Trying to remove subviews of an unknown view tag: " + containerTag);
}
WritableArray indicesToRemove = Arguments.createArray();
for (int childIndex = 0; childIndex < containerNode.getChildCount(); childIndex++) {
indicesToRemove.pushInt(childIndex);
}
manageChildren(containerTag, null, null, null, null, indicesToRemove);
}
/**
* Converts firebaseVisionText into a map
*
* @param firebaseVisionText
* @return
*/
private WritableArray processDeviceResult(FirebaseVisionText firebaseVisionText) {
WritableArray data = Arguments.createArray();
WritableMap info = Arguments.createMap();
WritableMap coordinates = Arguments.createMap();
List<FirebaseVisionText.TextBlock> blocks = firebaseVisionText.getTextBlocks();
if (blocks.size() == 0) {
return data;
}
for (int i = 0; i < blocks.size(); i++) {
List<FirebaseVisionText.Line> lines = blocks.get(i).getLines();
info = Arguments.createMap();
coordinates = Arguments.createMap();
Rect boundingBox = blocks.get(i).getBoundingBox();
coordinates.putInt("top", boundingBox.top);
coordinates.putInt("left", boundingBox.left);
coordinates.putInt("width", boundingBox.width());
coordinates.putInt("height", boundingBox.height());
info.putMap("blockCoordinates", coordinates);
info.putString("blockText", blocks.get(i).getText());
info.putString("resultText", firebaseVisionText.getText());
for (int j = 0; j < lines.size(); j++) {
List<FirebaseVisionText.Element> elements = lines.get(j).getElements();
info.putString("lineText", lines.get(j).getText());
for (int k = 0; k < elements.size(); k++) {
info.putString("elementText", elements.get(k).getText());
}
}
data.pushMap(info);
}
return data;
}
public ReadableArray getActivitySamples(long startTime, long endTime) {
WritableArray results = Arguments.createArray();
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.aggregate(DataType.TYPE_CALORIES_EXPENDED, DataType.AGGREGATE_CALORIES_EXPENDED)
.aggregate(DataType.TYPE_DISTANCE_DELTA, DataType.AGGREGATE_DISTANCE_DELTA)
.bucketByActivitySegment(1, TimeUnit.SECONDS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest).await(1, TimeUnit.MINUTES);
List<Bucket> buckets = dataReadResult.getBuckets();
for (Bucket bucket : buckets) {
String activityName = bucket.getActivity();
int activityType = bucket.getBucketType();
if (!bucket.getDataSets().isEmpty()) {
long start = bucket.getStartTime(TimeUnit.MILLISECONDS);
long end = bucket.getEndTime(TimeUnit.MILLISECONDS);
Date startDate = new Date(start);
Date endDate = new Date(end);
WritableMap map = Arguments.createMap();
map.putDouble("start",start);
map.putDouble("end",end);
map.putString("activityName", activityName);
String deviceName = "";
String sourceId = "";
boolean isTracked = true;
for (DataSet dataSet : bucket.getDataSets()) {
for (DataPoint dataPoint : dataSet.getDataPoints()) {
try {
int deviceType = dataPoint.getOriginalDataSource().getDevice().getType();
if (deviceType == TYPE_WATCH) {
deviceName = "Android Wear";
} else {
deviceName = "Android";
}
} catch (Exception e) {
}
sourceId = dataPoint.getOriginalDataSource().getAppPackageName();
if (startDate.getTime() % 1000 == 0 && endDate.getTime() % 1000 == 0) {
isTracked = false;
}
for (Field field : dataPoint.getDataType().getFields()) {
String fieldName = field.getName();
switch (fieldName) {
case STEPS_FIELD_NAME:
map.putInt("quantity", dataPoint.getValue(field).asInt());
break;
case DISTANCE_FIELD_NAME:
map.putDouble(fieldName, dataPoint.getValue(field).asFloat());
break;
case CALORIES_FIELD_NAME:
map.putDouble(fieldName, dataPoint.getValue(field).asFloat());
default:
Log.w(TAG, "don't specified and handled: " + fieldName);
}
}
}
}
map.putString("device", deviceName);
map.putString("sourceName", deviceName);
map.putString("sourceId", sourceId);
map.putBoolean("tracked", isTracked);
results.pushMap(map);
}
}
return results;
}
@ReactMethod
public void searchContacts( String searchText, Callback callback ) {
WritableArray contacts = Arguments.createArray();
Set<Integer> contactIds = new HashSet<Integer>();
contentResolver = getCurrentActivity().getContentResolver();
String whereString = null;
String[] whereParams = null;
if ( searchText != null && !searchText.equals( "" ) ) {
whereString = "display_name LIKE ?";
whereParams = new String[]{ "%" + searchText + "%" };
}
Cursor contactCursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
whereString,
whereParams,
null );
while( contactCursor.moveToNext() ) {
int contactId = getIntFromCursor( contactCursor, ContactsContract.Data.CONTACT_ID );
if ( contactIds.contains( contactId ) ) continue;
WritableMap contact = getContactDetailsFromContactId(contactId);
contacts.pushMap(contact);
contactIds.add( contactId );
}
contactCursor.close();
// ToDo: Add check for error and return error callback instead
// i.e. callback.invoke(error, null)
// Success
callback.invoke(null, contacts);
}