public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { for (int r : grantResults) { if (r == PackageManager.PERMISSION_DENIED) { this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); return; } } switch (requestCode) { case TAKE_PIC_SEC: takePicture(this.destType, this.encodingType); break; case SAVE_TO_ALBUM_SEC: this.getImage(this.srcType, this.destType, this.encodingType); break; } }
/** * Listener for event that some error happened during the update installation. * * @param event event information * @see UpdateInstallationErrorEvent * @see EventBus * @see UpdatesInstaller */ @SuppressWarnings("unused") @Subscribe public void onEvent(UpdateInstallationErrorEvent event) { Log.d("CHCP", "Failed to install"); PluginResult jsResult = PluginResultHelper.pluginResultFromEvent(event); // notify js if (installJsCallback != null) { installJsCallback.sendPluginResult(jsResult); installJsCallback = null; } sendMessageToDefaultCallback(jsResult); rollbackIfCorrupted(event.error()); }
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { for(int r:grantResults) { if(r == PackageManager.PERMISSION_DENIED) { mCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); return; } } switch(requestCode) { case SAVE_SCREENSHOT_SEC: saveScreenshot(); break; case SAVE_SCREENSHOT_URI_SEC: getScreenshotAsURI(); break; } }
/** * Listener for event that there is no update available at the moment. * We are as fresh as possible. * * @param event event information * @see EventBus * @see NothingToUpdateEvent * @see UpdatesLoader */ @SuppressWarnings("unused") @Subscribe public void onEvent(NothingToUpdateEvent event) { Log.d("CHCP", "Nothing to update"); PluginResult jsResult = PluginResultHelper.pluginResultFromEvent(event); //notify JS if (downloadJsCallback != null) { downloadJsCallback.sendPluginResult(jsResult); downloadJsCallback = null; } sendMessageToDefaultCallback(jsResult); }
/** * Full stop using brute force. Works with many Android versions. */ public void stopLocation(){ if(_phoneStateListener != null && _telephonyManager != null){ _telephonyManager.listen(_phoneStateListener, PhoneStateListener.LISTEN_NONE); _telephonyManager.listen(_signalStrengthListener, PhoneStateListener.LISTEN_NONE); _phoneStateListener = null; _signalStrengthListener = null; _telephonyManager = null; try { Thread.currentThread().interrupt(); } catch(SecurityException exc){ Log.e(TAG, exc.getMessage()); sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.FAILED_THREAD_INTERRUPT())); } Log.d(TAG, "Stopping cell location listeners"); } }
@Override public void initialize(final CordovaInterface cordova, final CordovaWebView webView) { super.initialize(cordova, webView); parseCordovaConfigXml(); loadPluginInternalPreferences(); Log.d("CHCP", "Currently running release version " + pluginInternalPrefs.getCurrentReleaseVersionName()); // clean up file system cleanupFileSystemFromOldReleases(); handler = new Handler(); fileStructure = new PluginFilesStructure(cordova.getActivity(), pluginInternalPrefs.getCurrentReleaseVersionName()); appConfigStorage = new ApplicationConfigStorage(); defaultCallbackStoredResults = new ArrayList<PluginResult>(); }
/** * For working with pre-Android M security permissions * @param gpsEnabled If the cacheManifest and system allow gps * @param networkLocationEnabled If the cacheManifest and system allow network location access * @param cellularEnabled If the cacheManifest and system allow cellular data access */ private void alertDialog(boolean gpsEnabled, boolean networkLocationEnabled, boolean cellularEnabled){ if(!gpsEnabled || !networkLocationEnabled){ sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(PROVIDER_PRIMARY, ErrorMessages.LOCATION_SERVICES_UNAVAILABLE())); final DialogFragment gpsFragment = new GPSAlertDialogFragment(); gpsFragment.show(_cordovaActivity.getFragmentManager(), "GPSAlert"); } if(!cellularEnabled){ sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(PROVIDER_PRIMARY, ErrorMessages.CELL_DATA_NOT_AVAILABLE())); final DialogFragment networkUnavailableFragment = new NetworkUnavailableDialogFragment(); networkUnavailableFragment.show(_cordovaActivity.getFragmentManager(), "NetworkUnavailableAlert"); } }
private void javascriptCallback(String event, JSONObject arguments, CallbackContext callbackContext) { if (callbackContext == null) { return; } JSONObject options = new JSONObject(); try { options.putOpt("callback", event); options.putOpt("arguments", arguments); } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult( PluginResult.Status.JSON_EXCEPTION)); return; } PluginResult result = new PluginResult(Status.OK, options); result.setKeepCallback(true); callbackContext.sendPluginResult(result); }
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { LOG.d(TAG, "We are entering execute"); context = callbackContext; if(action.equals("getPermission")) { if(hasPermisssion()) { PluginResult r = new PluginResult(PluginResult.Status.OK); context.sendPluginResult(r); return true; } else { PermissionHelper.requestPermissions(this, 0, permissions); } return true; } return false; }
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("getConnectionInfo")) { this.connectionCallbackContext = callbackContext; NetworkInfo info = sockMan.getActiveNetworkInfo(); String connectionType = ""; try { connectionType = this.getConnectionInfo(info).get("type").toString(); } catch (JSONException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } return false; }
private void save(JSONArray args) throws JSONException { final JSONObject contact = args.getJSONObject(0); this.cordova.getThreadPool().execute(new Runnable(){ public void run() { JSONObject res = null; String id = contactAccessor.save(contact); if (id != null) { try { res = contactAccessor.getContactById(id); } catch (JSONException e) { LOG.e(LOG_TAG, "JSON fail.", e); } } if (res != null) { callbackContext.success(res); } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, UNKNOWN_ERROR)); } } }); }
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) /* throws JSONException */ { for(int result:grantResults) { if(result == PackageManager.PERMISSION_DENIED) { LOG.d(TAG, "User *rejected* Coarse Location Access"); this.permissionCallback.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR)); return; } } switch(requestCode) { case REQUEST_ACCESS_COARSE_LOCATION: LOG.d(TAG, "User granted Coarse Location Access"); findLowEnergyDevices(permissionCallback, serviceUUIDs, scanSeconds); this.permissionCallback = null; this.serviceUUIDs = null; this.scanSeconds = -1; break; } }
@Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { super.onCharacteristicChanged(gatt, characteristic); LOG.d(TAG, "onCharacteristicChanged " + characteristic); CallbackContext callback = notificationCallbacks.get(generateHashKey(characteristic)); if (callback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, characteristic.getValue()); result.setKeepCallback(true); callback.sendPluginResult(result); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (_callbackContext != null) { switch (requestCode) { case ACTIVITY_CODE_SEND__BOOLRESULT: _callbackContext.sendPluginResult(new PluginResult( PluginResult.Status.OK, resultCode == Activity.RESULT_OK)); break; case ACTIVITY_CODE_SEND__OBJECT: JSONObject json = new JSONObject(); try { json.put("completed", resultCode == Activity.RESULT_OK); json.put("app", ""); // we need a completely different approach if we want to support this on Android. Idea: https://clickclickclack.wordpress.com/2012/01/03/intercepting-androids-action_send-intents/ _callbackContext.sendPluginResult(new PluginResult( PluginResult.Status.OK, json)); } catch (JSONException e) { _callbackContext.error(e.getMessage()); } break; default: _callbackContext.success(); } } }
private static void sendCallback(PluginResult.Status status, String message){ if(!Thread.currentThread().isInterrupted()){ final PluginResult result = new PluginResult(status, message); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } }
private void queueCommand(BLECommand command) { LOG.d(TAG,"Queuing Command " + command); commandQueue.add(command); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); command.getCallbackContext().sendPluginResult(result); if (!bleProcessing) { processCommands(); } }
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; }
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); } } } }); }
static void encodeAsMessageHelper(StringBuilder sb, PluginResult pluginResult) { switch (pluginResult.getMessageType()) { case PluginResult.MESSAGE_TYPE_BOOLEAN: sb.append(pluginResult.getMessage().charAt(0)); // t or f. break; case PluginResult.MESSAGE_TYPE_NULL: // N sb.append('N'); break; case PluginResult.MESSAGE_TYPE_NUMBER: // n sb.append('n') .append(pluginResult.getMessage()); break; case PluginResult.MESSAGE_TYPE_STRING: // s sb.append('s'); sb.append(pluginResult.getStrMessage()); break; case PluginResult.MESSAGE_TYPE_BINARYSTRING: // S sb.append('S'); sb.append(pluginResult.getMessage()); break; case PluginResult.MESSAGE_TYPE_ARRAYBUFFER: // A sb.append('A'); sb.append(pluginResult.getMessage()); break; case PluginResult.MESSAGE_TYPE_MULTIPART: sb.append('M'); for (int i = 0; i < pluginResult.getMultipartMessagesSize(); i++) { PluginResult multipartMessage = pluginResult.getMultipartMessage(i); sb.append(String.valueOf(calculateEncodedLengthHelper(multipartMessage))); sb.append(' '); encodeAsMessageHelper(sb, multipartMessage); } break; case PluginResult.MESSAGE_TYPE_JSON: default: sb.append(pluginResult.getMessage()); // [ or { } }
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { try { if (ACTION_KEEP_AWAKE.equals(action)) { cordova.getActivity().runOnUiThread( new Runnable() { public void run() { cordova.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } }); return true; } else if (ACTION_ALLOW_SLEEP_AGAIN.equals(action)) { cordova.getActivity().runOnUiThread( new Runnable() { public void run() { cordova.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } }); return true; } else { callbackContext.error("insomnia." + action + " is not a supported function. Did you mean '" + ACTION_KEEP_AWAKE + "'?"); return false; } } catch (Exception e) { callbackContext.error(e.getMessage()); return false; } }
/**----------------------- INTERSTITIAL --------------------------- */ private void hasInterstitialAction(JSONArray args, final CallbackContext callbackContext) { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { boolean ready = IronSource.isInterstitialReady(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, ready)); } }); }
void encodeAsJsMessage(StringBuilder sb) { if (pluginResult == null) { sb.append(jsPayloadOrCallbackId); } else { int status = pluginResult.getStatus(); boolean success = (status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal()); sb.append("cordova.callbackFromNative('") .append(jsPayloadOrCallbackId) .append("',") .append(success) .append(",") .append(status) .append(",["); switch (pluginResult.getMessageType()) { case PluginResult.MESSAGE_TYPE_BINARYSTRING: sb.append("atob('") .append(pluginResult.getMessage()) .append("')"); break; case PluginResult.MESSAGE_TYPE_ARRAYBUFFER: sb.append("cordova.require('cordova/base64').toArrayBuffer('") .append(pluginResult.getMessage()) .append("')"); break; default: sb.append(pluginResult.getMessage()); } sb.append("],") .append(pluginResult.getKeepCallback()) .append(");"); } }
/** * Callback handler for this Class * @param status Message status * @param message Any message */ private static void sendCallback(PluginResult.Status status, String message){ if(!Thread.currentThread().isInterrupted()){ final PluginResult result = new PluginResult(status, message); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } }
/** * If a notification with an ID is scheduled. * * @param id * Notification ID * @param command * The callback context used when calling back into JavaScript. */ private void isScheduled (int id, CallbackContext command) { boolean exist = getNotificationMgr().exist( id, Notification.Type.SCHEDULED); PluginResult result = new PluginResult( PluginResult.Status.OK, exist); command.sendPluginResult(result); }
/** * If a notification with an ID is triggered. * * @param id * Notification ID * @param command * The callback context used when calling back into JavaScript. */ private void isTriggered (int id, CallbackContext command) { boolean exist = getNotificationMgr().exist( id, Notification.Type.TRIGGERED); PluginResult result = new PluginResult( PluginResult.Status.OK, exist); command.sendPluginResult(result); }
void sendPluginResult(PluginResult pluginResult) { synchronized (this) { if (!aborted) { callbackContext.sendPluginResult(pluginResult); } } }
@Test public void testPopAndEncode() { NativeToJsMessageQueue.BridgeMode bridge; bridge = new NativeToJsMessageQueue.NoOpBridgeMode(); queue.addBridgeMode(bridge); queue.setBridgeMode(0); PluginResult result = new PluginResult(PluginResult.Status.OK); queue.addPluginResult(result, TEST_CALLBACK_ID); assertFalse(queue.isEmpty()); String resultString = queue.popAndEncode(false); String [] results = resultString.split(" "); assertEquals(TEST_CALLBACK_ID, results[2]); }
private static void processCellInfos(List<CellInfo> cellInfos){ if(cellInfos != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ for(CellInfo cellInfo : cellInfos){ if(cellInfo instanceof CellInfoWcdma){ final CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoWCDMAJSON(cellInfoWcdma, _returnSignalStrength)); } if(cellInfo instanceof CellInfoGsm){ final CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoGSMJSON(cellInfoGsm, _returnSignalStrength)); } if(cellInfo instanceof CellInfoCdma){ final CellInfoCdma cellIdentityCdma = (CellInfoCdma) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoCDMAJSON(cellIdentityCdma, _returnSignalStrength)); } if(cellInfo instanceof CellInfoLte){ final CellInfoLte cellInfoLte = (CellInfoLte) cellInfo; sendCallback(PluginResult.Status.OK, JSONHelper.cellInfoLTEJSON(cellInfoLte, _returnSignalStrength)); } Log.d(TAG,cellInfo.toString()); } } else { Log.e(TAG, "CellInfoLocation returning null. Is it supported on this phone?"); // There are several reasons as to why cell location data would be null. // * could be an older device running an unsupported version of the Android OS // * could be a device that doesn't support this capability. // * could be incorrect permissions: ACCESS_COARSE_LOCATION sendCallback(PluginResult.Status.ERROR, JSONHelper.errorJSON(CELLINFO_PROVIDER, ErrorMessages.CELL_DATA_IS_NULL())); } }
private void findEvents(JSONArray args) { if (args.length() == 0) { System.err.println("Exception: No Arguments passed"); return; } // note that if the dev didn't call requestReadPermission before calling this method and calendarPermissionGranted returns false, // the app will ask permission and this method needs to be invoked again (done for backward compat). if (!calendarPermissionGranted(Manifest.permission.READ_CALENDAR)) { requestReadPermission(PERMISSION_REQCODE_FIND_EVENTS); return; } try { final JSONObject jsonFilter = args.getJSONObject(0); final JSONObject argOptionsObject = jsonFilter.getJSONObject("options"); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { JSONArray jsonEvents = getCalendarAccessor().findEvents( getPossibleNullString("id", argOptionsObject), getPossibleNullString("title", jsonFilter), getPossibleNullString("location", jsonFilter), getPossibleNullString("notes", jsonFilter), jsonFilter.optLong("startTime"), jsonFilter.optLong("endTime"), getPossibleNullString("calendarId", argOptionsObject)) ; callback.sendPluginResult(new PluginResult(PluginResult.Status.OK, jsonEvents)); } }); } catch (JSONException e) { System.err.println("Exception: " + e.getMessage()); callback.error(e.getMessage()); } }
/** * Perform update availability check. * * @param jsCallback callback where to send the result; * used, when update is requested manually from JavaScript */ private void fetchUpdate(CallbackContext jsCallback, FetchUpdateOptions fetchOptions) { if (!isPluginReadyForWork) { return; } Map<String, String> requestHeaders = null; String configURL = chcpXmlConfig.getConfigUrl(); if (fetchOptions == null) { fetchOptions = defaultFetchUpdateOptions; } if (fetchOptions != null) { requestHeaders = fetchOptions.getRequestHeaders(); final String optionalConfigURL = fetchOptions.getConfigURL(); if (!TextUtils.isEmpty(optionalConfigURL)) { configURL = optionalConfigURL; } } final UpdateDownloadRequest request = UpdateDownloadRequest.builder(cordova.getActivity()) .setConfigURL(configURL) .setCurrentNativeVersion(chcpXmlConfig.getNativeInterfaceVersion()) .setCurrentReleaseVersion(pluginInternalPrefs.getCurrentReleaseVersionName()) .setRequestHeaders(requestHeaders) .build(); final ChcpError error = UpdatesLoader.downloadUpdate(request); if (error != ChcpError.NONE) { if (jsCallback != null) { PluginResult errorResult = PluginResultHelper.createPluginResult(UpdateDownloadErrorEvent.EVENT_NAME, null, error); jsCallback.sendPluginResult(errorResult); } return; } if (jsCallback != null) { downloadJsCallback = jsCallback; } }
public void onReceivedError(AmazonWebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { Log.d(LOG_TAG, "Should never happen"); } }
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", failingUrl); obj.put("code", errorCode); obj.put("message", description); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (onBroadcastCallbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, getIntentJson(intent)); result.setKeepCallback(true); onBroadcastCallbackContext.sendPluginResult(result); } }
private PluginResult executeIsConnected(JSONArray args, final CallbackContext callbackContext){ Log.w(LOG_TAG, "executeIsConnected"); if (wifitosg != null) { callbackContext.success(wifitosg.IsConnected() ? 1 : 0); } else { callbackContext.success(0); } return null; }
private PluginResult executeIsConnectwifi(JSONArray args, final CallbackContext callbackContext){ Log.w(LOG_TAG, "executeIsConnectwifi"); if (wifitosg != null) { callbackContext.success(wifitosg.IsConnectedWifi() ? 1 : 0); } else { callbackContext.success(0); } return null; }