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; }
public static void addToGalleryAndNotify(Context context, File imageFile, final Promise promise) { final WritableMap response = new WritableNativeMap(); response.putString("path", Uri.fromFile(imageFile).toString()); // borrowed from react-native CameraRollManager, it finds and returns the 'internal' // representation of the image uri that was just saved. // e.g. content://media/external/images/media/123 MediaScannerConnection.scanFile( context, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { promise.resolve(response); } }); }
@ReactMethod public void getSessionInfo(final Promise callback) { Taplytics.getSessionInfo(new SessionInfoRetrievedListener() { @Override public void sessionInfoRetrieved(HashMap hashMap) { WritableMap resultData = new WritableNativeMap(); if(hashMap.containsKey("session_id")){ resultData.putString("session_id", (String) hashMap.get("session_id")); } if(hashMap.containsKey("appUser_id")){ resultData.putString("appUser_id", (String) hashMap.get("appUser_id")); } callback.resolve(resultData); } }); }
public WritableMap checkDownloadStatus(long downloadId) { DownloadManager.Query downloadQuery = new DownloadManager.Query(); downloadQuery.setFilterById(downloadId); Cursor cursor = downloadManager.query(downloadQuery); HashMap<String, String> result = new HashMap<>(); if (cursor.moveToFirst()) { result = getDownloadStatus(cursor, downloadId); } else { result.put("status", "UNKNOWN"); result.put("reason", "COULD_NOT_FIND"); result.put("downloadId", String.valueOf(downloadId)); } WritableMap wmap = new WritableNativeMap(); for (HashMap.Entry<String, String> entry : result.entrySet()) { wmap.putString(entry.getKey(), entry.getValue()); } return wmap; }
/** * Checks download progress. */ private void checkProgress() { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(enqueue); Cursor cursor = dm.query(query); if (!cursor.moveToFirst()) { cursor.close(); return; } long reference = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); int progress = (int) ((bytes_downloaded * 100l) / bytes_total); WritableMap writableMap = new WritableNativeMap(); writableMap.putInt("progress", progress); sendEvent(writableMap); if(progress >= 100) { future.cancel(true); } }
private void resolveImage(final File imageFile, int width, int height, final Promise promise, boolean addToMediaStore) { final WritableMap response = new WritableNativeMap(); response.putString("path", Uri.fromFile(imageFile).toString()); response.putInt("width", width); response.putInt("height", height); if(addToMediaStore) { // borrowed from react-native CameraRollManager, it finds and returns the 'internal' // representation of the image uri that was just saved. // e.g. content://media/external/images/media/123 MediaScannerConnection.scanFile( _reactContext, new String[]{imageFile.getAbsolutePath()}, null, null); } promise.resolve(response); }
@ReactMethod public void auth(Promise promise) { if (HSinterface == null){ promise.reject("-1", "init failed"); return; } int ret = HSinterface.Authenticate(); WritableMap result = new WritableNativeMap(); if (ret == 1){ result.putString("code", ret+""); result.putString("msg", "success"); promise.resolve(result); }else if (ret == 2){ result.putString("code", ret+""); result.putString("msg", "auth failed"); promise.resolve(result); }else if (ret == 0){ promise.reject("0", "connect failed"); } }
@Override public boolean onException( Exception e, GlideUrl uri, Target<GlideDrawable> target, boolean isFirstResource ) { OkHttpProgressGlideModule.forget(uri.toStringUrl()); if (!(target instanceof ImageViewTarget)) { return false; } ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView(); ThemedReactContext context = (ThemedReactContext) view.getContext(); RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class); int viewId = view.getId(); eventEmitter.receiveEvent(viewId, REACT_ON_ERROR_EVENT, new WritableNativeMap()); eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap()); return false; }
@Override public boolean onResourceReady( GlideDrawable resource, GlideUrl uri, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource ) { if (!(target instanceof ImageViewTarget)) { return false; } ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView(); ThemedReactContext context = (ThemedReactContext) view.getContext(); RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class); int viewId = view.getId(); eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_EVENT, new WritableNativeMap()); eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap()); return false; }
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; }
@Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); boolean active = false; switch (state) { case BluetoothAdapter.STATE_OFF: active = false; break; case BluetoothAdapter.STATE_ON: active = true; break; } final WritableMap eventMap = new WritableNativeMap(); eventMap.putString(EVENT_TYPE, "bluetooth"); eventMap.putBoolean(EVENT_STATUS, active); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(RN_CONNECTIVITY_STATUS_TOPIC, eventMap); } }
private void attachMeasuredRootViewToInstance( ReactRootView rootView, CatalystInstance catalystInstance) { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachMeasuredRootViewToInstance"); UiThreadUtil.assertOnUiThread(); // Reset view content as it's going to be populated by the application content from JS rootView.removeAllViews(); rootView.setId(View.NO_ID); UIManagerModule uiManagerModule = catalystInstance.getNativeModule(UIManagerModule.class); int rootTag = uiManagerModule.addMeasuredRootView(rootView); rootView.setRootViewTag(rootTag); @Nullable Bundle launchOptions = rootView.getLaunchOptions(); WritableMap initialProps = Arguments.makeNativeMap(launchOptions); String jsAppModuleName = rootView.getJSModuleName(); WritableNativeMap appParams = new WritableNativeMap(); appParams.putDouble("rootTag", rootTag); appParams.putMap("initialProps", initialProps); catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); rootView.onAttachedToReactInstance(); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); }
private static void addEntry(WritableNativeMap nativeMap, String key, Object value) { value = makeNativeObject(value); if (value == null) { nativeMap.putNull(key); } else if (value instanceof Boolean) { nativeMap.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { nativeMap.putInt(key, (Integer) value); } else if (value instanceof Number) { nativeMap.putDouble(key, ((Number) value).doubleValue()); } else if (value instanceof String) { nativeMap.putString(key, (String) value); } else if (value instanceof WritableNativeArray) { nativeMap.putArray(key, (WritableNativeArray) value); } else if (value instanceof WritableNativeMap) { nativeMap.putMap(key, (WritableNativeMap) value); } else { throw new IllegalArgumentException("Could not convert " + value.getClass()); } }
public void testShowBasicShareDialog() { final WritableMap content = new WritableNativeMap(); content.putString("message", "Hello, ReactNative!"); final WritableMap options = new WritableNativeMap(); IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CHOOSER); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); ActivityMonitor monitor = getInstrumentation().addMonitor(intentFilter, null, true); getTestModule().showShareDialog(content, options); waitForBridgeAndUIIdle(); getInstrumentation().waitForIdleSync(); assertEquals(1, monitor.getHits()); assertEquals(1, mRecordingModule.getOpened()); assertEquals(0, mRecordingModule.getErrors()); }
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]); }
public void testMapWithArrays() { WritableNativeMap map = new WritableNativeMap(); WritableNativeArray a1 = new WritableNativeArray(); WritableNativeArray a2 = new WritableNativeArray(); a1.pushDouble(3); a1.pushDouble(1); a1.pushDouble(4); a2.pushDouble(1); a2.pushDouble(9); map.putArray("array1", a1); map.putArray("array2", a2); mInstance.getJSModule(TestJavaToJSArgumentsModule.class).receiveMapWithArrays(map); waitForBridgeAndUIIdle(); mAssertModule.verifyAssertsAndReset(); }
public void testMapWithNullStringValue() { WritableNativeMap map = new WritableNativeMap(); map.putString("string", null); map.putArray("array", null); map.putMap("map", null); WritableNativeArray array = new WritableNativeArray(); array.pushString(null); array.pushArray(null); array.pushMap(null); mInstance.getJSModule(TestJavaToJSArgumentsModule.class) .receiveMapAndArrayWithNullValues(map, array); waitForBridgeAndUIIdle(); mAssertModule.verifyAssertsAndReset(); }
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(); }
@DoNotStrip public NativeArray getConstants() { BaseJavaModule baseJavaModule = getModule(); ReactMarker.logMarker(GET_CONSTANTS_START, getName()); SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "Map constants") .arg("moduleName", getName()) .flush(); Map<String, Object> map = baseJavaModule.getConstants(); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "WritableNativeMap constants") .arg("moduleName", getName()) .flush(); ReactMarker.logMarker(CONVERT_CONSTANTS_START, getName()); WritableNativeMap writableNativeMap; try { writableNativeMap = Arguments.makeNativeMap(map); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } WritableNativeArray array = new WritableNativeArray(); array.pushMap(writableNativeMap); ReactMarker.logMarker(CONVERT_CONSTANTS_END); ReactMarker.logMarker(GET_CONSTANTS_END); return array; }
private void resolveImage(final File imageFile, final Promise promise, boolean addToMediaStore) { final WritableMap response = new WritableNativeMap(); response.putString("path", Uri.fromFile(imageFile).toString()); if(addToMediaStore) { // borrowed from react-native CameraRollManager, it finds and returns the 'internal' // representation of the image uri that was just saved. // e.g. content://media/external/images/media/123 MediaScannerConnection.scanFile( _reactContext, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { if (uri != null) { response.putString("mediaUri", uri.toString()); } promise.resolve(response); } }); } else { promise.resolve(response); } }
public static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException { WritableMap map = new WritableNativeMap(); Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); if (value instanceof JSONObject) { map.putMap(key, convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { map.putArray(key, convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { map.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { map.putInt(key, (Integer) value); } else if (value instanceof Double) { map.putDouble(key, (Double) value); } else if (value instanceof String) { map.putString(key, (String) value); } else { map.putString(key, value.toString()); } } return map; }
public static WritableMap convert(Output output) { WritableNativeMap shapeMap = new WritableNativeMap(); shapeMap.putInt("numDimensions", output.shape().numDimensions()); WritableNativeMap map = new WritableNativeMap(); map.putInt("index", output.index()); map.putString("dataType", output.dataType().name()); map.putMap("shape", shapeMap); return map; }
public static WritableMap jsonToWritableMap(JSONObject jsonObject) { WritableMap writableMap = new WritableNativeMap(); if (jsonObject == null) { return null; } Iterator<String> iterator = jsonObject.keys(); if (!iterator.hasNext()) { return null; } try { while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); if (value == null) { writableMap.putNull(key); } else if (value instanceof Boolean) { writableMap.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { writableMap.putInt(key, (Integer) value); } else if (value instanceof Double) { writableMap.putDouble(key, (Double) value); } else if (value instanceof String) { writableMap.putString(key, (String) value); } else if (value instanceof JSONObject) { writableMap.putMap(key, jsonToWritableMap((JSONObject) value)); } else if (value instanceof JSONArray) { writableMap.putArray(key, jsonArrayToWritableArray((JSONArray) value)); } } } catch (JSONException ex){ // Do nothing and fail silently } return writableMap; }
@Override public void onServiceConnected(ComponentName name, IBinder service) { HSinterface = (HSInterface) service; int i = 2; while (i > 0) { i--; int ret = HSinterface.init(); if (ret == 1) { i = 0; WritableMap result = new WritableNativeMap(); String sam = HSinterface.GetSAM(); result.putString("code", "1"); result.putString("sam", sam); mPromise.resolve(result); return; } else { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); mPromise.reject("0", "connect failed"); } continue; } } mPromise.reject("0", "connect failed"); }
@Override public void onProgress(String key, long bytesRead, long expectedLength) { List<ImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key); if (viewsForKey != null) { for (ImageViewWithUrl view: viewsForKey) { WritableMap event = new WritableNativeMap(); event.putInt("loaded", (int) bytesRead); event.putInt("total", (int) expectedLength); ThemedReactContext context = (ThemedReactContext) view.getContext(); RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class); int viewId = view.getId(); eventEmitter.receiveEvent(viewId, REACT_ON_PROGRESS_EVENT, event); } } }
@Override public void onEventCallback(final String name, final ReadableMap info, final MSREventBridgeReceiverCallback callback) { Log.d(ReactConstants.TAG, this.getClass().getName() + ": Received event with callback: ".concat(name)); final String activityClassName = this.getClass().getSimpleName(); // Example how to load some async data if (name.equals(LoadDataEventName)) { final int count = info.getInt("count"); // Simulate some data loading delay final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { WritableArray array = new WritableNativeArray(); for (int i = 0; i < count; i++) { array.pushString("Row " + i + " - " + activityClassName); } callback.onSuccess(array); } }, 2000); return; } // Emit callback WritableMap map = new WritableNativeMap(); map.putString("key", "value"); callback.onSuccess(map); }
@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); }
@ReactMethod public void getRangedRegions(Callback callback) { WritableArray array = new WritableNativeArray(); for (Region region: mBeaconManager.getRangedRegions()) { WritableMap map = new WritableNativeMap(); map.putString("region", region.getUniqueId()); map.putString("uuid", region.getId1().toString()); array.pushMap(map); } callback.invoke(array); }
private WritableMap createMonitoringResponse(Region region) { 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); return map; }
@Override public void onReceive(Context context, Intent intent) { final boolean locationEnabled = intent.getAction() != null && intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION) && checkLocation(); final WritableMap eventMap = new WritableNativeMap(); eventMap.putString(EVENT_TYPE, "location"); eventMap.putBoolean(EVENT_STATUS, locationEnabled); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(RN_CONNECTIVITY_STATUS_TOPIC, eventMap); }
@Override public void onTimeSet(TimePicker view, int hour, int minute) { if (!mPromiseResolved && getReactApplicationContext().hasActiveCatalystInstance()) { WritableMap result = new WritableNativeMap(); result.putString("action", ACTION_TIME_SET); result.putInt("hour", hour); result.putInt("minute", minute); mPromise.resolve(result); mPromiseResolved = true; } }
@Override public void onDismiss(DialogInterface dialog) { if (!mPromiseResolved && getReactApplicationContext().hasActiveCatalystInstance()) { WritableMap result = new WritableNativeMap(); result.putString("action", ACTION_DISMISSED); mPromise.resolve(result); mPromiseResolved = true; } }
private static void putPageInfo(Cursor photos, WritableMap response, int limit) { WritableMap pageInfo = new WritableNativeMap(); pageInfo.putBoolean("has_next_page", limit < photos.getCount()); if (limit < photos.getCount()) { photos.moveToPosition(limit - 1); pageInfo.putString( "end_cursor", photos.getString(photos.getColumnIndex(Images.Media.DATE_TAKEN))); } response.putMap("page_info", pageInfo); }
private static void putEdges( ContentResolver resolver, Cursor photos, WritableMap response, int limit) { WritableArray edges = new WritableNativeArray(); photos.moveToFirst(); int idIndex = photos.getColumnIndex(Images.Media._ID); int mimeTypeIndex = photos.getColumnIndex(Images.Media.MIME_TYPE); int groupNameIndex = photos.getColumnIndex(Images.Media.BUCKET_DISPLAY_NAME); int dateTakenIndex = photos.getColumnIndex(Images.Media.DATE_TAKEN); int widthIndex = IS_JELLY_BEAN_OR_LATER ? photos.getColumnIndex(Images.Media.WIDTH) : -1; int heightIndex = IS_JELLY_BEAN_OR_LATER ? photos.getColumnIndex(Images.Media.HEIGHT) : -1; int longitudeIndex = photos.getColumnIndex(Images.Media.LONGITUDE); int latitudeIndex = photos.getColumnIndex(Images.Media.LATITUDE); for (int i = 0; i < limit && !photos.isAfterLast(); i++) { WritableMap edge = new WritableNativeMap(); WritableMap node = new WritableNativeMap(); boolean imageInfoSuccess = putImageInfo(resolver, photos, node, idIndex, widthIndex, heightIndex); if (imageInfoSuccess) { putBasicNodeInfo(photos, node, mimeTypeIndex, groupNameIndex, dateTakenIndex); putLocationInfo(photos, node, longitudeIndex, latitudeIndex); edge.putMap("node", node); edges.pushMap(edge); } else { // we skipped an image because we couldn't get its details (e.g. width/height), so we // decrement i in order to correctly reach the limit, if the cursor has enough rows i--; } photos.moveToNext(); } response.putArray("edges", edges); }