下面列出了怎么用com.facebook.react.bridge.WritableArray的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Retrieves contacts matching String.
* Uses raw URI when <code>rawUri</code> is <code>true</code>, makes assets copy otherwise.
*
* @param searchString String to match
* @param callback user provided callback to run at completion
*/
@ReactMethod
public void getContactsMatchingString(final String searchString, final Callback callback) {
AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(final Void ... params) {
Context context = getReactApplicationContext();
ContentResolver cr = context.getContentResolver();
ContactsProvider contactsProvider = new ContactsProvider(cr);
WritableArray contacts = contactsProvider.getContactsMatchingString(searchString);
callback.invoke(null, contacts);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
/**
* Converts firebaseVisionText into a map
*
* @param firebaseVisionText
* @return
*/
private WritableArray getDataAsArray(FirebaseVisionText firebaseVisionText) {
WritableArray data = Arguments.createArray();
WritableMap info = Arguments.createMap();
WritableMap coordinates = Arguments.createMap();
for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
info = Arguments.createMap();
coordinates = Arguments.createMap();
Rect boundingBox = block.getBoundingBox();
coordinates.putInt("top", boundingBox.top);
coordinates.putInt("left", boundingBox.left);
coordinates.putInt("width", boundingBox.width());
coordinates.putInt("height", boundingBox.height());
info.putMap("bounding", coordinates);
info.putString("text", block.getText());
data.pushMap(info);
}
return data;
}
private WritableArray getAudioTrackInfo() {
WritableArray audioTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_AUDIO);
if (info == null || index == C.INDEX_UNSET) {
return audioTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap audioTrack = Arguments.createMap();
audioTrack.putInt("index", i);
audioTrack.putString("title", format.id != null ? format.id : "");
audioTrack.putString("type", format.sampleMimeType);
audioTrack.putString("language", format.language != null ? format.language : "");
audioTrack.putString("bitrate", format.bitrate == Format.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbps", format.bitrate / 1000000f));
audioTracks.pushMap(audioTrack);
}
return audioTracks;
}
@ReactMethod
public void getAllKeys(String service, Promise promise) {
try {
service = getDefaultServiceIfNull(service);
final PrefsStorage prefsStorage = new PrefsStorage(getReactApplicationContext(), service);
String[] allKeys = prefsStorage.getAllKeys();
WritableArray keyArray = new WritableNativeArray();
for (String key : allKeys) {
keyArray.pushString(key);
}
promise.resolve(keyArray);
return;
} catch (Exception e) {
Log.e(SECURE_STORAGE_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
}
}
/**
* Retrieves contacts matching a phone number.
* Uses raw URI when <code>rawUri</code> is <code>true</code>, makes assets copy otherwise.
*
* @param phoneNumber phone number to match
* @param callback user provided callback to run at completion
*/
@ReactMethod
public void getContactsByPhoneNumber(final String phoneNumber, final Callback callback) {
AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
@Override
protected Void doInBackground(final Void ... params) {
Context context = getReactApplicationContext();
ContentResolver cr = context.getContentResolver();
ContactsProvider contactsProvider = new ContactsProvider(cr);
WritableArray contacts = contactsProvider.getContactsByPhoneNumber(phoneNumber);
callback.invoke(null, contacts);
return null;
}
};
myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
/***
* This method will expose all the available languages in TTS engine
*
* @param callback
*/
@ReactMethod
public void getLocale(final Callback callback) {
new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
@Override
protected void doInBackgroundGuarded(Void... params) {
try {
if (tts == null) {
init();
}
Locale[] locales = Locale.getAvailableLocales();
WritableArray data = Arguments.createArray();
for (Locale locale : locales) {
int res = tts.isLanguageAvailable(locale);
if (res == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
data.pushString(locale.getLanguage());
}
}
callback.invoke(null, data);
} catch (Exception e) {
callback.invoke(e.getMessage());
}
}
}.execute();
}
public static WritableArray jsonToReact(JSONArray jsonArray) throws JSONException {
WritableArray writableArray = Arguments.createArray();
for(int i=0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof Float || value instanceof Double) {
writableArray.pushDouble(jsonArray.getDouble(i));
} else if (value instanceof Number) {
writableArray.pushInt(jsonArray.getInt(i));
} else if (value instanceof String) {
writableArray.pushString(jsonArray.getString(i));
} else if (value instanceof JSONObject) {
writableArray.pushMap(jsonToReact(jsonArray.getJSONObject(i)));
} else if (value instanceof JSONArray){
writableArray.pushArray(jsonToReact(jsonArray.getJSONArray(i)));
} else if (value == JSONObject.NULL){
writableArray.pushNull();
}
}
return writableArray;
}
public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data) {
WritableMap event = Arguments.createMap();
try {
String rawMeta = new String(data.getMetaData(), "UTF-8");
WritableMap id3 = Arguments.createMap();
id3.putString(EVENT_PROP_METADATA_VALUE, rawMeta.substring(rawMeta.lastIndexOf("\u0003") + 1));
id3.putString(EVENT_PROP_METADATA_IDENTIFIER, "id3/TDEN");
WritableArray metadata = new WritableNativeArray();
metadata.pushMap(id3);
event.putArray(EVENT_PROP_METADATA, metadata);
event.putDouble(EVENT_PROP_TARGET, getId());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mEventEmitter.receiveEvent(getId(), Events.EVENT_TIMED_METADATA.toString(), event);
}
@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);
}
private WritableMap createRangingResponse(Collection<Beacon> beacons, Region region) {
WritableMap map = new WritableNativeMap();
map.putString("identifier", region.getUniqueId());
map.putString("uuid", region.getId1() != null ? region.getId1().toString() : "");
WritableArray a = new WritableNativeArray();
for (Beacon beacon : beacons) {
WritableMap b = new WritableNativeMap();
b.putString("uuid", beacon.getId1().toString());
b.putInt("major", beacon.getId2().toInt());
b.putInt("minor", beacon.getId3().toInt());
b.putInt("rssi", beacon.getRssi());
b.putDouble("distance", beacon.getDistance());
b.putString("proximity", getProximity(beacon.getDistance()));
a.pushMap(b);
}
map.putArray("beacons", a);
return map;
}
private WritableArray getTextTrackInfo() {
WritableArray textTracks = Arguments.createArray();
MappingTrackSelector.MappedTrackInfo info = trackSelector.getCurrentMappedTrackInfo();
int index = getTrackRendererIndex(C.TRACK_TYPE_TEXT);
if (info == null || index == C.INDEX_UNSET) {
return textTracks;
}
TrackGroupArray groups = info.getTrackGroups(index);
for (int i = 0; i < groups.length; ++i) {
Format format = groups.get(i).getFormat(0);
WritableMap textTrack = Arguments.createMap();
textTrack.putInt("index", i);
textTrack.putString("title", format.id != null ? format.id : "");
textTrack.putString("type", format.sampleMimeType);
textTrack.putString("language", format.language != null ? format.language : "");
textTracks.pushMap(textTrack);
}
return textTracks;
}
/**
* 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 void testStringWithMultibyteUTF8Characters() {
TestJavaToJSArgumentsModule jsModule = mInstance.getJSModule(TestJavaToJSArgumentsModule.class);
WritableNativeMap map = new WritableNativeMap();
map.putString("two-bytes", "\u00A2");
map.putString("three-bytes", "\u20AC");
map.putString("four-bytes", "\uD83D\uDE1C");
map.putString(
"mixed",
"\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");
jsModule.receiveMapWithMultibyteUTF8CharacterString(map);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();
WritableArray array = new WritableNativeArray();
array.pushString("\u00A2");
array.pushString("\u20AC");
array.pushString("\uD83D\uDE1C");
array.pushString(
"\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 \u6211 \uD83D\uDE0E ja\u017A\u0107");
jsModule.receiveArrayWithMultibyteUTF8CharacterString(array);
waitForBridgeAndUIIdle();
mAssertModule.verifyAssertsAndReset();
}
/********Feature Requests*********/
@Test
public void givenArgs$setEmailFieldRequiredForFeatureRequests_whenQuery_thenShouldCallNativeApi() {
// given
PowerMockito.mockStatic(FeatureRequests.class);
PowerMockito.mockStatic(Arguments.class);
// when
PowerMockito.when(Arguments.createArray()).thenReturn(new JavaOnlyArray());
ReadableArray actionTypes = Arguments.createArray();
((WritableArray) actionTypes).pushString("requestNewFeature");
((WritableArray) actionTypes).pushString("addCommentToFeature");
featureRequestsModule.setEmailFieldRequiredForFeatureRequests(true, actionTypes );
int[] parsedActionTypes = new int[2];
parsedActionTypes[0] = ActionType.REQUEST_NEW_FEATURE;
parsedActionTypes[1] = ActionType.ADD_COMMENT_TO_FEATURE;
// then
PowerMockito.verifyStatic(VerificationModeFactory.times(1));
FeatureRequests.setEmailFieldRequired(true, parsedActionTypes);
}
public static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException {
WritableArray array = new WritableNativeArray();
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);
} else {
array.pushString(value.toString());
}
}
return array;
}
public static WritableArray convertArrayToWritableArray(Object[] input) {
WritableArray output = new WritableNativeArray();
for (int i = 0; i < input.length; i++) {
Object value = input[i];
if (value instanceof Map) {
output.pushMap(convertMapToWritableMap((Map<String, Object>) value));
} else if (value instanceof JSONArray) {
output.pushArray(convertArrayToWritableArray((Object[]) value));
} else if (value instanceof Boolean) {
output.pushBoolean((Boolean) value);
} else if (value instanceof Integer) {
output.pushInt((Integer) value);
} else if (value instanceof Double) {
output.pushDouble((Double) value);
} else if (value instanceof String) {
output.pushString((String) value);
} else {
output.pushString(value.toString());
}
}
return output;
}
@ReactMethod
public void getBluetoothDeviceName(Promise aPromise) {
if (mOBD2Handler == null) {
mOBD2Handler = new OBD2Handler(mReactContext);
}
try {
Set<BluetoothDevice> pairedDevices = mOBD2Handler.getBondedDevices();
WritableArray deviceList = mArguments.createArray();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
WritableMap map = mArguments.createMap();
map.putString("name", device.getName());
map.putString("address", device.getAddress());
deviceList.pushMap(map);
}
}
aPromise.resolve(deviceList);
} catch (IOException e) {
e.printStackTrace();
aPromise.reject(TAG, e);
}
}
public WritableArray getContactsByEmailAddress(String emailAddress) {
Map<String, Contact> matchingContacts;
{
Cursor cursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
FULL_PROJECTION.toArray(new String[FULL_PROJECTION.size()]),
ContactsContract.CommonDataKinds.Email.ADDRESS + " LIKE ?",
new String[]{"%" + emailAddress + "%"},
null
);
try {
matchingContacts = loadContactsFrom(cursor);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
WritableArray contacts = Arguments.createArray();
for (Contact contact : matchingContacts.values()) {
contacts.pushMap(contact.toMap());
}
return contacts;
}
private void processDataSet(DataSet dataSet, WritableArray map) {
//Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getDefault());
WritableMap stepMap = Arguments.createMap();
for (DataPoint dp : dataSet.getDataPoints()) {
Log.i(TAG, "\tData point:");
Log.i(TAG, "\t\tType : " + dp.getDataType().getName());
Log.i(TAG, "\t\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Log.i(TAG, "\t\tEnd : " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
for(Field field : dp.getDataType().getFields()) {
Log.i(TAG, "\t\tField: " + field.getName() +
" Value: " + dp.getValue(field));
stepMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
stepMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
stepMap.putDouble("steps", dp.getValue(field).asInt());
map.pushMap(stepMap);
}
}
}
private static WritableMap fromJsonObject(JsonObject object) {
WritableMap result = new WritableNativeMap();
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Object value = fromJson(entry.getValue());
if (value instanceof WritableMap) {
result.putMap(entry.getKey(), (WritableMap) value);
} else if (value instanceof WritableArray) {
result.putArray(entry.getKey(), (WritableArray) value);
} else if (value instanceof String) {
result.putString(entry.getKey(), (String) value);
} else if (value instanceof LazilyParsedNumber) {
result.putInt(entry.getKey(), ((LazilyParsedNumber) value).intValue());
} else if (value instanceof Integer) {
result.putInt(entry.getKey(), (Integer) value);
} else if (value instanceof Double) {
result.putDouble(entry.getKey(), (Double) value);
} else if (value instanceof Boolean) {
result.putBoolean(entry.getKey(), (Boolean) value);
} else {
Log.d("ArgumentUtils", "Unknown type: " + value.getClass().getName());
result.putNull(entry.getKey());
}
}
return result;
}
private static WritableArray fromJsonArray(JsonArray arr) {
WritableArray result = new WritableNativeArray();
for (JsonElement el : arr) {
Object item = fromJson(el);
if (item instanceof WritableMap) {
result.pushMap((WritableMap) item);
} else if (item instanceof WritableArray) {
result.pushArray((WritableArray) item);
} else if (item instanceof String) {
result.pushString((String) item);
} else if (item instanceof LazilyParsedNumber) {
result.pushInt(((LazilyParsedNumber) item).intValue());
} else if (item instanceof Integer) {
result.pushInt((Integer) item);
} else if (item instanceof Double) {
result.pushDouble((Double) item);
} else if (item instanceof Boolean) {
result.pushBoolean((Boolean) item);
} else {
Log.d("ArgumentUtils", "Unknown type: " + item.getClass().getName());
result.pushNull();
}
}
return result;
}
@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);
}
public static ReadableArray intArrayToReadableArray(int[] arr) {
WritableArray writableArray = new WritableNativeArray();
for (int i : arr) {
writableArray.pushInt(i);
}
return writableArray;
}
public static WritableArray jsonArrayToWritableArray(JSONArray jsonArray) {
WritableArray writableArray = new WritableNativeArray();
if (jsonArray == null) {
return null;
}
if (jsonArray.length() <= 0) {
return null;
}
for (int i = 0 ; i < jsonArray.length(); i++) {
try {
Object value = jsonArray.get(i);
if (value == null) {
writableArray.pushNull();
} else if (value instanceof Boolean) {
writableArray.pushBoolean((Boolean) value);
} else if (value instanceof Integer) {
writableArray.pushInt((Integer) value);
} else if (value instanceof Double) {
writableArray.pushDouble((Double) value);
} else if (value instanceof String) {
writableArray.pushString((String) value);
} else if (value instanceof JSONObject) {
writableArray.pushMap(jsonToWritableMap((JSONObject) value));
} else if (value instanceof JSONArray) {
writableArray.pushArray(jsonArrayToWritableArray((JSONArray) value));
}
} catch (JSONException e) {
// Do nothing and fail silently
}
}
return writableArray;
}
/**
* 获取联系人页展示的用户
*
* @param callback
*/
@ReactMethod
public void getContacts(Callback callback) {
List<Nick> fList = ConnectionUtil.getInstance().SelectFriendListForRN();
WritableNativeMap map = new WritableNativeMap();
WritableArray array = new WritableNativeArray();
if (fList != null && fList.size() > 0) {
// WritableMap map = new WritableNativeMap();
for (int i = 0; i < fList.size(); i++) {
Nick nick = fList.get(i);
WritableNativeMap item = new WritableNativeMap();
String name = nick.getName();
String pinyin = nick.getXmppId();
if (!TextUtils.isEmpty(name)) {
pinyin = HanziToPinyin.zh2Abb(name);
}
item.putString("Name", TextUtils.isEmpty(name) ? nick.getXmppId() : name);
item.putString("HeaderUri", TextUtils.isEmpty(nick.getHeaderSrc()) ? "" : nick.getHeaderSrc());
item.putString("SearchIndex", pinyin);
item.putString("XmppId", nick.getXmppId());
item.putString("Remark", nick.getMark());
item.putString("Mood",nick.getMood());
array.pushMap(item);
}
}
map.putArray("contacts", array);
callback.invoke(map);
// WritableNativeMap map2= new WritableNativeMap();
// map2.putString("aaa","aaaa");
// sendEvent("EventName",map2);
}
public static WritableArray getChildKeys(DataSnapshot snapshot) {
WritableArray childKeys = Arguments.createArray();
if (snapshot.hasChildren()) {
for (DataSnapshot child : snapshot.getChildren()) {
childKeys.pushString(child.getKey());
}
}
return childKeys;
}
public static ReadableArray doubleArrayToReadableArray(double[] arr) {
WritableArray writableArray = new WritableNativeArray();
for (double d : arr) {
writableArray.pushDouble(d);
}
return writableArray;
}
@ReactMethod
public void listOwnedProducts(final Promise promise){
if (bp != null) {
List<String> purchasedProductIds = bp.listOwnedProducts();
WritableArray arr = Arguments.createArray();
for (int i = 0; i < purchasedProductIds.size(); i++) {
arr.pushString(purchasedProductIds.get(i));
}
promise.resolve(arr);
} else {
promise.reject("EUNSPECIFIED", "Channel is not opened. Call open() on InAppBilling.");
}
}
/**
* Get all the payloads received by this device
*/
@ReactMethod
public void payloads(final Promise promise) {
WritableArray result = Arguments.createArray();
for (String key : mReceivedPayloads.keySet()) {
// Explode key to get serviceId, endpointId, payloadId
//result.pushMap(endpoint.toWritableMap());
}
promise.resolve(result);
}
public void getDistance(Context context, double startDate, double endDate, String customInterval, final Promise promise) {
TimeUnit interval = getInterval(customInterval);
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_DISTANCE_DELTA, DataType.AGGREGATE_DISTANCE_DELTA)
.bucketByTime(1, interval)
.setTimeRange((long) startDate, (long) endDate, TimeUnit.MILLISECONDS)
.build();
Fitness.getHistoryClient(context, GoogleSignIn.getLastSignedInAccount(context))
.readData(readRequest)
.addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
@Override
public void onSuccess(DataReadResponse dataReadResponse) {
if (dataReadResponse.getBuckets().size() > 0) {
WritableArray distances = Arguments.createArray();
for (Bucket bucket : dataReadResponse.getBuckets()) {
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
processDistance(dataSet, distances);
}
}
promise.resolve(distances);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
promise.reject(e);
}
})
.addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
@Override
public void onComplete(@NonNull Task<DataReadResponse> task) {
}
});
}