下面列出了怎么用com.facebook.react.bridge.ReadableMap的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Invoked by React to create a new node with a given tag has its properties changed.
*/
public void updateView(int tag, String className, ReadableMap props) {
ViewManager viewManager = mViewManagers.get(className);
if (viewManager == null) {
throw new IllegalViewOperationException("Got unknown view type: " + className);
}
ReactShadowNode cssNode = mShadowNodeRegistry.getNode(tag);
if (cssNode == null) {
throw new IllegalViewOperationException("Trying to update non-existent view with tag " + tag);
}
if (props != null) {
ReactStylesDiffMap styles = new ReactStylesDiffMap(props);
cssNode.updateProperties(styles);
handleUpdateView(cssNode, className, styles);
}
}
@ReactMethod
public void post(String path, ReadableMap map, final Promise promise) {
Log.d(TAG, "post");
Object data = fromReactArgument(map);
if (data == null) {
promise.reject("invalid-data-type", "invalid data type");
return;
}
mApiMagnet.post(path, data, new Api.Callback() {
@Override
public void resolve(Object result) {
promise.resolve(toReactArgument(result));
}
@Override
public void reject(String error) {
promise.reject(error, error);
}
});
}
static public OAuthRequest getRequestForProvider(
final String providerName,
final Verb httpVerb,
final OAuth2AccessToken oa2token,
final URL url,
final HashMap<String,Object> cfg,
@Nullable final ReadableMap params
) {
final OAuth20Service service =
OAuthManagerProviders.getApiFor20Provider(providerName, cfg, null, null);
OAuthConfig config = service.getConfig();
OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config);
String token = oa2token.getAccessToken();
request = OAuthManagerProviders.addParametersToRequest(request, token, params);
//
Log.d(TAG, "Making request for " + providerName + " to add token " + token);
// Need a way to standardize this, but for now
if (providerName.equalsIgnoreCase("slack")) {
request.addParameter("token", token);
}
return request;
}
SocketClient(ReadableMap params, ReactContext reactContext) {
//String addr, int port, boolean autoReconnect
mReactContext = reactContext;
dstAddress = params.getString("address");
dstPort = params.getInt("port");
if (params.hasKey("timeout")) {
timeout = params.getInt("timeout");
} else {
timeout = 60000;
}
if (params.hasKey("reconnect")) {
reconnectOnClose = params.getBoolean("reconnect");
}
if (params.hasKey("maxReconnectAttempts")) {
maxReconnectAttempts = params.getInt("maxReconnectAttempts");
}
if (params.hasKey("reconnectDelay")) {
reconnectDelay = params.getInt("reconnectDelay");
}
Thread socketClientThread = new Thread(new SocketClientThread());
socketClientThread.start();
}
public RNAGSGraphicsOverlay(ReadableMap rawData, GraphicsOverlay graphicsOverlay) {
this.referenceId = rawData.getString("referenceId");
ReadableArray pointImageDictionaryRaw = rawData.getArray("pointGraphics");
pointImageDictionary = new HashMap<>();
this.graphicsOverlay = graphicsOverlay;
for (int i = 0; i < pointImageDictionaryRaw.size(); i++) {
ReadableMap item = pointImageDictionaryRaw.getMap(i);
if (item.hasKey("graphicId")) {
String graphicId = item.getString("graphicId");
String uri = item.getMap("graphic").getString("uri");
pointImageDictionary.put(graphicId, uri);
}
}
// Create graphics within overlay
ReadableArray rawPoints = rawData.getArray("points");
for (int i = 0; i < rawPoints.size(); i++) {
addGraphicsLoop(rawPoints.getMap(i));
}
}
@ReactProp(name = "profile")
public void setProfile(AspectFrameLayout view, @Nullable ReadableMap profile) {
ReadableMap video = profile.getMap("video");
ReadableMap audio = profile.getMap("audio");
int encodingSize = profile.getInt("encodingSize");
StreamingProfile.AudioProfile aProfile =
new StreamingProfile.AudioProfile(audio.getInt("rate"), audio.getInt("bitrate")); //audio sample rate, audio bitrate
StreamingProfile.VideoProfile vProfile =
new StreamingProfile.VideoProfile(video.getInt("fps"), video.getInt("bps"), video.getInt("maxFrameInterval"));//fps bps maxFrameInterval
StreamingProfile.AVProfile avProfile = new StreamingProfile.AVProfile(vProfile, aProfile);
mProfile.setAVProfile(avProfile);
mProfile.setEncodingSizeLevel(encodingSize);
mMediaStreamingManager.setStreamingProfile(mProfile);
}
@ReactMethod
public void recognize(String path, String lang, @Nullable ReadableMap tessOptions, Promise promise) {
prepareTesseract();
Log.d(REACT_CLASS, "Start ocr images");
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// TODO:
// Check image size before use inSampleSize (maybe this could help) --> https://goo.gl/4MvBvB
// considering that when inSampleSize is used (usually to save memory) the ocr quality decreases
//options.inSampleSize = 4; //inSampleSize documentation --> http://goo.gl/KRrlvi
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
String result = extractText(bitmap, lang, tessOptions);
promise.resolve(result);
} catch (Exception e) {
Log.e(REACT_CLASS, e.getMessage());
promise.reject("An error occurred", e.getMessage());
}
}
@ReactMethod
public void readAsText(ReadableMap blob, String encoding, Promise promise) {
byte[] bytes = getBlobModule().resolve(
blob.getString("blobId"),
blob.getInt("offset"),
blob.getInt("size"));
if (bytes == null) {
promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid");
return;
}
try {
promise.resolve(new String(bytes, encoding));
} catch (Exception e) {
promise.reject(e);
}
}
@ReactProp(name = "region")
public void setRegion(MapView mapView, @Nullable ReadableMap region) {
if (region == null) return;
AMap map = mapView.getMap();
Double lat = region.getDouble("latitude");
Double lng = region.getDouble("longitude");
Double lngDelta = region.getDouble("longitudeDelta");
Double latDelta = region.getDouble("latitudeDelta");
LatLngBounds bounds = new LatLngBounds(
new LatLng(lat - latDelta / 2, lng - lngDelta / 2), // southwest
new LatLng(lat + latDelta / 2, lng + lngDelta / 2) // northeast
);
if (mapView.getHeight() <= 0 || mapView.getWidth() <= 0) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
boundsToMove = bounds;
} else {
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
}
}
/**
* Invoked by React to create a new node with a given tag, class name and properties.
*/
public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
ReactShadowNode cssNode = createShadowNode(className);
ReactShadowNode rootNode = mShadowNodeRegistry.getNode(rootViewTag);
Assertions.assertNotNull(rootNode, "Root node with tag " + rootViewTag + " doesn't exist");
cssNode.setReactTag(tag);
cssNode.setViewClassName(className);
cssNode.setRootTag(rootNode.getReactTag());
cssNode.setThemedContext(rootNode.getThemedContext());
mShadowNodeRegistry.addNode(cssNode);
ReactStylesDiffMap styles = null;
if (props != null) {
styles = new ReactStylesDiffMap(props);
cssNode.updateProperties(styles);
}
handleCreateView(cssNode, rootViewTag, styles);
}
/**
* Ajout Tab contribuée sans Custom View:
*
* @param configMap
* @return
*/
public boolean attachTab(ReadableMap configMap) {
if (configMap != null) {
Tab tab = this.newTab();
if (configMap.hasKey("text")) {
tab.setText(configMap.getString("text"));
}
if (configMap.hasKey("icon")) {
tab.setIcon(ContextCompat.getDrawable(this.getContext(), Drawable.getID(this, configMap.getString("icon"))));
}
this.addTab(tab);
return true;
}
return false;
}
public void setPov(ReadableMap pov) {
if (pov == null ) return;
tilt = (float) pov.getDouble("tilt");
bearing = (float) pov.getDouble("bearing");
zoom = pov.getInt("zoom");
long duration = 1000;
if (bearing > 0 && this.started) {
StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder()
.zoom(zoom)
.tilt(tilt)
.bearing(bearing)
.build();
panorama.animateTo(camera,duration);
}
}
/**
* Ajout Tab contribuée sans Custom View:
*
* @param configMap
* @return
*/
public boolean attachTab(ReadableMap configMap) {
if (configMap != null) {
Tab tab = this.newTab();
if (configMap.hasKey("text")) {
tab.setText(configMap.getString("text"));
}
if (configMap.hasKey("icon")) {
tab.setIcon(ContextCompat.getDrawable(this.getContext(), Drawable.getID(this, configMap.getString("icon"))));
}
this.addTab(tab);
return true;
}
return false;
}
/**
*
* @param dbname - The name of the database file
* @param options - options passed in from JS
* @param cbc - JS callback context
*/
private void startDatabase(String dbname, ReadableMap options, CallbackContext cbc) {
// TODO: is it an issue that we can orphan an existing thread? What should we do here?
// If we re-use the existing DBRunner it might be in the process of closing...
DBRunner r = dbrmap.get(dbname);
// Brody TODO: It may be better to terminate the existing db thread here & start a new one, instead.
if (r != null) {
// don't orphan the existing thread; just re-open the existing database.
// In the worst case it might be in the process of closing, but even that's less serious
// than orphaning the old DBRunner.
cbc.success("database started");
} else {
r = new DBRunner(dbname, options, cbc);
dbrmap.put(dbname, r);
this.getThreadPool().execute(r);
}
}
/**
* Converts Facebook's ReadableMap to a Java Map<>
*
* @param readableMap The Readable Map to parse
* @return a Java Map<> to be used in memory
*/
public static Map<String, Object> toMap(@Nullable ReadableMap readableMap) {
if (readableMap == null) {
return null;
}
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
if (!iterator.hasNextKey()) {
return null;
}
Map<String, Object> result = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
result.put(key, toObject(readableMap, key));
}
return result;
}
@ReactMethod
public final void sendRequest(
String method,
String url,
int requestId,
ReadableArray headers,
ReadableMap data,
final String responseType,
boolean incrementalUpdates,
int timeout,
boolean withCredentials) {
mLastRequestId = requestId;
mRequestCount++;
mRequestMethod = method;
mRequestURL = url;
mRequestHeaders = headers;
mRequestData = data;
if (mRequestListener != null) {
mRequestListener.onRequest(method, url, headers, data);
}
if (mCompleteRequest) {
onResponseReceived(requestId, mResponseCode, null);
onDataReceived(requestId, mResponseBody);
onRequestComplete(requestId, null);
}
}
/**
* 进行网络请求
*/
@ReactMethod
public void getSearchInfo(String url, ReadableMap params, ReadableMap cookie, Callback callback1, final Callback callback2) {
final WritableNativeMap map = new WritableNativeMap();
HttpUtil.PostUrl(url, params.toHashMap(), cookie.toHashMap(), new ProtocolCallback.UnitCallback<String>() {
@Override
public void onCompleted(String s) {
map.putBoolean("isOk", true);
map.putString("responseJson", s);
callback2.invoke(map);
}
@Override
public void onFailure(String errMsg) {
map.putBoolean("isOk", false);
map.putString("message", errMsg);
callback2.invoke(map);
}
});
//
}
@ReactMethod
public void sendOverSocket(ReadableMap blob, int id) {
byte[] data = resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size"));
if (data != null) {
getWebSocketModule().sendBinary(ByteString.of(data), id);
} else {
getWebSocketModule().sendBinary((ByteString) null, id);
}
}
private SocialObject createSocialObject(ReadableMap social) {
SocialObject.Builder socialObject = SocialObject.newBuilder();
if (social.hasKey("likeCount")) socialObject.setLikeCount(social.getInt("likeCount"));
if (social.hasKey("commentCount"))
socialObject.setCommentCount(social.getInt("commentCount"));
if (social.hasKey("sharedCount")) socialObject.setSharedCount(social.getInt("sharedCount"));
if (social.hasKey("subscriberCount"))
socialObject.setSubscriberCount(social.getInt("subscriberCount"));
if (social.hasKey("viewCount")) socialObject.setViewCount(social.getInt("viewCount"));
return socialObject.build();
}
@ReactMethod
public void identify(String userId, ReadableMap traits) {
try {
Analytics.with(this.getReactApplicationContext()).identify(
userId,
toTraits(traits),
null
);
} catch (Exception e) {
Log.e("SegmentAnalyticsModule", "Failed to identify " + userId + ". " + e.getMessage());
}
}
private RouteParaOption createRouteParaOption(ReadableMap startPoint, ReadableMap endPoint) {
RouteParaOption paraOption = new RouteParaOption()
.startPoint(LatLngUtil.fromReadableMap(startPoint))
.endPoint(LatLngUtil.fromReadableMap(endPoint))
.busStrategyType(RouteParaOption.EBusStrategyType.bus_recommend_way);
if (startPoint.hasKey(KEY_NAME)) {
paraOption.startName(startPoint.getString(KEY_NAME));
}
if (endPoint.hasKey(KEY_NAME)) {
paraOption.endName(endPoint.getString(KEY_NAME));
}
return paraOption;
}
/**
* 删除好友
*
* @param params
*/
@ReactMethod
public void deleteUserFriend(ReadableMap params) {
String jid = params.getString("UserId");
//这个好友可能是跨域的 所以domain不能取内存的 要从jid截取
ConnectionUtil.getInstance().deleteFriend(QtalkStringUtils.parseId(jid), QtalkStringUtils.parseDomain(jid));
saveRNActLog("delete friend", "删除好友", "好友名片页");
}
@ReactMethod
public void echoStringValue(ReadableMap args, Callback success, Callback error) {
String actionAsString = "echoStringValue";
try {
this.execute(actionAsString, args, new CallbackContext(success, error));
} catch (Exception ex){
error.invoke("Unexpected error");
}
}
@ReactMethod
public void getUserData (ReadableMap accountObject, String key, Promise promise) {
Account account = accounts.get(accountObject.getInt("_index"));
if(account == null) {
promise.reject("Invalid account");
return;
}
WritableNativeMap result = new WritableNativeMap();
result.putString("value", manager.getUserData(account, key));
promise.resolve(result);
return;
}
public void testInvalidIteratorExceptionThrown() {
mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class).returnMapWithBasicTypes();
waitForBridgeAndUIIdle();
List<ReadableMap> calls = mRecordingTestModule.getMapCalls();
assertEquals(1, calls.size());
ReadableNativeMap map = (ReadableNativeMap) calls.get(0);
assertNotNull(map);
ReadableMapKeySetIterator mapIterator = map.keySetIterator();
while (mapIterator.hasNextKey()) {
mapIterator.nextKey();
}
assertInvalidIteratorExceptionThrown(mapIterator);
}
/**
* 群角色管理
* @param params
* @param callback
*/
@ReactMethod
public void setGroupAdmin(ReadableMap params, Callback callback){
Logger.i("setGroupAdmin:" + params.toString());
String groupId = params.getString("groupId");
String xmppid = params.getString("xmppid");
String name = params.getString("name");
boolean isAdmin = params.getBoolean("isAdmin");
ConnectionUtil.getInstance().setGroupAdmin(groupId,xmppid,name,isAdmin);
}
@ReactMethod
public void updateView(int tag, String className, ReadableMap props) {
if (DEBUG) {
String message =
"(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props;
FLog.d(ReactConstants.TAG, message);
PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
}
mUIImplementation.updateView(tag, className, props);
}
@ReactMethod
public void decode(ReadableMap option, final Promise promise) {
int decoderID = option.getInt("decoder");
Decoder decoder = RNLBarCodeUtils.getDecoderByID(decoderID);
if (decoder == null) {
promise.reject(RNLBarCodeError.InvokeFailed.toString(),
"Device doesn't support this decoder");
return;
}
decoder.setFormats(option.getArray("formats"));
Bitmap image = null;
if (option.getBoolean("screenshot")) {
image = RNLBarCodeUtils.takeScreenshot(getCurrentActivity());
if (image == null) {
promise.reject(RNLBarCodeError.InvokeFailed.toString(),
"Can't take screenshot");
}
} else {
try {
image = RNLBarCodeUtils.parseImageStr(option.getString("data"));
} catch (Exception e) {
promise.reject(RNLBarCodeError.InvokeFailed.toString(),
"Parse image failed, reason: " + e.getMessage());
}
}
if (image != null) {
promise.resolve(decoder.decodeRGBBitmap(image));
}
decoder.release();
}
public DatePicker(ReadableMap options, Callback callback) {
final Calendar c = Calendar.getInstance();
this.callback = callback;
year = options.hasKey("year") ? options.getInt("year") : c.get(Calendar.YEAR);
month = options.hasKey("month") ? options.getInt("month") : c.get(Calendar.MONTH);
day = options.hasKey("day") ? options.getInt("day") : c.get(Calendar.DAY_OF_MONTH);
}
private NavBarStyle(ReadableMap rp) {
ReadableMap menuIcon = rp.hasKey(MENU_ICON) ? rp.getMap(MENU_ICON) : null;
this.titleTextColor = rp.hasKey(TITLE_TEXT_COLOR) && !rp.isNull(TITLE_TEXT_COLOR) ? rp.getInt(TITLE_TEXT_COLOR) : null;
this.subtitleTextColor = rp.hasKey(SUBTITLE_TEXT_COLOR) && !rp.isNull(SUBTITLE_TEXT_COLOR) ? rp.getInt(SUBTITLE_TEXT_COLOR) : null;
this.barTintColor = rp.hasKey(BAR_TINT_COLOR) && !rp.isNull(BAR_TINT_COLOR) ? rp.getInt(BAR_TINT_COLOR) : null;
this.menuIcon = menuIcon != null ? Arguments.toBundle(menuIcon) : null;
}