/** * Install update if any available. * * @param jsCallback callback where to send the result; * used, when installation os requested manually from JavaScript */ private void installUpdate(CallbackContext jsCallback) { if (!isPluginReadyForWork) { return; } ChcpError error = UpdatesInstaller.install(cordova.getActivity(), pluginInternalPrefs.getReadyForInstallationReleaseVersionName(), pluginInternalPrefs.getCurrentReleaseVersionName()); if (error != ChcpError.NONE) { if (jsCallback != null) { PluginResult errorResult = PluginResultHelper.createPluginResult(UpdateInstallationErrorEvent.EVENT_NAME, null, error); jsCallback.sendPluginResult(errorResult); } return; } if (jsCallback != null) { installJsCallback = jsCallback; } }
/** * Initialize default callback, received from the web side. * * @param callback callback to use for events broadcasting */ private void jsInit(CallbackContext callback) { jsDefaultCallback = callback; dispatchDefaultCallbackStoredResults(); // Clear web history. // In some cases this is necessary, because on the launch we redirect user to the // external storage. And if he presses back button - browser will lead him back to // assets folder, which we don't want. handler.post(new Runnable() { @Override public void run() { webView.clearHistory(); } }); // fetch update when we are initialized if (chcpXmlConfig.isAutoDownloadIsAllowed() && !UpdatesInstaller.isInstalling() && !UpdatesLoader.isExecuting()) { fetchUpdate(); } }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("hide")) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.postMessage("splashscreen", "hide"); } }); } else if (action.equals("show")) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.postMessage("splashscreen", "show"); } }); } else { return false; } callbackContext.success(); return true; }
private void getIdToken(final boolean forceRefresh, final CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { callbackContext.error("User is not authorized"); } else { user.getIdToken(forceRefresh) .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(Task<GetTokenResult> task) { if (task.isSuccessful()) { callbackContext.success(task.getResult().getToken()); } else { callbackContext.error(task.getException().getMessage()); } } }); } } }); }
@Override public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) throws JSONException { if (methodList.contains(action)) { threadPool.execute(new Runnable() { @Override public void run() { try { Method method = NXTPushPlugin.class.getDeclaredMethod(action, JSONArray.class, CallbackContext.class); method.invoke(NXTPushPlugin.this, data, callbackContext); } catch (Exception e) { Log.e(TAG, e.toString()); } } }); } return true; }
public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) { this.destType = state.getInt("destType"); this.srcType = state.getInt("srcType"); this.mQuality = state.getInt("mQuality"); this.targetWidth = state.getInt("targetWidth"); this.targetHeight = state.getInt("targetHeight"); this.encodingType = state.getInt("encodingType"); this.mediaType = state.getInt("mediaType"); this.numPics = state.getInt("numPics"); this.allowEdit = state.getBoolean("allowEdit"); this.correctOrientation = state.getBoolean("correctOrientation"); this.saveToPhotoAlbum = state.getBoolean("saveToPhotoAlbum"); if (state.containsKey("croppedUri")) { this.croppedUri = Uri.parse(state.getString("croppedUri")); } if (state.containsKey("imageUri")) { //I have no idea what type of URI is being passed in this.imageUri = new CordovaUri(Uri.parse(state.getString("imageUri"))); } this.callbackContext = callbackContext; }
private boolean hideCamera(CallbackContext callbackContext) { if(this.hasView(callbackContext) == false){ return true; } FragmentManager fragmentManager = cordova.getActivity().getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.hide(fragment); fragmentTransaction.commit(); callbackContext.success(); return true; }
/** * Check if new version was loaded and can be installed. * * @param callback callback where to send the result */ private void jsIsUpdateAvailableForInstallation(final CallbackContext callback) { Map<String, Object> data = null; ChcpError error = null; final String readyForInstallationVersionName = pluginInternalPrefs.getReadyForInstallationReleaseVersionName(); if (!TextUtils.isEmpty(readyForInstallationVersionName)) { data = new HashMap<String, Object>(); data.put("readyToInstallVersion", readyForInstallationVersionName); data.put("currentVersion", pluginInternalPrefs.getCurrentReleaseVersionName()); } else { error = ChcpError.NOTHING_TO_INSTALL; } PluginResult pluginResult = PluginResultHelper.createPluginResult(null, data, error); callback.sendPluginResult(pluginResult); }
private void deleteApp(final CallbackContext callbackContext, final String appName) { if (!appAuth.containsKey(appName)) { callbackContext.error("There is no app named " + appName); return; } try { final AuthComponent authComponent = appAuth.get(appName); authComponent.reset(); appAuth.remove(appName); final DatabaseComponent databaseComponent = appDatabase.get(appName); databaseComponent.reset(); appDatabase.remove(appName); } catch (Exception e) { callbackContext.error(e.getMessage()); } }
private void initializeComponentsWithApp(final CallbackContext callbackContext, final String appName, final FirebaseApp firebaseApp) { final Firebase self = this; final Bundle extras = this.cordova.getActivity().getIntent().getExtras(); this.cordova.getThreadPool().execute(new Runnable() { public void run() { Log.i(TAG, "Initializing plugin components for " + appName); if (appName.equals("[DEFAULT]")) { mAnalyticsComponent.initialize(context); MessagingComponent.initialize(extras); } appAuth.put(appName, new AuthComponent(self, firebaseApp)); appDatabase.put(appName, new DatabaseComponent(self, firebaseApp)); callbackContext.success(); } }); }
private void sendEvent(String type, String msg) { JSONObject response = new JSONObject(); try { response.put("type", type); response.put("message", msg); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, response); pluginResult.setKeepCallback(true); CallbackContext pushCallback = getCurrentCallbackContext(); if (pushCallback != null) { pushCallback.sendPluginResult(pluginResult); } } catch (JSONException e) { sendError(e.getMessage()); } }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if ("update".equals(action)) { update(args.getLong(0), callbackContext); } else if ("getBoolean".equals(action)) { getBoolean(args.getString(0), args.getString(1), callbackContext); } else if ("getBytes".equals(action)) { getBytes(args.getString(0), args.getString(1), callbackContext); } else if ("getNumber".equals(action)) { getNumber(args.getString(0), args.getString(1), callbackContext); } else if ("getString".equals(action)) { getString(args.getString(0), args.getString(1), callbackContext); } else { return false; } return true; }
public void removeListeners(final CallbackContext callbackContext, final JSONArray listenerIDs) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { int size = listenerIDs.length(); Log.i(TAG, "Removing " + size + "listeners"); for (int i = 0; i < size; i++) { String listenerID = listenerIDs.optString(i); if (listenerID != null) { DatabaseListener listener = listeners.get(listenerID); listener.removeListener(); removeListener(listenerID); } } callbackContext.success(); } catch (Exception e) { Log.e(TAG, "Error removing listeners"); callbackContext.error(e.getMessage()); } } }); }
public void getByteArray(final CallbackContext callbackContext, final String key, final String namespace) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.i(TAG, "Getting byte array " + key); byte[] bytes = namespace == null ? FirebaseRemoteConfig.getInstance().getByteArray(key) : FirebaseRemoteConfig.getInstance().getByteArray(key, namespace); JSONObject object = new JSONObject(); object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT)); object.put("array", new JSONArray(bytes)); callbackContext.success(object); } catch (Exception e) { Log.e(TAG, "Error getting byte array " + key, e); callbackContext.error(e.getMessage()); } } }); }
public void getInfo(final CallbackContext callbackContext) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.i(TAG, "Getting info"); FirebaseRemoteConfigInfo remoteConfigInfo = FirebaseRemoteConfig.getInstance().getInfo(); JSONObject settings = new JSONObject(); settings.put("developerModeEnabled", remoteConfigInfo.getConfigSettings().isDeveloperModeEnabled()); JSONObject info = new JSONObject(); info.put("configSettings", settings); info.put("fetchTimeMillis", remoteConfigInfo.getFetchTimeMillis()); info.put("lastFetchStatus", remoteConfigInfo.getLastFetchStatus()); callbackContext.success(info); } catch (Exception e) { Log.e(TAG, "Error getting info", e); callbackContext.error(e.getMessage()); } } }); }
public NetworkLocationController( CordovaInterface cordova, CallbackContext callbackContext, long minDistance, long minTime, boolean returnCache, boolean buffer, int bufferSize ){ _cordova = cordova; _callbackContext = callbackContext; _minDistance = minDistance; _minTime = minTime; _returnCache = returnCache; _buffer = buffer; _bufferSize = bufferSize; }
@Override public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException { boolean cmdProcessed = true; if (JSAction.INIT.equals(action)) { jsInit(callbackContext); } else if (JSAction.FETCH_UPDATE.equals(action)) { jsFetchUpdate(callbackContext, args); } else if (JSAction.INSTALL_UPDATE.equals(action)) { jsInstallUpdate(callbackContext); } else if (JSAction.CONFIGURE.equals(action)) { jsSetPluginOptions(args, callbackContext); } else if (JSAction.REQUEST_APP_UPDATE.equals(action)) { jsRequestAppUpdate(args, callbackContext); } else if (JSAction.IS_UPDATE_AVAILABLE_FOR_INSTALLATION.equals(action)) { jsIsUpdateAvailableForInstallation(callbackContext); } else if (JSAction.GET_VERSION_INFO.equals(action)) { jsGetVersionInfo(callbackContext); } else { cmdProcessed = false; } return cmdProcessed; }
public void hasPermission(final CallbackContext callbackContext) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.i(TAG, "Checking permission"); Context context = mFirebase.cordova.getActivity(); NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); JSONObject object = new JSONObject(); object.put("isEnabled", areNotificationsEnabled); callbackContext.success(object); } catch (Exception e) { Log.e(TAG, "Error checking permission"); callbackContext.error(e.getMessage()); } } }); }
public void setBadgeNumber(final CallbackContext callbackContext, final int number) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.i(TAG, "Setting badge number " + number); Context context = mFirebase.cordova.getActivity(); SharedPreferences.Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); editor.putInt(KEY, number); editor.apply(); ShortcutBadger.applyCount(context, number); callbackContext.success(); } catch (Exception e) { Log.e(TAG, "Error setting badge number " + number); callbackContext.error(e.getMessage()); } } }); }
public void getBadgeNumber(final CallbackContext callbackContext) { mFirebase.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.i(TAG, "Getting badge number"); Context context = mFirebase.cordova.getActivity(); SharedPreferences settings = context.getSharedPreferences(KEY, Context.MODE_PRIVATE); int number = settings.getInt(KEY, 0); callbackContext.success(number); } catch (Exception e) { Log.e(TAG, "Error getting badge number"); callbackContext.error(e.getMessage()); } } }); }
private boolean setZoom(int zoom, CallbackContext callbackContext) { if(this.hasCamera(callbackContext) == false){ return true; } Camera camera = fragment.getCamera(); Camera.Parameters params = camera.getParameters(); if (camera.getParameters().isZoomSupported()) { params.setZoom(zoom); fragment.setCameraParameters(params); callbackContext.success(zoom); } else { callbackContext.error("Zoom not supported"); } return true; }
private boolean getSupportedFocusModes(CallbackContext callbackContext) { if(this.hasCamera(callbackContext) == false){ return true; } Camera camera = fragment.getCamera(); Camera.Parameters params = camera.getParameters(); List<String> supportedFocusModes; supportedFocusModes = params.getSupportedFocusModes(); if (supportedFocusModes != null) { JSONArray jsonFocusModes = new JSONArray(); for (int i=0; i<supportedFocusModes.size(); i++) { jsonFocusModes.put(new String(supportedFocusModes.get(i))); } callbackContext.success(jsonFocusModes); return true; } callbackContext.error("Camera focus modes parameters access error"); return true; }
private void showNotification(JSONArray arguments, CallbackContext context) { Context acontext = TwilioVoicePlugin.this.webView.getContext(); NotificationManager mNotifyMgr = (NotificationManager) acontext.getSystemService(Activity.NOTIFICATION_SERVICE); mNotifyMgr.cancelAll(); mCurrentNotificationText = arguments.optString(0); PackageManager pm = acontext.getPackageManager(); Intent notificationIntent = pm.getLaunchIntentForPackage(acontext.getPackageName()); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("notificationTag", "BVNotification"); PendingIntent pendingIntent = PendingIntent.getActivity(acontext, 0, notificationIntent, 0); int notification_icon = acontext.getResources().getIdentifier("notification", "drawable", acontext.getPackageName()); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(acontext) .setSmallIcon(notification_icon) .setContentTitle("Incoming Call") .setContentText(mCurrentNotificationText) .setContentIntent(pendingIntent); mNotifyMgr.notify(mCurrentNotificationId, mBuilder.build()); context.success(); }
public void getAppVersion(String packagename, CallbackContext callbackContext) { PackageManager packageManager = this.cordova.getActivity().getPackageManager(); try { PackageInfo info = packageManager.getPackageInfo(packagename, 0); String version = info.versionName; callbackContext.success(version); } catch (PackageManager.NameNotFoundException e) { callbackContext.error("Package not found"); } }
private boolean hasCamera(CallbackContext callbackContext) { if(this.hasView(callbackContext) == false){ return false; } if(fragment.getCamera() == null) { callbackContext.error("No Camera"); return false; } return true; }
private void removeNotifyCallback(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) { if (gatt == null) { callbackContext.error("BluetoothGatt is null"); return; } BluetoothGattService service = gatt.getService(serviceUUID); BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID); String key = generateHashKey(serviceUUID, characteristic); if (characteristic != null) { notificationCallbacks.remove(key); if (gatt.setCharacteristicNotification(characteristic, false)) { BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID); if (descriptor != null) { descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(descriptor); } callbackContext.success(); } else { // TODO we can probably ignore and return success anyway since we removed the notification callback callbackContext.error("Failed to stop notification for " + characteristicUUID); } } else { callbackContext.error("Characteristic " + characteristicUUID + " not found"); } commandCompleted(); }
private void readCharacteristic(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) { boolean success = false; if (gatt == null) { callbackContext.error("BluetoothGatt is null"); return; } BluetoothGattService service = gatt.getService(serviceUUID); BluetoothGattCharacteristic characteristic = findReadableCharacteristic(service, characteristicUUID); if (characteristic == null) { callbackContext.error("Characteristic " + characteristicUUID + " not found."); } else { readCallback = callbackContext; if (gatt.readCharacteristic(characteristic)) { success = true; } else { readCallback = null; callbackContext.error("Read failed"); } } if (!success) { commandCompleted(); } }
private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONArray args = new JSONArray(rawArgs); f.run(args); } catch ( Exception e) { if( e instanceof EncodingException){ callbackContext.error(FileUtils.ENCODING_ERR); } else if(e instanceof FileNotFoundException) { callbackContext.error(FileUtils.NOT_FOUND_ERR); } else if(e instanceof FileExistsException) { callbackContext.error(FileUtils.PATH_EXISTS_ERR); } else if(e instanceof NoModificationAllowedException ) { callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); } else if(e instanceof InvalidModificationException ) { callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); } else if(e instanceof MalformedURLException ) { callbackContext.error(FileUtils.ENCODING_ERR); } else if(e instanceof IOException ) { callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); } else if(e instanceof EncodingException ) { callbackContext.error(FileUtils.ENCODING_ERR); } else if(e instanceof TypeMismatchException ) { callbackContext.error(FileUtils.TYPE_MISMATCH_ERR); } else if(e instanceof JSONException ) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } else if (e instanceof SecurityException) { callbackContext.error(FileUtils.SECURITY_ERR); } else { e.printStackTrace(); callbackContext.error(FileUtils.UNKNOWN_ERR); } } } }); }
public void setPlacesProvider(final JSONArray args, final CallbackContext callbackContext) throws JSONException { final String provider = args.getString(0); Radar.RadarPlacesProvider p; if ("facebook".equals(provider)) { p = Radar.RadarPlacesProvider.FACEBOOK; } else { p = Radar.RadarPlacesProvider.NONE; } Radar.setPlacesProvider(p); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); }
private void hasRewardedVideoAction(JSONArray args, final CallbackContext callbackContext) throws JSONException { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { boolean available = IronSource.isRewardedVideoAvailable(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, available)); } }); }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("init")) { this.init(callbackContext); return true; } if (action.equals("stop")) { this.delToken(callbackContext); } return false; }
/** * Requests a filesystem in which to store application data. * * @param type of file system requested * @param requiredSize required free space in the file system in bytes * @param callbackContext context for returning the result or error * @throws JSONException */ private void requestFileSystem(int type, long requiredSize, final CallbackContext callbackContext) throws JSONException { Filesystem rootFs = null; try { rootFs = this.filesystems.get(type); } catch (ArrayIndexOutOfBoundsException e) { // Pass null through } if (rootFs == null) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR)); } else { // If a nonzero required size was specified, check that the retrieved filesystem has enough free space. long availableSize = 0; if (requiredSize > 0) { availableSize = rootFs.getFreeSpaceInBytes(); } if (availableSize < requiredSize) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR)); } else { JSONObject fs = new JSONObject(); fs.put("name", rootFs.name); fs.put("root", rootFs.getRootEntry()); callbackContext.success(fs); } } }
/** * Destroys IronSource Banner and removes it from the container */ private void hideBannerAction(JSONArray args, final CallbackContext callbackContext) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { hideBannerView(); callbackContext.success(); } }); }
private void sendResult(PluginResult result) { if (result == null) { return; } for (CallbackContext callbackContext : callbackContexts) { callbackContext.sendPluginResult(result); } }
private void stopLogging(final CallbackContext callbackContext) { if (this.bashExecuter != null) { this.bashExecuter.killProcess(); this.bashExecuter = null; } if (this.loggerThread != null) { this.loggerThread.interrupt(); this.loggerThread = null; } if (callbackContext != null) { callbackContext.success(); } }
/** * Get the badge number. * * @param callback The function to be exec as the callback. */ private void getBadge (final CallbackContext callback) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { int badge = impl.getBadge(); sendPluginResult(callback, badge); } }); }
private ActivityInfo getActivity(final CallbackContext callbackContext, final Intent shareIntent, final String appPackageName, final String appName) { final PackageManager pm = webView.getContext().getPackageManager(); List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0); for (final ResolveInfo app : activityList) { if ((app.activityInfo.packageName).contains(appPackageName)) { if (appName == null || (app.activityInfo.name).contains(appName)) { return app.activityInfo; } } } // no matching app found callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, getShareActivities(activityList))); return null; }