@SuppressWarnings("deprecation") public WritableMap getCameraInfo(int index) { CameraInfo info = new CameraInfo(); Size size = null; try { Camera.getCameraInfo(index, info); Camera camera = Camera.open(index); size = getMaxSupportedVideoSize(camera); camera.release(); } catch (Exception var3) { Logging.e("CameraEnumerationAndroid", "getCameraInfo failed on index " + index, var3); return null; } WritableMap params = Arguments.createMap(); String facing = info.facing == 1 ? "front" : "back"; params.putString("label", "Camera " + index + ", Facing " + facing + ", Orientation " + info.orientation); params.putString("id", "" + index); params.putString("facing", facing); params.putString("kind", "video"); params.putString("maxWidth", String.valueOf(size.width)); params.putString("maxHeight", String.valueOf(size.height)); return params; }
@Override public boolean onInfo(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_STALLED.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: mEventEmitter.receiveEvent(getId(), Events.EVENT_RESUME.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_READY_FOR_DISPLAY.toString(), Arguments.createMap()); break; default: } return false; }
@ReactMethod public void queryCache(final ReadableArray uris, final Promise promise) { // perform cache interrogation in async task as disk cache checks are expensive new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { WritableMap result = Arguments.createMap(); ImagePipeline imagePipeline = Fresco.getImagePipeline(); for (int i = 0; i < uris.size(); i++) { String uriString = uris.getString(i); final Uri uri = Uri.parse(uriString); if (imagePipeline.isInBitmapMemoryCache(uri)) { result.putString(uriString, "memory"); } else if (imagePipeline.isInDiskCacheSync(uri)) { result.putString(uriString, "disk"); } } promise.resolve(result); } }.executeOnExecutor(GuardedAsyncTask.THREAD_POOL_EXECUTOR); }
@ReactMethod public void getEnginesInfo(Promise promise) { if(notReady(promise)) return; try { WritableArray ttsInfo = Arguments.createArray(); List<TextToSpeech.EngineInfo> engineList = tts.getEngines(); Iterator iterator = engineList.iterator(); while(iterator.hasNext()) { ttsInfo.pushString(iterator.next().toString()); } promise.resolve(ttsInfo); } catch(Exception e) { promise.reject("error", "Unable to retrieve TTS Engine info for getEnginesInfo()", e); } }
private void handleError() { LogUtils.d(TAG, "handleError"); if(tweetView != null) { tweetView.setVisibility(View.INVISIBLE); } WritableMap evt = Arguments.createMap(); evt.putString("message", "Could not load tweet"); ReactContext ctx = (ReactContext) getContext(); ctx.getJSModule(RCTEventEmitter.class).receiveEvent( getId(), "onLoadError", evt); }
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; }
private void listenVolume(final ReactApplicationContext reactContext) { volumeBR = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) { WritableMap para = Arguments.createMap(); para.putDouble("value", getNormalizationVolume(VOL_MUSIC)); para.putDouble(VOL_VOICE_CALL, getNormalizationVolume(VOL_VOICE_CALL)); para.putDouble(VOL_SYSTEM, getNormalizationVolume(VOL_SYSTEM)); para.putDouble(VOL_RING, getNormalizationVolume(VOL_RING)); para.putDouble(VOL_MUSIC, getNormalizationVolume(VOL_MUSIC)); para.putDouble(VOL_ALARM, getNormalizationVolume(VOL_ALARM)); para.putDouble(VOL_NOTIFICATION, getNormalizationVolume(VOL_NOTIFICATION)); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("EventVolume", para); } } }; filter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION"); reactContext.registerReceiver(volumeBR, filter); }
private void checkForKeyboardEvents() { getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea); final int heightDiff = DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; if (mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected) { // keyboard is now showing, or the keyboard height has changed mKeyboardHeight = heightDiff; WritableMap params = Arguments.createMap(); WritableMap coordinates = Arguments.createMap(); coordinates.putDouble("screenY", PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom)); coordinates.putDouble("screenX", PixelUtil.toDIPFromPixel(mVisibleViewArea.left)); coordinates.putDouble("width", PixelUtil.toDIPFromPixel(mVisibleViewArea.width())); coordinates.putDouble("height", PixelUtil.toDIPFromPixel(mKeyboardHeight)); params.putMap("endCoordinates", coordinates); sendEvent("keyboardDidShow", params); } else if (mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected) { // keyboard is now hidden mKeyboardHeight = 0; sendEvent("keyboardDidHide", null); } }
@ReactMethod public void _newAsyncObject(final String name, String defaultValue) { try { JSONObject object = new JSONObject(defaultValue); TaplyticsVar var = new TaplyticsVar<>(name, object, new TaplyticsVarListener() { @Override public void variableUpdated(Object o) { WritableMap params = Arguments.createMap(); params.putString("value", ((JSONObject) o).toString()); sendEvent(name, params); } }); } catch (JSONException e) { Log.e(tagName, e.getMessage()); } }
private WritableMap getIntentData(Intent intent) { WritableMap data = Arguments.createMap(); JSONObject dataObject = new JSONObject(); try { if (intent.hasExtra("tl_id")) { dataObject.put("tl_id", intent.getExtras().getString("tl_id")); } if (intent.hasExtra("custom_keys")) { dataObject.put("custom_keys", new JSONObject(intent.getExtras().getString("custom_keys"))); } } catch (Throwable ignored) { //Ignore the bad JSON for now. Log here as you please. } data.putString("value", dataObject.toString()); return data; }
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); } } }
@ReactMethod public void startListeningToAnimatedNodeValue(final int tag) { final AnimatedNodeValueListener listener = new AnimatedNodeValueListener() { public void onValueUpdate(double value) { WritableMap onAnimatedValueData = Arguments.createMap(); onAnimatedValueData.putInt("tag", tag); onAnimatedValueData.putDouble("value", value); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("onAnimatedValueUpdate", onAnimatedValueData); } }; mOperations.add(new UIThreadOperation() { @Override public void execute(NativeAnimatedNodesManager animatedNodesManager) { animatedNodesManager.startListeningToAnimatedNodeValue(tag, listener); } }); }
private void sendResponse(String status, String message, Promise promise) { Reprint.cancelAuthentication(); response = Arguments.createMap(); response.putString("status", status); response.putString("error", message); promise.resolve(response); }
@ReactMethod public void scheduleLocalNotification(ReadableMap details) { Bundle bundle = Arguments.toBundle(details); // If notification ID is not provided by the user, generate one at random if (bundle.getString("id") == null) { bundle.putString("id", String.valueOf(mRandomNumberGenerator.nextInt())); } mRNPushNotificationHelper.sendNotificationScheduled(bundle); }
@Override public void onEvent(int eventType, Bundle params) { Logger.debug(TAG, "onEvent: " + eventType); WritableMap data = Arguments.createMap(); data.putInt("eventType", eventType); data.putMap("params", Arguments.fromBundle(params)); emit(SPEECH_TO_TEXT, data); }
public ReactVideoView(ThemedReactContext themedReactContext) { super(themedReactContext); mThemedReactContext = themedReactContext; mEventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class); themedReactContext.addLifecycleEventListener(this); initializeMediaPlayerIfNeeded(); setSurfaceTextureListener(this); mProgressUpdateRunnable = new Runnable() { @Override public void run() { if (mMediaPlayerValid && !isCompleted &&!mPaused) { WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_CURRENT_TIME, mMediaPlayer.getCurrentPosition() / 1000.0); event.putDouble(EVENT_PROP_PLAYABLE_DURATION, mVideoBufferedDuration / 1000.0); //TODO:mBufferUpdateRunnable mEventEmitter.receiveEvent(getId(), Events.EVENT_PROGRESS.toString(), event); // Check for update after an interval // TODO: The update interval is fixed at 250. There is a property in React component that defines this value. Totally ignored !!! mProgressUpdateHandler.postDelayed(mProgressUpdateRunnable, 250); } } }; }
@Override public void onReceive(Context context, Intent intent) { WritableMap params = Arguments.createMap(); switch(intent.getAction()) { case "update-position-event": int nCurrentPosition = intent.getIntExtra("currentPosition", 0); params.putInt("currentPosition", nCurrentPosition); sendEvent("onPlaybackPositionUpdated", params); break; case "change-playback-action-event": String strAction = intent.getStringExtra("action"); params.putString("action", strAction); sendEvent("onPlaybackActionChanged", params); break; case "change-playback-state-event": int nState = intent.getIntExtra("state", 0); if (mStateMap.containsKey(nState)) { params.putString("state", mStateMap.get(nState)); sendEvent("onPlaybackStateChanged", params); } break; case "playback-error-event": String strError = intent.getStringExtra("msg"); params.putString("msg", strError); sendEvent("onPlaybackError", params); default: break; } }
public static void onRequestError( RCTDeviceEventEmitter eventEmitter, int requestId, String error, IOException e) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushString(error); if ((e != null) && (e.getClass() == SocketTimeoutException.class)) { args.pushBoolean(true); // last argument is a time out boolean } eventEmitter.emit("didCompleteNetworkResponse", args); }
public static void onRequestSuccess(RCTDeviceEventEmitter eventEmitter, int requestId) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushNull(); eventEmitter.emit("didCompleteNetworkResponse", args); }
/** * Post an event to all event subscriber for the given name * Example: MSREventBridgeModule.emitEventContext(getApplicationContext(), "eventName", data); */ static public void emitEventContext(Context context, final String name, @Nullable WritableMap info) { Bundle bundle = new Bundle(); bundle.putString(EventBridgeModuleEventNameKey, name); if (info != null) { bundle.putBundle(EventBridgeModuleEventInfoKey, Arguments.toBundle(info)); } LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context); Intent customEvent= new Intent(EventBridgeModuleIntentEventName); customEvent.putExtra(EventBridgeModuleIntentEventDataKey, bundle); localBroadcastManager.sendBroadcast(customEvent); }
private void registerNotificationsRegistration() { IntentFilter intentFilter = new IntentFilter(getReactApplicationContext().getPackageName() + ".RNPushNotificationRegisteredToken"); getReactApplicationContext().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String token = intent.getStringExtra("token"); WritableMap params = Arguments.createMap(); params.putString("deviceToken", token); mJsDelivery.sendEvent("remoteNotificationsRegistered", params); } }, intentFilter); }
@Override public void onSignalingChange(PeerConnection.SignalingState signalingState) { WritableMap params = Arguments.createMap(); params.putInt("id", id); params.putString("signalingState", signalingStateString(signalingState)); webRTCModule.sendEvent("peerConnectionSignalingStateChanged", params); }
@Deprecated public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (mHelper == null) return; // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, intent)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... WritableMap params = Arguments.createMap(); params.putString("Warning","you need to use your activity to perfom billing"); sendEvent(TAG, params); } }
private WritableMap serializeEventData() { WritableMap eventData = Arguments.createMap(); eventData.putInt("target", getViewTag()); eventData.putDouble("value", getValue()); eventData.putBoolean("fromUser", isFromUser()); return eventData; }
public static WritableArray Members(ArrayList<Member> members) { WritableArray array = Arguments.createArray(); for (Member m : members) { array.pushMap(Member(m)); } return array; }
@Override public void loadComplete(int pageCount) { WritableMap event = Arguments.createMap(); event.putString("message", String.valueOf(pageCount)); ReactContext reactContext = (ReactContext) this.getContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent( this.getId(), "topChange", event ); }
@Override public void phoneDataConnectionStateUpdated(int direction) { WritableMap map = Arguments.createMap(); map.putInt("direction", direction); WritableMap result = Arguments.createMap(); result.putString("type", "LISTEN_DATA_CONNECTION_STATE"); result.putMap("data", map); sendEvent(PHONE_STATE_LISTENER, result); }
@ReactMethod public void getScheduledAlarms(Promise promise) { ArrayList<Bundle> bundles = anHelper.getScheduledAlarms(); WritableArray array = Arguments.createArray(); for(Bundle bundle:bundles){ array.pushMap(Arguments.fromBundle(bundle)); } promise.resolve(array); }
private WritableMap createWebViewEvent(WebView webView, String url) { WritableMap event = Arguments.createMap(); event.putDouble("target", webView.getId()); // Don't use webView.getUrl() here, the URL isn't updated to the new value yet in callbacks // like onPageFinished event.putString("url", url); event.putBoolean("loading", !mLastLoadFailed && webView.getProgress() != 100); event.putString("title", webView.getTitle()); event.putBoolean("canGoBack", webView.canGoBack()); event.putBoolean("canGoForward", webView.canGoForward()); return event; }
@ReactMethod public void download(final ReadableMap params, Callback callback){ // 获取参数 String url = params.hasKey("url") ? params.getString("url") : null; String description = params.hasKey("description") ? params.getString("description") : "downloading"; // 判断是否未回调继续调用 if(rctCallback!=null){ WritableMap map = Arguments.createMap(); map.putInt("status", -2); map.putString("description", "busy"); map.putString("url",url); callback.invoke(map); return; } rctCallback = callback; rctParams = params; // 设置参数 DownloadManager.Request request = new Request(Uri.parse(url)); request.setAllowedNetworkTypes(Request.NETWORK_WIFI); request.setNotificationVisibility(Request.VISIBILITY_VISIBLE); // 是否通知 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); request.setMimeType(mimeString); // 下载的文件类型 request.setTitle("下载"); // 通知栏的标题 request.setDescription(description); // 通知栏描述 request.setAllowedOverRoaming(false); //漫游网络是否可以下载 request.setAllowedOverMetered(false); request.setVisibleInDownloadsUi(true); //设置文件存放目录 request.setDestinationInExternalFilesDir(mApplicationContext, Environment.DIRECTORY_DOWNLOADS, description); mTaskId = downloadManager.enqueue(request); //注册广播接收者,监听下载状态 mApplicationContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }
private void handleIOException(IOException e) { //debug log Log.e(eTag, "Server IOException", e); //emit event String message = e.getMessage(); WritableMap eventParams = Arguments.createMap(); eventParams.putString("error", message); if (message.equals("Socket closed")) { sendEvent(mReactContext, event_closed, eventParams); isOpen = false; } else { sendEvent(mReactContext, event_error, eventParams); } }
@Override public void onRmsChanged(float rmsdB) { Logger.debug(TAG, "onRmsChanged: " + rmsdB); WritableMap data = Arguments.createMap(); data.putDouble("rmsdB", rmsdB); emit(SPEECH_TO_TEXT, data); }
@Override public void onError(AccessManager twilioAccessManager, String s) { WritableMap params = Arguments.createMap(); params.putString("error",s); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("accessManager:tokenInvalid",params); }
public static void onDataReceived( RCTDeviceEventEmitter eventEmitter, int requestId, String data) { WritableArray args = Arguments.createArray(); args.pushInt(requestId); args.pushString(data); eventEmitter.emit("didReceiveNetworkData", args); }
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; }
@Override public void phoneDataActivityUpdated(int direction) { WritableMap map = Arguments.createMap(); map.putInt("direction", direction); WritableMap result = Arguments.createMap(); result.putString("type", "LISTEN_DATA_ACTIVITY"); result.putMap("data", map); sendEvent(PHONE_STATE_LISTENER, result); }
private void onSaveSketch(SketchViewContainer root, SketchFile sketchFile) { WritableMap event = Arguments.createMap(); event.putString("localFilePath", sketchFile.localFilePath); event.putInt("imageWidth", sketchFile.width); event.putInt("imageHeight", sketchFile.height); sendEvent(root, "onSaveSketch", event); }
private void sendEvent(View view, String eventType, WritableMap event) { WritableMap nativeEvent = Arguments.createMap(); nativeEvent.putString("type", eventType); nativeEvent.putMap("event", event); ReactContext reactContext = (ReactContext) view.getContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(view.getId(), "topChange", nativeEvent); }
private void sendEvent(String status, String message) { WritableMap params = Arguments.createMap(); params.putString("status", status); params.putString("message", message); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("FINGERPRINT_IDENTIFY_STATUS", params); }
@Override public void onToastNotification(String channelSid, String messageSid) { WritableMap map = Arguments.createMap(); map.putString("channelSid", channelSid); map.putString("messageSid", messageSid); sendEvent("chatClient:toastReceived", map); }