private void errorCallback(final String returnInfo) { if (geofencingCallbacks == null) { JSONObject returnErrorInfo = new JSONObject(); try { returnErrorInfo.put("code", DGLocationStatus.PERMISSIONDENIED.getStatusCode()); returnErrorInfo.put("message", "At first, Please call initCallbackForRegionMonitoring()."); } catch (JSONException ex) { currentCallbacks.sendPluginResult( new PluginResult(PluginResult.Status.ERROR, ex.toString())); return; } currentCallbacks.sendPluginResult( new PluginResult(PluginResult.Status.ERROR, returnErrorInfo)); } else { cordova .getThreadPool() .execute( new Runnable() { public void run() { PluginResult result = new PluginResult(PluginResult.Status.ERROR, returnInfo); result.setKeepCallback(true); geofencingCallbacks.sendPluginResult(result); } }); } }
private void addTransaction( String id, String affiliation, double revenue, double tax, double shipping, String currencyCode, CallbackContext callbackContext) { if (!trackerStarted) { callbackContext.error("Tracker not started"); return; } if (null != id && id.length() > 0) { HitBuilders.TransactionBuilder hitBuilder = new HitBuilders.TransactionBuilder(); addCustomDimensionsToHitBuilder(hitBuilder); tracker.send( hitBuilder .setTransactionId(id) .setAffiliation(affiliation) .setRevenue(revenue) .setTax(tax) .setShipping(shipping) .setCurrencyCode(currencyCode) .build()); // Deprecated callbackContext.success("Add Transaction: " + id); } else { callbackContext.error("Expected non-empty ID."); } }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("getBluetoothMacAddress")) { String macAddress = this.getBluetoothMacAddress(); if (macAddress != null) { JSONObject JSONresult = new JSONObject(); try { JSONresult.put("mac", macAddress); PluginResult r = new PluginResult(PluginResult.Status.OK, JSONresult); callbackContext.success(macAddress); r.setKeepCallback(true); callbackContext.sendPluginResult(r); return true; } catch (JSONException jsonEx) { PluginResult r = new PluginResult(PluginResult.Status.JSON_EXCEPTION); callbackContext.error("error"); r.setKeepCallback(true); callbackContext.sendPluginResult(r); return true; } } } return false; }
/** * Open a database. * * @param dbName The name of the database file */ private SQLiteAndroidDatabase openDatabase(String dbname, CallbackContext cbc, boolean old_impl) throws Exception { try { // ASSUMPTION: no db (connection/handle) is already stored in the map // [should be true according to the code in DBRunner.run()] File dbfile = this.cordova.getActivity().getDatabasePath(dbname); if (!dbfile.exists()) { dbfile.getParentFile().mkdirs(); } Log.v("info", "Open sqlite db: " + dbfile.getAbsolutePath()); SQLiteAndroidDatabase mydb = old_impl ? new SQLiteAndroidDatabase() : new SQLiteDatabaseNDK(); mydb.open(dbfile); if (cbc != null) // XXX Android locking/closing BUG workaround cbc.success(); return mydb; } catch (Exception e) { if (cbc != null) // XXX Android locking/closing BUG workaround cbc.error("can't open database " + e); throw e; } }
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equals("upload") || action.equals("download")) { String source = args.getString(0); String target = args.getString(1); if (action.equals("upload")) { try { source = URLDecoder.decode(source, "UTF-8"); upload(source, target, args, callbackContext); } catch (UnsupportedEncodingException e) { callbackContext.sendPluginResult( new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error.")); } } else { download(source, target, args, callbackContext); } return true; } else if (action.equals("abort")) { String objectId = args.getString(0); abort(objectId); callbackContext.success(); return true; } return false; }
private boolean readTokenCacheItems(String authority) throws JSONException { final AuthenticationContext authContext; try { authContext = getOrCreateContext(authority); } catch (Exception e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); return true; } JSONArray result = new JSONArray(); ITokenCacheStore cache = authContext.getCache(); if (cache instanceof ITokenStoreQuery) { Iterator<TokenCacheItem> cacheItems = ((ITokenStoreQuery) cache).getAll(); while (cacheItems.hasNext()) { TokenCacheItem item = cacheItems.next(); result.put(tokenItemToJSON(item)); } } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); return true; }
@Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { if (action.equals("storeMeasurement")) { Context ctxt = cordova.getActivity(); (new ClientStatsHelper(ctxt)) .storeMeasurement( data.getString(0), // key data.getString(1), // value data.getString(2)); // ts callbackContext.success(); return true; } else if (action.equals("storeEventNow")) { Context ctxt = cordova.getActivity(); new ClientStatsHelper(ctxt) .storeMeasurement( data.getString(0), // key null, // value String.valueOf(System.currentTimeMillis())); // ts callbackContext.success(); return true; } else { return false; } }
private void trackEvent( String category, String deepLinkUrl, String action, String label, long value, CallbackContext callbackContext) { if (!trackerStarted) { callbackContext.error("Tracker not started"); return; } addCustomDimensionsToTracker(tracker); if (null != category && category.length() > 0) { tracker.send( new HitBuilders.EventBuilder() .setCampaignParamsFromUrl(deepLinkUrl) .setCategory(category) .setAction(action) .setLabel(label) .setValue(value) .build()); callbackContext.success("Track Event: " + category); } else { callbackContext.error("Expected non-empty string arguments."); } }
@Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { if (action.equals(ACTION)) { String base64 = data.optString(0); if (base64.equals("")) // isEmpty() requires API level 9 callbackContext.error("Missing base64 string"); // Create the bitmap from the base64 string Log.d("Canvas2ImagePlugin", base64); byte[] decodedString = Base64.decode(base64, Base64.DEFAULT); Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); if (bmp == null) { callbackContext.error("The image could not be decoded"); } else { // Save the image File imageFile = savePhoto(bmp); if (imageFile == null) callbackContext.error("Error while saving image"); // Update image gallery scanPhoto(imageFile); callbackContext.success(imageFile.toString()); } return true; } else { return false; } }
public void sendSingleTextMessage(JSONArray data, CallbackContext callbackContext) { Log.i(TAG, " sendSingleTextMessage \n" + data); final CallbackContext cb = callbackContext; try { String username = data.getString(0); String text = data.getString(1); Conversation conversation = JMessageClient.getSingleConversation(username); if (conversation == null) { conversation = Conversation.createSingleConversation(username); } if (conversation == null) { callbackContext.error("无法创建对话"); return; } TextContent content = new TextContent(text); final Message msg = conversation.createSendMessage(content); JMessageClient.sendMessage(msg); callbackContext.success("正在发送"); } catch (JSONException e) { e.printStackTrace(); callbackContext.error("error reading id json"); } }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try { if (action.equals("takePicture")) { this.targetHeight = 0; this.targetWidth = 0; this.mQuality = 80; this.targetHeight = args.getInt(4); this.targetWidth = args.getInt(3); this.mQuality = args.getInt(0); this.takePicture(); PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); r.setKeepCallback(true); callbackContext.sendPluginResult(r); return true; } return false; } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return true; } }
private boolean executeInitWithAppID(JSONArray inputs, CallbackContext callbackContext) { JSONObject args; // Get the input data. String strEnv = "ENV_NONE"; try { args = inputs.getJSONObject(0); this.appId = args.getString("appId"); strEnv = args.getString("appEnv"); } catch (JSONException exception) { Log.w(LOGTAG, String.format("Got JSON Exception: %s", exception.getMessage())); callbackContext.sendPluginResult(new PluginResult(Status.JSON_EXCEPTION)); return true; } if (strEnv.equals("ENV_LIVE")) { this.appEnv = PayPal.ENV_LIVE; } else if (strEnv.equals("ENV_SANDBOX")) { this.appEnv = PayPal.ENV_SANDBOX; } else { this.appEnv = PayPal.ENV_NONE; } Log.d(LOGTAG, "init paypal for " + this.appId + " with " + strEnv); PayPal.initWithAppID(cordova.getActivity(), this.appId, this.appEnv); callbackContext.sendPluginResult(new PluginResult(Status.OK)); return true; }
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if ("initialize".equals(action)) { initialize(args.optJSONObject(0), callbackContext); } else if ("attachUser".equals(action)) { attachUser(args.optJSONObject(0), callbackContext); } else if ("detachUser".equals(action)) { detachUser(callbackContext); } else if ("refresh".equals(action)) { refresh(callbackContext); } else if ("checkCapabilitiesAndRights".equals(action)) { verifyCapabilities(callbackContext); } else if ("askPermissions".equals(action)) { askPermissions(callbackContext); } else if ("startListener".equals(action)) { registerEventCallback(callbackContext); } else if ("stopListener".equals(action)) { unregisterEventCallback(callbackContext); // iOS only methods } else if ("setLogLevel".equals(action)) { callbackContext.error("setLogLevel is only available on iOS"); } else if ("checkCapabilitiesAndRightsWithAlert".equals(action)) { callbackContext.error("checkCapabilitiesAndRightsWithAlert is only available on iOS"); } else if ("getInRegions".equals(action)) { callbackContext.error("getInRegions is only available on iOS"); } else if ("getBeaconState".equals(action)) { callbackContext.error("getBeaconState is only available on iOS"); } else { return false; } return true; }
private void sum(Integer num1, Integer num2, CallbackContext callbackContext) { if (num1 != null && num2 != null) { callbackContext.success(num1 + num2); } else { callbackContext.error("Expected two integer arguments."); } }
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackS=Context The callback id used when calling back into JavaScript. * @return True if the action was valid. * @throws JSONException */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("start")) { this.start(); } else if (action.equals("stop")) { this.stop(); } else if (action.equals("getProximityState")) { // If not running, then this is an async call, so don't worry about waiting if (this.status != ProximitySensorListener.RUNNING) { int r = this.start(); if (r == ProximitySensorListener.ERROR_FAILED_TO_START) { callbackContext.sendPluginResult( new PluginResult( PluginResult.Status.IO_EXCEPTION, ProximitySensorListener.ERROR_FAILED_TO_START)); return true; } // Set a timeout callback on the main thread. Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed( new Runnable() { public void run() { ProximitySensorListener.this.timeout(); } }, 2000); } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getProximity())); } else { // Unsupported action return false; } return true; }
/** * Executes the request. * * @param action the action to execute. * @param args the exec() arguments. * @param callbackContext the callback context used when calling back into JavaScript. * @return whether the action was valid. */ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { if (action.equalsIgnoreCase("init")) { if (logger != null) { logger.stop(); } String[] sensors; try { JSONArray strings = args.getJSONArray(0); sensors = new String[strings.length()]; for (int i = 0; i < strings.length(); i++) sensors[i] = strings.getString(i); } catch (JSONException ex) { callbackContext.error(ex.getMessage()); return true; } try { logger = new SensorLogger(this.view.getContext(), sensors); } catch (IOException ex) { callbackContext.error(ex.getMessage()); return true; } callbackContext.success(); return true; } else if (action.equalsIgnoreCase("start")) { logger.start(); callbackContext.success(); return true; } else if (action.equalsIgnoreCase("stop")) { logger.stop(); callbackContext.success(); return true; } return false; }
void setTags(JSONArray data, CallbackContext callbackContext) { HashSet<String> tags = null; try { String tagStr; if (data == null) { // tags=null; } else if (data.length() == 0) { tags = new HashSet<String>(); } else { tagStr = data.getString(0); String[] tagArray = tagStr.split(","); for (String tag : tagArray) { if (tags == null) { tags = new HashSet<String>(); } tags.add(tag); } } // Set<String> validTags = JPushInterface.filterValidTags(tags); JPushInterface.setTags( this.cordova.getActivity().getApplicationContext(), tags, mTagWithAliasCallback); callbackContext.success(); } catch (JSONException e) { e.printStackTrace(); callbackContext.error("Error reading tags JSON"); } }
public int readNfcV(Tag tag) throws Exception { if (tag == null) { callbackContext.error("NULL"); } byte[] response = new byte[4]; NfcV nfcv = NfcV.get(tag); if (nfcv != null) { try { nfcv.connect(); byte[] request = new byte[] { (byte) 0x00, // flag (byte) 0x20, // command: READ ONE BLOCK (byte) block // IMMER im gleichen Block }; response = nfcv.transceive(request); } catch (IOException e) { callbackContext.error(nfcv.toString()); } finally { try { nfcv.close(); } catch (IOException e) { } } } // 1. Byte: Block locking status byte[] value = new byte[] {response[1], response[2], response[3], response[4]}; return ByteBuffer.wrap(value).order(java.nio.ByteOrder.BIG_ENDIAN).getInt(); }
@Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { this._callbackContext = callbackContext; if (ACTION_INIT.equals(action)) { return init(args.getString(0), args.getString(1), args.getString(2)); } else if (ACTION_LOGIN.equals(action)) { JSONArray permissions = args.optJSONArray(0); return login(permissions, callbackContext); } else if (ACTION_SHARE.equals(action)) { return shareOrLogin(args.getString(0), args.getString(1)); } else if (ACTION_FRIENDS_GET.equals(action)) { return friendsGet(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_FRIENDS_GET_ONLINE.equals(action)) { return friendsGetOnline(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_STREAM_PUBLISH.equals(action)) { // TODO } else if (ACTION_USERS_GET_INFO.equals(action)) { return usersGetInfo(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_CALL_API_METHOD.equals(action)) { String method = args.getString(0); JSONObject params = args.getJSONObject(1); return callApiMethod(method, JsonHelper.toMap(params), callbackContext); } Log.e(TAG, "Unknown action: " + action); _callbackContext.sendPluginResult( new PluginResult(PluginResult.Status.ERROR, "Unimplemented method: " + action)); _callbackContext.error("Unimplemented method: " + action); return true; }
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equals("upload") || action.equals("download")) { String source = args.getString(0); String target = args.getString(1); if (action.equals("upload")) { upload(source, target, args, callbackContext); } else { download(source, target, args, callbackContext); } return true; } else if (action.equals("abort")) { String objectId = args.getString(0); abort(objectId); callbackContext.success(); return true; } else if (action.equals("pause")) { String objectId = args.getString(0); pause(objectId); callbackContext.success(); return true; } return false; }
/** * Busca todos os dispositivos Bluetooth pareados com o device * * @param callbackContext */ protected void getBluetoothPairedDevices(CallbackContext callbackContext) { BluetoothAdapter mBluetoothAdapter = null; try { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { callbackContext.error(this.getErrorByCode(1)); return; } if (!mBluetoothAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); this.mCordova.getActivity().startActivityForResult(enableBluetooth, 0); } Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { JSONArray json = new JSONArray(); for (BluetoothDevice device : pairedDevices) { Hashtable map = new Hashtable(); map.put("type", device.getType()); map.put("address", device.getAddress()); map.put("name", device.getName()); JSONObject jObj = new JSONObject(map); json.put(jObj); } callbackContext.success(json); } else { callbackContext.error(this.getErrorByCode(2)); } } catch (Exception e) { Log.e(LOG_TAG, e.getMessage()); e.printStackTrace(); callbackContext.error(e.getMessage()); } }
private void coolMethod(String message, CallbackContext callbackContext) { if (message != null && message.length() > 0) { callbackContext.success(message); } else { callbackContext.error("Expected one non-empty string argument."); } }
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { WifiManager wifiMgr = (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE); DhcpInfo ipConfig = wifiMgr.getDhcpInfo(); if (IpUtils.toIpv4(ipConfig.ipAddress).compareTo("0.0.0.0") != 0) { netConfig.put("ipAddress", IpUtils.toIpv4(ipConfig.ipAddress)); } netConfig.put("ipAddress", IpUtils.toIpv4(ipConfig.ipAddress)); netConfig.put("macAddress", wifiMgr.getConnectionInfo().getMacAddress()); netConfig.put("netmask", IpUtils.toIpv4(ipConfig.netmask)); netConfig.put("gateway", IpUtils.toIpv4(ipConfig.gateway)); netConfig.put("dns1", IpUtils.toIpv4(ipConfig.dns1)); netConfig.put("dns2", IpUtils.toIpv4(ipConfig.dns1)); if (netConfig != null) { callbackContext.success(netConfig); return true; } else { callbackContext.error("Operation failed"); return false; } }
private void getScreenshotAsURI(Bitmap bitmap, int quality) { try { ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.NO_WRAP); String js_out = new String(output); js_out = "data:image/jpeg;base64," + js_out; JSONObject jsonRes = new JSONObject(); jsonRes.put("URI", js_out); PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes); mCallbackContext.sendPluginResult(result); js_out = null; output = null; code = null; } jpeg_data = null; } catch (JSONException e) { mCallbackContext.error(e.getMessage()); } catch (Exception e) { mCallbackContext.error(e.getMessage()); } }
private void trackTiming( String category, long intervalInMilliseconds, String name, String label, CallbackContext callbackContext) { if (!trackerStarted) { callbackContext.error("Tracker not started"); return; } if (null != category && category.length() > 0) { HitBuilders.TimingBuilder hitBuilder = new HitBuilders.TimingBuilder(); addCustomDimensionsToHitBuilder(hitBuilder); tracker.send( hitBuilder .setCategory(category) .setValue(intervalInMilliseconds) .setVariable(name) .setLabel(label) .build()); callbackContext.success("Track Timing: " + category); } else { callbackContext.error("Expected non-empty string arguments."); } }
private void saveScreenshot(Bitmap bitmap, String format, String fileName, Integer quality) { try { File folder = new File(Environment.getExternalStorageDirectory(), "Pictures"); if (!folder.exists()) { folder.mkdirs(); } File f = new File(folder, fileName + "." + format); FileOutputStream fos = new FileOutputStream(f); if (format.equals("png")) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } else if (format.equals("jpg")) { bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null ? 100 : quality, fos); } JSONObject jsonRes = new JSONObject(); jsonRes.put("filePath", f.getAbsolutePath()); PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes); mCallbackContext.sendPluginResult(result); scanPhoto(f.getAbsolutePath()); fos.close(); } catch (JSONException e) { mCallbackContext.error(e.getMessage()); } catch (IOException e) { mCallbackContext.error(e.getMessage()); } }
private void addTransactionItem( String id, String name, String sku, String category, double price, long quantity, String currencyCode, CallbackContext callbackContext) { if (!trackerStarted) { callbackContext.error("Tracker not started"); return; } if (null != id && id.length() > 0) { HitBuilders.ItemBuilder hitBuilder = new HitBuilders.ItemBuilder(); addCustomDimensionsToHitBuilder(hitBuilder); tracker.send( hitBuilder .setTransactionId(id) .setName(name) .setSku(sku) .setCategory(category) .setPrice(price) .setQuantity(quantity) .setCurrencyCode(currencyCode) .build()); // Deprecated callbackContext.success("Add Transaction Item: " + id); } else { callbackContext.error("Expected non-empty ID."); } }
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; if (action.equals(ENCODE)) { JSONObject obj = args.optJSONObject(0); if (obj != null) { String type = obj.optString(TYPE); String data = obj.optString(DATA); // If the type is null then force the type to text if (type == null) { type = TEXT_TYPE; } if (data == null) { callbackContext.error("User did not specify data to encode"); return true; } encode(type, data); } else { callbackContext.error("User did not specify data to encode"); return true; } } else if (action.equals(SCAN)) { scan(); } else { return false; } return true; }
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { if (ACTION_ADD_CALENDAR_ENTRY.equals(action)) { JSONObject arg_object = args.getJSONObject(0); Intent calIntent = new Intent(Intent.ACTION_EDIT) .setType("vnd.android.cursor.item/event") .putExtra("beginTime", arg_object.getLong("startTimeMillis")) .putExtra("endTime", arg_object.getLong("endTimeMillis")) .putExtra("title", arg_object.getString("title")) .putExtra("description", arg_object.getString("description")) .putExtra("eventLocation", arg_object.getString("eventLocation")); this.cordova.getActivity().startActivity(calIntent); callbackContext.success(); return true; } callbackContext.error("Invalid action"); return false; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); callbackContext.error(e.getMessage()); return false; } }
private boolean checkGeofencingAvailable() throws JSONException { if (!isLocationServicesEnabled()) { JSONObject returnInfo = new JSONObject(); returnInfo.put("code", DGLocationStatus.PERMISSIONDENIED.getStatusCode()); returnInfo.put("message", "Location services are disabled."); errorCallback(returnInfo); if (currentCallbacks != null) { currentCallbacks.error(returnInfo); } return false; } else if (!isGooglePlayServicesAvailable()) { JSONObject returnInfo = new JSONObject(); returnInfo.put("code", DGGeofencingStatus.GEOFENCINGUNAVAILABLE.getStatusCode()); returnInfo.put("message", "Geofencing services are disabled."); errorCallback(returnInfo); if (currentCallbacks != null) { currentCallbacks.error(returnInfo); } return false; } return true; }