List of usage examples for org.apache.cordova PluginResult setKeepCallback
public void setKeepCallback(boolean b)
From source file:com.nolgong.pedometer.Pedometer.java
License:Apache License
public void startPedometerUpdates() { LOG.i(TAG, "startPedometerUpdates() " + this.activityRunning); if (this.activityRunning) { return;//from w w w.j a v a 2s .c o m } this.activityRunning = true; countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); if (countSensor != null) { LOG.i(TAG, "StepCountingAvailable " + countSensor); sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI); this.activityRunning = true; } else { LOG.i(TAG, "StepCountingAvailable fail"); this.activityRunning = false; JSONObject errorObj = new JSONObject(); try { errorObj.put("message", "Step Counter could not be started."); } catch (JSONException e) { e.printStackTrace(); } PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj); err.setKeepCallback(true); callbackContext.sendPluginResult(err); return; } }
From source file:com.nolgong.pedometer.Pedometer.java
License:Apache License
@Override public void onSensorChanged(SensorEvent event) { // LOG.i(TAG, "onSensorChanged()"); if (this.activityRunning) { if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_HIGH) { long temptime = System.currentTimeMillis(); if (temptime - this.timestamp > 2000) { LOG.i(TAG, "onSensorChanged() count : " + event.values[0]); this.numberOfSteps = event.values[0]; // this.timestamp = System.currentTimeMillis(); this.timestamp = temptime; PluginResult result = new PluginResult(PluginResult.Status.OK, this.getStepCountJSON()); result.setKeepCallback(true); callbackContext.sendPluginResult(result); }/*from w w w . j av a2 s. c om*/ } } }
From source file:com.oonhee.oojs.inappbrowser.InAppBrowser.java
License:Apache License
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry 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. */// ww w . j a v a 2 s.c o m public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); Log.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { Log.d(LOG_TAG, "in self"); // load in webview if (url.startsWith("file://") || url.startsWith("javascript:") || Config.isUrlWhiteListed(url)) { webView.loadUrl(url); } //Load the dialer else if (url.startsWith(AmazonWebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { result = showWebPage(url, features); } } // SYSTEM else if (SYSTEM.equals(target)) { Log.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { Log.d(LOG_TAG, "in blank"); result = showWebPage(url, features); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.show(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else { return false; } return true; }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
License:Apache License
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * @param callbackContext callback id for optional progress reports * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request */// w w w . java 2s .co m private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "upload " + source + " to " + target); // Setup the options final String mimeType = getArgument(args, 4, "image/jpeg"); final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); final boolean trustEveryone = args.optBoolean(6); // Always use chunked mode unless set to false as per API final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); // Look for headers on the params map for backwards compatibility with older Cordova versions. final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); final String objectId = args.getString(9); final String httpMethod = getArgument(args, 10, "POST"); final CordovaResourceApi resourceApi = webView.getResourceApi(); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); Log.d(LOG_TAG, "headers: " + headers); Log.d(LOG_TAG, "objectId: " + objectId); Log.d(LOG_TAG, "httpMethod: " + httpMethod); final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); // Accept a path or a URI for the source. Uri tmpSrc = Uri.parse(source); final Uri sourceUri = resourceApi .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); int uriType = CordovaResourceApi.getUriType(targetUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection conn = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; int totalBytes = 0; int fixedLength = -1; try { // Create return object PSFileUploadResult result = new PSFileUploadResult(); PSFileProgressResult progress = new PSFileProgressResult(); //------------------ CLIENT REQUEST // Open a HTTP connection to the URL based on protocol conn = resourceApi.createHttpConnection(targetUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) conn; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", mimeType); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); if (readResult.length >= 0) { fixedLength = (int) readResult.length; progress.setLengthComputable(true); progress.setTotal(fixedLength); } Log.d(LOG_TAG, "Content Length: " + fixedLength); // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. // http://code.google.com/p/android/issues/detail?id=3164 // It also causes OOM if HTTPS is used, even on newer devices. boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); useChunkedMode = useChunkedMode || (fixedLength == -1); if (useChunkedMode) { conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); // Although setChunkedStreamingMode sets this header, setting it explicitly here works // around an OutOfMemoryException when using https. conn.setRequestProperty("Transfer-Encoding", "chunked"); } else { conn.setFixedLengthStreamingMode(fixedLength); } conn.connect(); OutputStream sendStream = null; try { sendStream = conn.getOutputStream(); synchronized (context) { if (context.aborted) { return; } context.currentOutputStream = sendStream; } //We don't want to change encoding, we just want this to write for all Unicode. // create a buffer of maximum size int bytesAvailable = readResult.inputStream.available(); int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); long prevBytesRead = 0; while (bytesRead > 0) { result.setBytesSent(totalBytes); sendStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (totalBytes > prevBytesRead + 102400) { prevBytesRead = totalBytes; Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); } bytesAvailable = readResult.inputStream.available(); bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); // Send a progress event. progress.setLoaded(totalBytes); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } context.currentOutputStream = null; Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); //------------------ read the SERVER RESPONSE String responseString; int responseCode = conn.getResponseCode(); Log.d(LOG_TAG, "response code: " + responseCode); Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); TrackingInputStream inStream = null; try { inStream = getInputStream(conn); synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inStream; } ByteArrayOutputStream out = new ByteArrayOutputStream( Math.max(1024, conn.getContentLength())); byte[] buffer = new byte[1024]; int bytesRead = 0; // write bytes to file while ((bytesRead = inStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } responseString = out.toString("UTF-8"); } finally { context.currentInputStream = null; safeClose(inStream); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); // send request and retrieve response result.setResponseCode(responseCode); result.setResponse(responseString); context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), t); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (conn != null) { // Revert back to the proper verifier and socket factories // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) conn; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } } }); }
From source file:com.phonegap.bossbolo.plugin.inappbrowser.InAppBrowser.java
License:Apache License
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry 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. *//*from w w w . j av a 2 s. c om*/ public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if (action.equals("open")) { this.callbackContext = callbackContext; final String url = args.getString(0); String t = args.optString(1); if (t == null || t.equals("") || t.equals(NULL)) { t = SELF; } final String target = t; final HashMap<String, Boolean> features = parseFeature(args.optString(2)); String h = args.optString(3); if (h == null || h.equals("") || h.equals(NULL)) { h = url; } final String header = h; Log.d(LOG_TAG, "target = " + target); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { String result = ""; // SELF if (SELF.equals(target)) { Log.d(LOG_TAG, "in self"); /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the Config class had a static method, isUrlWhitelisted(). That * responsibility has been moved to the plugins, with an aggregating method in * PluginManager. */ Boolean shouldAllowNavigation = null; if (url.startsWith("javascript:")) { shouldAllowNavigation = true; } if (shouldAllowNavigation == null) { try { Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class); shouldAllowNavigation = (Boolean) iuw.invoke(null, url); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } if (shouldAllowNavigation == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager) gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class); shouldAllowNavigation = (Boolean) san.invoke(pm, url); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } // load in webview if (Boolean.TRUE.equals(shouldAllowNavigation)) { Log.d(LOG_TAG, "loading in webview"); webView.loadUrl(url); } //Load the dialer else if (url.startsWith(WebView.SCHEME_TEL)) { try { Log.d(LOG_TAG, "loading in dialer"); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString()); } } // load in InAppBrowser else { Log.d(LOG_TAG, "loading in InAppBrowser"); result = showWebPage(url, features, header); } } // SYSTEM else if (SYSTEM.equals(target)) { Log.d(LOG_TAG, "in system"); result = openExternal(url); } // BLANK - or anything else else { Log.d(LOG_TAG, "in blank"); result = showWebPage(url, features, header); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } }); } else if (action.equals("close")) { closeDialog(); } else if (action.equals("injectScriptCode")) { String jsWrapper = null; if (args.getBoolean(1)) { jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')", callbackContext.getCallbackId()); } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectScriptFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleCode")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("injectStyleFile")) { String jsWrapper; if (args.getBoolean(1)) { jsWrapper = String.format( "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId()); } else { jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)"; } injectDeferredObject(args.getString(0), jsWrapper); } else if (action.equals("show")) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.show(); } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); } else { return false; } return true; }
From source file:com.phonegap.customcamera.NativeCameraLauncher.java
License:Apache License
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try {//from w w w . jav a2 s. com 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.captureButtonColor = args.getString(12); this.captureButtonBorderColor = args.getString(14); this.brightnessThreshold = (float) args.getDouble(13); 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; } }
From source file:com.phonegap.plugin.BluetoothPlugin.java
License:Apache License
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { Log.d(LOG_TAG, "Plugin Called"); this.callbackContext = callbackContext; PluginResult result = null; //Looper.prepare(); btadapter = BluetoothAdapter.getDefaultAdapter(); found_devices = new ArrayList<BluetoothDevice>(); if (ACTION_DISCOVER_DEVICES.equals(action)) { try {/*from ww w .j a va2 s . c o m*/ Log.d(LOG_TAG, "We're in " + ACTION_DISCOVER_DEVICES); found_devices.clear(); discovering = true; if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } Log.i(LOG_TAG, "Discovering devices..."); btadapter.startDiscovery(); result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISCOVER_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_IS_BT_ENABLED.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_IS_BT_ENABLED); boolean isEnabled = btadapter.isEnabled(); Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Returning " + "is Bluetooth Enabled? " + isEnabled); result = new PluginResult(PluginResult.Status.OK, isEnabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BT_ENABLED, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_ENABLE_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_ENABLE_BT); boolean enabled = false; Log.d(LOG_TAG, "Enabling Bluetooth..."); if (btadapter.isEnabled()) { enabled = true; } else { enabled = btadapter.enable(); } Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Returning " + "Result: " + enabled); result = new PluginResult(PluginResult.Status.OK, enabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_ENABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_DISABLE_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_DISABLE_BT); boolean disabled = false; Log.d(LOG_TAG, "Disabling Bluetooth..."); if (btadapter.isEnabled()) { disabled = btadapter.disable(); } else { disabled = true; } Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Returning " + "Result: " + disabled); result = new PluginResult(PluginResult.Status.OK, disabled); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_DISABLE_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_PAIR_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_PAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean paired = false; Log.d(LOG_TAG, "Pairing with Bluetooth device with name " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("createBond"); paired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Returning " + "Result: " + paired); result = new PluginResult(PluginResult.Status.OK, paired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_PAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_UNPAIR_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_UNPAIR_BT); String addressDevice = args.getString(0); if (btadapter.isDiscovering()) { btadapter.cancelDiscovery(); } BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); boolean unpaired = false; Log.d(LOG_TAG, "Unpairing Bluetooth device with " + device.getName() + " and address " + device.getAddress()); try { Method m = device.getClass().getMethod("removeBond"); unpaired = (Boolean) m.invoke(device); } catch (Exception e) { e.printStackTrace(); } Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Returning " + "Result: " + unpaired); result = new PluginResult(PluginResult.Status.OK, unpaired); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_UNPAIR_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_LIST_BOUND_DEVICES.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_LIST_BOUND_DEVICES); Log.d(LOG_TAG, "Getting paired devices..."); Set<BluetoothDevice> pairedDevices = btadapter.getBondedDevices(); int count = 0; String resultBoundDevices = "[ "; if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i(LOG_TAG, device.getName() + " " + device.getAddress() + " " + device.getBondState()); if ((device.getName() != null) && (device.getBluetoothClass() != null)) { resultBoundDevices = resultBoundDevices + " { \"name\" : \"" + device.getName() + "\" ," + "\"address\" : \"" + device.getAddress() + "\" ," + "\"class\" : \"" + device.getBluetoothClass().getDeviceClass() + "\" }"; if (count < pairedDevices.size() - 1) resultBoundDevices = resultBoundDevices + ","; } else Log.i(LOG_TAG, device.getName() + " Problems retrieving attributes. Device not added "); count++; } } resultBoundDevices = resultBoundDevices + "] "; Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Returning " + resultBoundDevices); result = new PluginResult(PluginResult.Status.OK, resultBoundDevices); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_LIST_BOUND_DEVICES, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_STOP_DISCOVERING_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_STOP_DISCOVERING_BT); boolean stopped = true; Log.d(LOG_TAG, "Stop Discovering Bluetooth Devices..."); if (btadapter.isDiscovering()) { Log.i(LOG_TAG, "Stop discovery..."); stopped = btadapter.cancelDiscovery(); discovering = false; } Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Returning " + "Result: " + stopped); result = new PluginResult(PluginResult.Status.OK, stopped); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_STOP_DISCOVERING_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } } else if (ACTION_IS_BOUND_BT.equals(action)) { try { Log.d(LOG_TAG, "We're in " + ACTION_IS_BOUND_BT); String addressDevice = args.getString(0); BluetoothDevice device = btadapter.getRemoteDevice(addressDevice); Log.i(LOG_TAG, "BT Device in state " + device.getBondState()); boolean state = false; if (device != null && device.getBondState() == 12) state = true; else state = false; Log.d(LOG_TAG, "Is Bound with " + device.getName() + " - address " + device.getAddress()); Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Returning " + "Result: " + state); result = new PluginResult(PluginResult.Status.OK, state); } catch (Exception Ex) { Log.d("BluetoothPlugin - " + ACTION_IS_BOUND_BT, "Got Exception " + Ex.getMessage()); result = new PluginResult(PluginResult.Status.ERROR); } /* } else if ( ACTION_READ.equals(action) ) { final int socketId = args.getInt(0); final int bufferSize = args.getInt(1); this.callback_read = callbackContext; ReadThread readThread = new ReadThread( m_sockets.get(socketId),socketId,bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult( PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; */ } else { result = new PluginResult(PluginResult.Status.INVALID_ACTION); Log.d(LOG_TAG, "Invalid action : " + action + " passed"); } this.callbackContext.sendPluginResult(result); return true; }
From source file:com.phonegap.plugins.Firebase.CDVFirebase.java
License:Apache License
/** * Executes the request./*from ww w . j a v a 2s .c o m*/ * * This method is called from the Web. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); * * * @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. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult result = null; if (action.equals(INIT)) { mCallbackContext = callbackContext; init(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(SETPERSISTENCEENABLED)) { mCallbackContext = callbackContext; setPersistenceEnabled(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(READDATA)) { mCallbackContext = callbackContext; readData(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(READVALUETYPEEVENTWITHURL)) { mCallbackContext = callbackContext; readValueTypeEventWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(RETRIEVECHILDADDEDEVENTWITHURL)) { mCallbackContext = callbackContext; RetrieveChildAddedEventWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(RETRIEVECHILDCHANGEDEVENTWITHURL)) { mCallbackContext = callbackContext; RetrieveChildChangedEventWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(RETRIEVECHILDREMOVEDEVENTWITHURL)) { mCallbackContext = callbackContext; RetrieveChildRemovedEventWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(READDATAONCEWITHURL)) { mCallbackContext = callbackContext; readDataOnceWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(REMOVEALLCALLBACKSWITHURL)) { mCallbackContext = callbackContext; removeAllCallbacksWithURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(WRITEDATA)) { mCallbackContext = callbackContext; writeData(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(WRITEVALUETOURL)) { mCallbackContext = callbackContext; writeValueToURL(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(WRITEVALUETOURLWITHAUTOID)) { mCallbackContext = callbackContext; writeValueToURLWithAutoID(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(CHILDSET)) { mCallbackContext = callbackContext; childSet(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(AUTHWITHCUSTOMTOKEN)) { mCallbackContext = callbackContext; authWithCustomToken(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTSETVALUE)) { mCallbackContext = callbackContext; onDisconnectSetValue(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTSETVALUEWITHCOMPLETIONBLOCK)) { mCallbackContext = callbackContext; onDisconnectSetValueWithCompletionBlock(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTREMOVEVALUE)) { mCallbackContext = callbackContext; onDisconnectRemoveValue(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTREMOVEVALUEWITHCOMPLETIONBLOCK)) { mCallbackContext = callbackContext; onDisconnectRemoveValueWithCompletionBlock(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTUPDATECHILDVALUES)) { mCallbackContext = callbackContext; onDisconnectUpdateChildValues(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(ONDISCONNECTUPDATECHILDVALUESWITHCOMPLETIONBLOCK)) { mCallbackContext = callbackContext; onDisconnectUpdateChildValuesWithCompletionBlock(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(CANCELDISCONNECTOPERATIONS)) { mCallbackContext = callbackContext; cancelDisconnectOperations(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(CANCELDISCONNECTOPERATIONSWITHCOMPLETIONBLOCK)) { mCallbackContext = callbackContext; cancelDisconnectOperationsWithCompletionBlock(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYLIMITEDTONUMBEROFCHILDREN)) { mCallbackContext = callbackContext; queryLimitedToNumberOfChildren(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYLIMITEDTOFIRST)) { mCallbackContext = callbackContext; queryLimitedToFirst(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYLIMITEDTOLAST)) { mCallbackContext = callbackContext; queryLimitedToLast(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYORDEREDBYCHILD)) { mCallbackContext = callbackContext; queryOrderedByChild(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYORDEREDBYKEY)) { mCallbackContext = callbackContext; queryOrderedByKey(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYSTARTINGATVALUE)) { mCallbackContext = callbackContext; queryStartingAtValue(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYSTARTINGATVALUECHILDKEY)) { mCallbackContext = callbackContext; queryStartingAtValueChildKey(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYENDINGATVALUE)) { mCallbackContext = callbackContext; queryEndingAtValue(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYENDINGATVALUECHILDKEY)) { mCallbackContext = callbackContext; queryEndingAtValueChildKey(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYEQUALTOVALUE)) { mCallbackContext = callbackContext; queryEqualToValue(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYEQUALTOVALUECHILDKEY)) { mCallbackContext = callbackContext; queryEqualToValueChildKey(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(QUERYSEARCH)) { mCallbackContext = callbackContext; try { querySearch(args); } catch (JSONException e) { e.printStackTrace(); } result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else if (action.equals(USERLOGIN)) { mCallbackContext = callbackContext; userLogin(args); result = new PluginResult(Status.NO_RESULT); result.setKeepCallback(true); mCallbackContext.sendPluginResult(result); return true; } else { result = new PluginResult(Status.INVALID_ACTION, "No Plugin Function: " + action); mCallbackContext.sendPluginResult(result); return false; } }
From source file:com.phonegap.plugins.Firebase.CDVFirebase.java
License:Apache License
private void readData(JSONArray data) { ///*from www. j a v a2s. co m*/ String strURL = String.format("https://%s.firebaseio.com", appName); String path, child, value; final Firebase myRootRef = new Firebase(strURL); if (data.length() >= 1) { try { path = data.getString(0); child = data.getString(1); value = data.getString(2); } catch (JSONException e) { PluginResult pluginResult = new PluginResult(Status.ERROR, e.getMessage()); mCallbackContext.sendPluginResult(pluginResult); e.printStackTrace(); return; } } else { PluginResult pluginResult = new PluginResult(Status.ERROR, "readDataOnceWithURL : Parameter Error"); mCallbackContext.sendPluginResult(pluginResult); return; } Firebase myChildRef = myRootRef.child(path); Query query = myChildRef.orderByChild(child).equalTo(value); query.keepSynced(true); if (isUsed != true) isUsed = true; // Read data and react to changes query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { JSONObject resultObj; try { HashMap result = snapshot.getValue(HashMap.class); if (result == null) resultObj = new JSONObject(); else resultObj = new JSONObject(result); myRootRef.keepSynced(true); PluginResult pluginResult = new PluginResult(Status.OK, resultObj); pluginResult.setKeepCallback(true); mCallbackContext.sendPluginResult(pluginResult); } catch (Exception e) { PluginResult pluginResult = new PluginResult(Status.ERROR, e.getMessage()); mCallbackContext.sendPluginResult(pluginResult); e.printStackTrace(); } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The readData(addValueEventListener) failed: " + firebaseError.getMessage()); PluginResult pluginResult = new PluginResult(Status.ERROR, firebaseError.getMessage()); mCallbackContext.sendPluginResult(pluginResult); } }); }
From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java
License:Open Source License
private void fireRecognitionEvent(ArrayList<String> transcripts, float[] confidences) { JSONObject event = new JSONObject(); JSONArray results = new JSONArray(); try {/*from w w w . j a va 2s. c o m*/ for (int i = 0; i < transcripts.size(); i++) { JSONArray alternatives = new JSONArray(); JSONObject result = new JSONObject(); result.put("transcript", transcripts.get(i)); result.put("final", true); if (confidences != null) { result.put("confidence", confidences[i]); } alternatives.put(result); results.put(alternatives); } event.put("type", "result"); // event.put("emma", null); // event.put("interpretation", null); event.put("results", results); } catch (JSONException e) { // this will never happen } PluginResult pr = new PluginResult(PluginResult.Status.OK, event); pr.setKeepCallback(true); this.callbackContext.sendPluginResult(pr); }