From 891f8d00cf3f3b58f84014f51197fdb06ce30b9d Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Wed, 10 Oct 2012 14:11:13 -0400 Subject: [PATCH 01/17] Cleanups to CordovaPlugin. --- .../org/apache/cordova/api/CordovaPlugin.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/framework/src/org/apache/cordova/api/CordovaPlugin.java b/framework/src/org/apache/cordova/api/CordovaPlugin.java index 8a1da49f..18f3c558 100644 --- a/framework/src/org/apache/cordova/api/CordovaPlugin.java +++ b/framework/src/org/apache/cordova/api/CordovaPlugin.java @@ -33,27 +33,28 @@ public class CordovaPlugin { public CordovaInterface cordova; /** - * @param ctx The context of the main Activity. + * @param cordova The context of the main Activity. + * @param webView The associated CordovaWebView. */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { assert this.cordova == null; this.cordova = cordova; this.webView = webView; } - + /** * Executes the request. - * + * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); - * + * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * - * @param action The action to execute. - * @param rawArgs The exec() arguments in JSON form. - * @param callbackId The callback id used when calling back into JavaScript. - * @return Whether the action was valid. + * @param action The action to execute. + * @param rawArgs The exec() arguments in JSON form. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return Whether the action was valid. */ public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException { JSONArray args = new JSONArray(rawArgs); @@ -62,17 +63,17 @@ public class CordovaPlugin { /** * Executes the request. - * + * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); - * + * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * - * @param action The action to execute. - * @param args The exec() arguments. - * @param callbackId The callback id used when calling back into JavaScript. - * @return Whether the action was valid. + * @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, CallbackContext callbackContext) throws JSONException { return false; From e1dea5b4d3b12e7b5f62574d022a55d000d05464 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 10:02:46 -0400 Subject: [PATCH 02/17] Port AccelListener to CordovaPlugin. Also using the MessageQueue to handle the sensor start timeout, instead of a Thread.sleep() loop. This allows the listener to run synchronously. --- .../src/org/apache/cordova/AccelListener.java | 85 ++++++++++--------- 1 file changed, 47 insertions(+), 38 deletions(-) diff --git a/framework/src/org/apache/cordova/AccelListener.java b/framework/src/org/apache/cordova/AccelListener.java index df7181b5..47229671 100755 --- a/framework/src/org/apache/cordova/AccelListener.java +++ b/framework/src/org/apache/cordova/AccelListener.java @@ -20,8 +20,9 @@ package org.apache.cordova; import java.util.List; +import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -33,11 +34,14 @@ import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; +import android.os.Handler; +import android.os.Looper; + /** * This class listens to the accelerometer sensor and stores the latest * acceleration values x,y,z. */ -public class AccelListener extends Plugin implements SensorEventListener { +public class AccelListener extends CordovaPlugin implements SensorEventListener { public static int STOPPED = 0; public static int STARTING = 1; @@ -52,7 +56,7 @@ public class AccelListener extends Plugin implements SensorEventListener { private SensorManager sensorManager; // Sensor manager private Sensor mSensor; // Acceleration sensor returned by sensor manager - private String callbackId; // Keeps track of the single "start" callback ID passed in from JS + private CallbackContext callbackContext; // Keeps track of the JS callback context. /** * Create an accelerometer listener. @@ -70,29 +74,25 @@ public class AccelListener extends Plugin implements SensorEventListener { * get file paths associated with the Activity. * * @param cordova The context of the main Activity. + * @param webView The associated CordovaWebView. */ - - public void setContext(CordovaInterface cordova) { - super.setContext(cordova); + @Override + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE); } /** - * Executes the request and returns PluginResult. - * + * Executes the request. + * * @param action The action to execute. - * @param args JSONArry of arguments for the plugin. + * @param args The exec() arguments. * @param callbackId The callback id used when calling back into JavaScript. - * @return A PluginResult object with a status and message. + * @return Whether the action was valid. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.NO_RESULT; - String message = ""; - PluginResult result = new PluginResult(status, message); - result.setKeepCallback(true); - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("start")) { - this.callbackId = callbackId; + this.callbackContext = callbackContext; if (this.status != AccelListener.RUNNING) { // If not running, then this is an async call, so don't worry about waiting // We drop the callback onto our stack, call start, and let start and the sensor callback fire off the callback down the road @@ -105,9 +105,13 @@ public class AccelListener extends Plugin implements SensorEventListener { } } else { // Unsupported action - return new PluginResult(PluginResult.Status.INVALID_ACTION); + return false; } - return result; + + PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, ""); + result.setKeepCallback(true); + callbackContext.sendPluginResult(result); + return true; } /** @@ -148,21 +152,16 @@ public class AccelListener extends Plugin implements SensorEventListener { this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to."); return this.status; } - - // Wait until running - long timeout = 2000; - while ((this.status == STARTING) && (timeout > 0)) { - timeout = timeout - 100; - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - if (timeout == 0) { - this.setStatus(AccelListener.ERROR_FAILED_TO_START); - this.fail(AccelListener.ERROR_FAILED_TO_START, "Accelerometer could not be started."); - } + + // Set a timeout callback on the main thread. + Handler handler = new Handler(Looper.getMainLooper()); + handler.postDelayed(new Runnable() { + @Override + public void run() { + AccelListener.this.timeout(); + } + }, 2000); + return this.status; } @@ -177,6 +176,18 @@ public class AccelListener extends Plugin implements SensorEventListener { this.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE; } + /** + * Returns an error if the sensor hasn't started. + * + * Called two seconds after starting the listener. + */ + private void timeout() { + if (this.status == AccelListener.STARTING) { + this.setStatus(AccelListener.ERROR_FAILED_TO_START); + this.fail(AccelListener.ERROR_FAILED_TO_START, "Accelerometer could not be started."); + } + } + /** * Called when the accuracy of the sensor has changed. * @@ -247,16 +258,14 @@ public class AccelListener extends Plugin implements SensorEventListener { } PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj); err.setKeepCallback(true); - - this.error(err, this.callbackId); + callbackContext.sendPluginResult(err); } private void win() { // Success return object PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON()); result.setKeepCallback(true); - - this.success(result, this.callbackId); + callbackContext.sendPluginResult(result); } private void setStatus(int status) { From 10510484b5a9f9c7fb7f11a9a4c3f4992dd95a94 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 11:09:12 -0400 Subject: [PATCH 03/17] Port AudioHandler and AudioPlayer to CordovaPlugin. Had to adapt AudioPlayer because CordovaPlugin doesn't define sendJavascript. --- .../src/org/apache/cordova/AudioHandler.java | 42 +++++++++---------- .../src/org/apache/cordova/AudioPlayer.java | 34 +++++++-------- 2 files changed, 35 insertions(+), 41 deletions(-) diff --git a/framework/src/org/apache/cordova/AudioHandler.java b/framework/src/org/apache/cordova/AudioHandler.java index 9ee226ab..5872ddff 100644 --- a/framework/src/org/apache/cordova/AudioHandler.java +++ b/framework/src/org/apache/cordova/AudioHandler.java @@ -18,12 +18,14 @@ */ package org.apache.cordova; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; + import android.content.Context; import android.media.AudioManager; import java.util.ArrayList; -import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -40,7 +42,7 @@ import java.util.HashMap; * android_asset: file name must start with /android_asset/sound.mp3 * sdcard: file name is just sound.mp3 */ -public class AudioHandler extends Plugin { +public class AudioHandler extends CordovaPlugin { public static String TAG = "AudioHandler"; HashMap players; // Audio player object @@ -58,10 +60,10 @@ public class AudioHandler extends Plugin { * 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. + * @param callbackContext The callback context used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; @@ -91,11 +93,13 @@ public class AudioHandler extends Plugin { } } else if (action.equals("getCurrentPositionAudio")) { float f = this.getCurrentPositionAudio(args.getString(0)); - return new PluginResult(status, f); + callbackContext.sendPluginResult(new PluginResult(status, f)); + return true; } else if (action.equals("getDurationAudio")) { float f = this.getDurationAudio(args.getString(0), args.getString(1)); - return new PluginResult(status, f); + callbackContext.sendPluginResult(new PluginResult(status, f)); + return true; } else if (action.equals("create")) { String id = args.getString(0); @@ -105,28 +109,20 @@ public class AudioHandler extends Plugin { } else if (action.equals("release")) { boolean b = this.release(args.getString(0)); - return new PluginResult(status, b); + callbackContext.sendPluginResult(new PluginResult(status, b)); + return true; } - return new PluginResult(status, result); + else { // Unrecognized action. + return false; + } + + callbackContext.sendPluginResult(new PluginResult(status, result)); } catch (JSONException e) { e.printStackTrace(); - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } - } - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - if (action.equals("getCurrentPositionAudio")) { - return true; - } - else if (action.equals("getDurationAudio")) { - return true; - } - return false; + return true; } /** diff --git a/framework/src/org/apache/cordova/AudioPlayer.java b/framework/src/org/apache/cordova/AudioPlayer.java index c0d6b932..99dbb3d8 100644 --- a/framework/src/org/apache/cordova/AudioPlayer.java +++ b/framework/src/org/apache/cordova/AudioPlayer.java @@ -31,8 +31,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import org.apache.cordova.AudioPlayer.MODE; - /** * This class implements the audio playback and recording capabilities used by Cordova. * It is called by the AudioHandler Cordova class. @@ -135,7 +133,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On switch (this.mode) { case PLAY: Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode."); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); break; case NONE: this.audioFile = file; @@ -153,11 +151,11 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On } catch (IOException e) { e.printStackTrace(); } - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); break; case RECORD: Log.d(LOG_TAG, "AudioPlayer Error: Already recording."); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); } } @@ -223,7 +221,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On if (this.readyPlayer(this.audioFile)) { this.player.seekTo(milliseconds); Log.d(LOG_TAG, "Send a onStatus update for the new seek"); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + milliseconds / 1000.0f + ");"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + milliseconds / 1000.0f + ");"); } else { this.seekOnPrepared = milliseconds; @@ -242,7 +240,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On } else { Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal()); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});"); } } @@ -258,7 +256,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On } else { Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal()); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});"); } } @@ -280,7 +278,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On public long getCurrentPosition() { if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) { int curPos = this.player.getCurrentPosition(); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + curPos / 1000.0f + ");"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + curPos / 1000.0f + ");"); return curPos; } else { @@ -359,7 +357,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On this.prepareOnly = true; // Send status notification to JavaScript - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_DURATION + "," + this.duration + ");"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_DURATION + "," + this.duration + ");"); } /** @@ -387,7 +385,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On this.player.release(); // Send error notification to JavaScript - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":" + arg1 + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":" + arg1 + "});"); return false; } @@ -398,7 +396,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On */ private void setState(STATE state) { if (this.state != state) { - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + state.ordinal() + ");"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + state.ordinal() + ");"); } this.state = state; } @@ -411,7 +409,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On private void setMode(MODE mode) { if (this.mode != mode) { //mode is not part of the expected behavior, so no notification - //this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");"); + //this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");"); } this.mode = mode; } @@ -447,7 +445,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On break; case RECORD: Log.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode."); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); return false; //player is not ready } return true; @@ -468,7 +466,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On try { this.loadAudioFile(file); } catch (Exception e) { - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); } return false; case MEDIA_LOADING: @@ -493,14 +491,14 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On try { this.loadAudioFile(file); } catch (Exception e) { - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); } //if we had to prepare= the file, we won't be in the correct state for playback return false; } default: Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state); - this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); + this.handler.webView.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});"); } } return false; @@ -526,7 +524,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On else { if (file.startsWith("/android_asset/")) { String f = file.substring(15); - android.content.res.AssetFileDescriptor fd = this.handler.ctx.getActivity().getAssets().openFd(f); + android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f); this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); } else { From 076bfcde87e223bc907e20ce44ee602990e405a7 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 11:21:02 -0400 Subject: [PATCH 04/17] Port BatteryListener to CordovaPlugin. --- .../org/apache/cordova/BatteryListener.java | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/framework/src/org/apache/cordova/BatteryListener.java b/framework/src/org/apache/cordova/BatteryListener.java index 4476cc3c..85558c2a 100755 --- a/framework/src/org/apache/cordova/BatteryListener.java +++ b/framework/src/org/apache/cordova/BatteryListener.java @@ -18,7 +18,8 @@ */ package org.apache.cordova; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -30,13 +31,13 @@ import android.content.Intent; import android.content.IntentFilter; import android.util.Log; -public class BatteryListener extends Plugin { +public class BatteryListener extends CordovaPlugin { private static final String LOG_TAG = "BatteryManager"; BroadcastReceiver receiver; - private String batteryCallbackId = null; + private CallbackContext batteryCallbackContext = null; /** * Constructor. @@ -46,22 +47,20 @@ public class BatteryListener extends Plugin { } /** - * Executes the request and returns PluginResult. + * Executes the request. * - * @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. + * @param action The action to execute. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return True if the action was valid, false if not. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.INVALID_ACTION; - String result = "Unsupported Operation: " + action; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("start")) { - if (this.batteryCallbackId != null) { - return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running."); + if (this.batteryCallbackContext != null) { + callbackContext.error( "Battery listener already running."); + return true; } - this.batteryCallbackId = callbackId; + this.batteryCallbackContext = callbackContext; // We need to listen to power events to update battery status IntentFilter intentFilter = new IntentFilter(); @@ -79,17 +78,19 @@ public class BatteryListener extends Plugin { // Don't return any result now, since status results will be sent when events come in from broadcast receiver PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); - return pluginResult; + callbackContext.sendPluginResult(pluginResult); + return true; } else if (action.equals("stop")) { removeBatteryListener(); this.sendUpdate(new JSONObject(), false); // release status callback in JS side - this.batteryCallbackId = null; - return new PluginResult(PluginResult.Status.OK); + this.batteryCallbackContext = null; + callbackContext.success(); + return true; } - return new PluginResult(status, result); + return false; } /** @@ -153,10 +154,10 @@ public class BatteryListener extends Plugin { * @param connection the network info to set as navigator.connection */ private void sendUpdate(JSONObject info, boolean keepCallback) { - if (this.batteryCallbackId != null) { + if (this.batteryCallbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, info); result.setKeepCallback(keepCallback); - this.success(result, this.batteryCallbackId); + this.batteryCallbackContext.sendPluginResult(result); } } } From 205215d409c4f75e958a9c09c0b4a38bd9a859ac Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 11:34:46 -0400 Subject: [PATCH 05/17] Port CameraLauncher to CordovaPlugin. --- .../org/apache/cordova/CameraLauncher.java | 55 ++++++++++--------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/framework/src/org/apache/cordova/CameraLauncher.java b/framework/src/org/apache/cordova/CameraLauncher.java index efb14fc8..59e9f212 100755 --- a/framework/src/org/apache/cordova/CameraLauncher.java +++ b/framework/src/org/apache/cordova/CameraLauncher.java @@ -27,8 +27,9 @@ import java.io.IOException; import java.io.OutputStream; import org.apache.commons.codec.binary.Base64; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.LOG; -import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -53,7 +54,7 @@ import android.util.Log; * and returns the captured image. When the camera view is closed, the screen displayed before * the camera view was shown is redisplayed. */ -public class CameraLauncher extends Plugin implements MediaScannerConnectionClient { +public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectionClient { private static final int DATA_URL = 0; // Return base64 encoded string private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android) @@ -82,9 +83,9 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie private int mediaType; // What type of media to retrieve private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album private boolean correctOrientation; // Should the pictures orientation be corrected - private boolean allowEdit; // Should we allow the user to crop the image + //private boolean allowEdit; // Should we allow the user to crop the image. UNUSED. - public String callbackId; + public CallbackContext callbackContext; private int numPics; private MediaScannerConnection conn; // Used to update gallery app with newly-written files @@ -110,15 +111,13 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie /** * 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. + * @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 A PluginResult object with a status and message. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - this.callbackId = callbackId; + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + this.callbackContext = callbackContext; try { if (action.equals("takePicture")) { @@ -138,7 +137,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie this.targetHeight = args.getInt(4); this.encodingType = args.getInt(5); this.mediaType = args.getInt(6); - this.allowEdit = args.getBoolean(7); + //this.allowEdit = args.getBoolean(7); // This field is unused. this.correctOrientation = args.getBoolean(8); this.saveToPhotoAlbum = args.getBoolean(9); @@ -159,12 +158,14 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie } PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); r.setKeepCallback(true); - return r; + callbackContext.sendPluginResult(r); + return true; } - return new PluginResult(status, result); + return false; } catch (JSONException e) { e.printStackTrace(); - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); + return true; } } @@ -199,7 +200,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie this.imageUri = Uri.fromFile(photo); if (this.cordova != null) { - this.cordova.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1); + this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1); } // else // LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity"); @@ -251,7 +252,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie intent.setAction(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); if (this.cordova != null) { - this.cordova.startActivityForResult((Plugin) this, Intent.createChooser(intent, + this.cordova.startActivityForResult((CordovaPlugin) this, Intent.createChooser(intent, new String(title)), (srcType + 1) * 16 + returnType + 1); } } @@ -319,7 +320,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && rotate == 0) { writeUncompressedImage(uri); - this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); + this.callbackContext.success(uri.toString()); } else { bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString())); @@ -346,7 +347,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie } // Send Uri back to JavaScript for viewing image - this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); + this.callbackContext.success(uri.toString()); } this.cleanup(FILE_URI, this.imageUri, uri, bitmap); @@ -377,14 +378,14 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie // If you ask for video or all media type you will automatically get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { - this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); + this.callbackContext.success(uri.toString()); } else { // This is a special case to just return the path as no scaling, // rotating or compression needs to be done if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && destType == FILE_URI && !this.correctOrientation) { - this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); + this.callbackContext.success(uri.toString()); } else { // Get the path to the image. Makes loading so much easier. String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova); @@ -456,14 +457,14 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie // The resized image is cached by the app in order to get around this and not have to delete you // application cache I'm adding the current system time to the end of the file url. - this.success(new PluginResult(PluginResult.Status.OK, ("file://" + resizePath + "?" + System.currentTimeMillis())), this.callbackId); + this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } else { - this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); + this.callbackContext.success(uri.toString()); } } if (bitmap != null) { @@ -732,7 +733,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encodeBase64(code); String js_out = new String(output); - this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId); + this.callbackContext.success(js_out); js_out = null; output = null; code = null; @@ -749,7 +750,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie * @param err */ public void failPicture(String err) { - this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId); + this.callbackContext.error(err); } private void scanForGallery(Uri newImage) { @@ -757,7 +758,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie if(this.conn != null) { this.conn.disconnect(); } - this.conn = new MediaScannerConnection(this.ctx.getActivity().getApplicationContext(), this); + this.conn = new MediaScannerConnection(this.cordova.getActivity().getApplicationContext(), this); conn.connect(); } From fa15763c5dc1432d35bea8ede89f87a75618096e Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 15:50:04 -0400 Subject: [PATCH 06/17] Port Capture to use CordovaPlugin. Untested beyond compiling! --- framework/src/org/apache/cordova/Capture.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/framework/src/org/apache/cordova/Capture.java b/framework/src/org/apache/cordova/Capture.java index d84c6268..1e03d7b3 100644 --- a/framework/src/org/apache/cordova/Capture.java +++ b/framework/src/org/apache/cordova/Capture.java @@ -23,8 +23,9 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.LOG; -import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -41,7 +42,7 @@ import android.os.Environment; import android.provider.MediaStore; import android.util.Log; -public class Capture extends Plugin { +public class Capture extends CordovaPlugin { private static final String VIDEO_3GPP = "video/3gpp"; private static final String VIDEO_MP4 = "video/mp4"; @@ -57,13 +58,11 @@ public class Capture extends Plugin { // private static final int CAPTURE_APPLICATION_BUSY = 1; // private static final int CAPTURE_INVALID_ARGUMENT = 2; private static final int CAPTURE_NO_MEDIA_FILES = 3; - private static final int CAPTURE_NOT_SUPPORTED = 20; - private String callbackId; // The ID of the callback to be invoked with our result + private CallbackContext callbackContext; // The callback context from which we were invoked. private long limit; // the number of pics/vids/clips to take private double duration; // optional duration parameter for video recording private JSONArray results; // The array of results to be returned to the user - private Uri imageUri; // Uri of captured image private int numPics; // Number of pictures before capture activity //private CordovaInterface cordova; @@ -77,8 +76,8 @@ public class Capture extends Plugin { // } @Override - public PluginResult execute(String action, JSONArray args, String callbackId) { - this.callbackId = callbackId; + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { + this.callbackContext = callbackContext; this.limit = 1; this.duration = 0.0f; this.results = new JSONArray(); @@ -92,10 +91,11 @@ public class Capture extends Plugin { if (action.equals("getFormatData")) { try { JSONObject obj = getFormatData(args.getString(0), args.getString(1)); - return new PluginResult(PluginResult.Status.OK, obj); + callbackContext.success(obj); } catch (JSONException e) { - return new PluginResult(PluginResult.Status.ERROR); + callbackContext.error(""); } + return true; } else if (action.equals("captureAudio")) { this.captureAudio(); @@ -106,10 +106,11 @@ public class Capture extends Plugin { else if (action.equals("captureVideo")) { this.captureVideo(duration); } + else { + return false; + } - PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); - r.setKeepCallback(true); - return r; + return true; } /** @@ -199,7 +200,7 @@ public class Capture extends Plugin { private void captureAudio() { Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION); - this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_AUDIO); + this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_AUDIO); } /** @@ -214,9 +215,8 @@ public class Capture extends Plugin { // Specify file so that large image is captured and returned File photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), "Capture.jpg"); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); - this.imageUri = Uri.fromFile(photo); - this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_IMAGE); + this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_IMAGE); } /** @@ -227,7 +227,7 @@ public class Capture extends Plugin { // Introduced in API 8 //intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration); - this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO); + this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_VIDEO); } /** @@ -252,7 +252,7 @@ public class Capture extends Plugin { if (results.length() >= limit) { // Send Uri back to JavaScript for listening to audio - this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results)); } else { // still need to capture more audio clips captureAudio(); @@ -298,7 +298,7 @@ public class Capture extends Plugin { if (results.length() >= limit) { // Send Uri back to JavaScript for viewing image - this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results)); } else { // still need to capture more images captureImage(); @@ -315,7 +315,7 @@ public class Capture extends Plugin { if (results.length() >= limit) { // Send Uri back to JavaScript for viewing video - this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results)); } else { // still need to capture more video clips captureVideo(duration); @@ -326,7 +326,7 @@ public class Capture extends Plugin { else if (resultCode == Activity.RESULT_CANCELED) { // If we have partial results send them back to the user if (results.length() > 0) { - this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results)); } // user canceled the action else { @@ -337,7 +337,7 @@ public class Capture extends Plugin { else { // If we have partial results send them back to the user if (results.length() > 0) { - this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); + this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results)); } // something bad happened else { @@ -401,7 +401,7 @@ public class Capture extends Plugin { * @param err */ public void fail(JSONObject err) { - this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId); + this.callbackContext.error(err); } From fe0876ded6a93401a8df6ba1dab459d97fdf22f4 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 15:50:31 -0400 Subject: [PATCH 07/17] Port CompassListener to CordovaPlugin. --- .../org/apache/cordova/CompassListener.java | 94 ++++++++----------- 1 file changed, 40 insertions(+), 54 deletions(-) diff --git a/framework/src/org/apache/cordova/CompassListener.java b/framework/src/org/apache/cordova/CompassListener.java index 458afaf4..e3a7c596 100755 --- a/framework/src/org/apache/cordova/CompassListener.java +++ b/framework/src/org/apache/cordova/CompassListener.java @@ -20,8 +20,9 @@ package org.apache.cordova; import java.util.List; +import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -33,12 +34,13 @@ import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.content.Context; -import android.util.Log; +import android.os.Handler; +import android.os.Looper; /** * This class listens to the compass sensor and stores the latest heading value. */ -public class CompassListener extends Plugin implements SensorEventListener { +public class CompassListener extends CordovaPlugin implements SensorEventListener { public static int STOPPED = 0; public static int STARTING = 1; @@ -56,6 +58,8 @@ public class CompassListener extends Plugin implements SensorEventListener { private SensorManager sensorManager;// Sensor manager Sensor mSensor; // Compass sensor returned by sensor manager + private CallbackContext callbackContext; + /** * Constructor. */ @@ -70,24 +74,22 @@ public class CompassListener extends Plugin implements SensorEventListener { * get file paths associated with the Activity. * * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. */ - public void setContext(CordovaInterface cordova) { - super.setContext(cordova); + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE); } /** * 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. + * @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. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("start")) { this.start(); @@ -97,68 +99,42 @@ public class CompassListener extends Plugin implements SensorEventListener { } else if (action.equals("getStatus")) { int i = this.getStatus(); - return new PluginResult(status, i); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i)); } else if (action.equals("getHeading")) { // If not running, then this is an async call, so don't worry about waiting if (this.status != CompassListener.RUNNING) { int r = this.start(); if (r == CompassListener.ERROR_FAILED_TO_START) { - return new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START)); + return true; } - // Wait until running - long timeout = 2000; - while ((this.status == STARTING) && (timeout > 0)) { - timeout = timeout - 100; - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); + // Set a timeout callback on the main thread. + Handler handler = new Handler(Looper.getMainLooper()); + handler.postDelayed(new Runnable() { + @Override + public void run() { + CompassListener.this.timeout(); } - } - if (timeout == 0) { - return new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START); - } + }, 2000); } - return new PluginResult(status, getCompassHeading()); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getCompassHeading())); } else if (action.equals("setTimeout")) { this.setTimeout(args.getLong(0)); } else if (action.equals("getTimeout")) { long l = this.getTimeout(); - return new PluginResult(status, l); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l)); } else { // Unsupported action - return new PluginResult(PluginResult.Status.INVALID_ACTION); + return false; } - return new PluginResult(status, result); } catch (JSONException e) { e.printStackTrace(); - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } - } - - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - if (action.equals("getStatus")) { - return true; - } - else if (action.equals("getHeading")) { - // Can only return value if RUNNING - if (this.status == CompassListener.RUNNING) { - return true; - } - } - else if (action.equals("getTimeout")) { - return true; - } - return false; + return true; } /** @@ -225,6 +201,16 @@ public class CompassListener extends Plugin implements SensorEventListener { // TODO Auto-generated method stub } + /** + * Called after a delay to time out if the listener has not attached fast enough. + */ + private void timeout() { + if (this.status == CompassListener.STARTING) { + this.setStatus(CompassListener.ERROR_FAILED_TO_START); + this.callbackContext.error("Compass listener failed to start."); + } + } + /** * Sensor listener event. * From d72a8cbf8954aae7a868112d74b55c8a1dac23a4 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 16:03:49 -0400 Subject: [PATCH 08/17] Port Contacts to CordovaPlugin. --- .../org/apache/cordova/ContactManager.java | 35 ++++++++++--------- .../apache/cordova/api/CallbackContext.java | 13 ++++++- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/framework/src/org/apache/cordova/ContactManager.java b/framework/src/org/apache/cordova/ContactManager.java index 31b5452f..a47f3d11 100755 --- a/framework/src/org/apache/cordova/ContactManager.java +++ b/framework/src/org/apache/cordova/ContactManager.java @@ -18,14 +18,15 @@ */ package org.apache.cordova; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; -public class ContactManager extends Plugin { +public class ContactManager extends CordovaPlugin { private ContactAccessor contactAccessor; private static final String LOG_TAG = "Contact Query"; @@ -47,21 +48,19 @@ public class ContactManager extends Plugin { /** * 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. + * @param action The action to execute. + * @param args JSONArray of arguments for the plugin. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return True if the action was valid, false otherwise. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { /** * Check to see if we are on an Android 1.X device. If we are return an error as we * do not support this as of Cordova 1.0. */ if (android.os.Build.VERSION.RELEASE.startsWith("1.")) { - return new PluginResult(PluginResult.Status.ERROR, ContactManager.NOT_SUPPORTED_ERROR); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, ContactManager.NOT_SUPPORTED_ERROR)); + return true; } /** @@ -75,27 +74,29 @@ public class ContactManager extends Plugin { try { if (action.equals("search")) { JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); - return new PluginResult(status, res); + callbackContext.success(res); } else if (action.equals("save")) { String id = contactAccessor.save(args.getJSONObject(0)); if (id != null) { JSONObject res = contactAccessor.getContactById(id); if (res != null) { - return new PluginResult(status, res); + callbackContext.success(res); } } } else if (action.equals("remove")) { if (contactAccessor.remove(args.getString(0))) { - return new PluginResult(status, result); + callbackContext.success(); } } - // If we get to this point an error has occurred - return new PluginResult(PluginResult.Status.ERROR, ContactManager.UNKNOWN_ERROR); + else { + return false; + } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } + return true; } } diff --git a/framework/src/org/apache/cordova/api/CallbackContext.java b/framework/src/org/apache/cordova/api/CallbackContext.java index c9dc9d7a..c098d405 100644 --- a/framework/src/org/apache/cordova/api/CallbackContext.java +++ b/framework/src/org/apache/cordova/api/CallbackContext.java @@ -1,5 +1,7 @@ package org.apache.cordova.api; +import org.json.JSONArray; + import android.util.Log; import org.apache.cordova.CordovaWebView; @@ -60,6 +62,15 @@ public class CallbackContext { sendPluginResult(new PluginResult(PluginResult.Status.OK, message)); } + /** + * Helper for success callbacks that just returns the Status.OK by default + * + * @param message The message to add to the success result. + */ + public void success(JSONArray message) { + sendPluginResult(new PluginResult(PluginResult.Status.OK, message)); + } + /** * Helper for success callbacks that just returns the Status.OK by default * @@ -87,4 +98,4 @@ public class CallbackContext { public void error(String message) { sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message)); } -} \ No newline at end of file +} From dd8533a320e06d951b7aa01845bc88a48ebc5ae0 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 16:11:20 -0400 Subject: [PATCH 09/17] Port Device to use CordovaPlugin. --- framework/src/org/apache/cordova/Device.java | 45 ++++++++------------ 1 file changed, 17 insertions(+), 28 deletions(-) diff --git a/framework/src/org/apache/cordova/Device.java b/framework/src/org/apache/cordova/Device.java index b130fd52..08217329 100644 --- a/framework/src/org/apache/cordova/Device.java +++ b/framework/src/org/apache/cordova/Device.java @@ -20,9 +20,10 @@ package org.apache.cordova; import java.util.TimeZone; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.LOG; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -35,7 +36,7 @@ import android.content.IntentFilter; import android.provider.Settings; import android.telephony.TelephonyManager; -public class Device extends Plugin { +public class Device extends CordovaPlugin { public static final String TAG = "Device"; public static String cordovaVersion = "2.1.0"; // Cordova version @@ -55,9 +56,10 @@ public class Device extends Plugin { * get file paths associated with the Activity. * * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. */ - public void setContext(CordovaInterface cordova) { - super.setContext(cordova); + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); Device.uuid = getUuid(); this.initTelephonyReceiver(); } @@ -65,15 +67,12 @@ public class Device extends Plugin { /** * 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. + * @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 if not. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("getDeviceInfo")) { JSONObject r = new JSONObject(); @@ -85,25 +84,15 @@ public class Device extends Plugin { //JSONObject pg = new JSONObject(); //pg.put("version", Device.CordovaVersion); //r.put("cordova", pg); - return new PluginResult(status, r); + callbackContext.success(r); + } + else { + return false; } - return new PluginResult(status, result); } catch (JSONException e) { - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } - } - - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - if (action.equals("getDeviceInfo")) { - return true; - } - return false; + return true; } /** From b582e1592a0ac61321036393b606d20dad9b6d08 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 16:29:02 -0400 Subject: [PATCH 10/17] Port FileUtils to CordovaPlugin. --- .../src/org/apache/cordova/FileUtils.java | 97 +++++++++---------- .../apache/cordova/api/CallbackContext.java | 10 ++ 2 files changed, 58 insertions(+), 49 deletions(-) diff --git a/framework/src/org/apache/cordova/FileUtils.java b/framework/src/org/apache/cordova/FileUtils.java index cbeff98a..7d5e5a14 100755 --- a/framework/src/org/apache/cordova/FileUtils.java +++ b/framework/src/org/apache/cordova/FileUtils.java @@ -25,8 +25,9 @@ import java.net.URLDecoder; import java.nio.channels.FileChannel; import org.apache.commons.codec.binary.Base64; +import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.file.EncodingException; import org.apache.cordova.file.FileExistsException; @@ -50,7 +51,7 @@ import android.webkit.MimeTypeMap; * This class provides SD card file and directory services to JavaScript. * Only files on the SD card can be accessed. */ -public class FileUtils extends Plugin { +public class FileUtils extends CordovaPlugin { @SuppressWarnings("unused") private static final String LOG_TAG = "FileUtils"; private static final String _DATA = "_data"; // The column name where the file path is stored @@ -84,83 +85,78 @@ public class FileUtils extends Plugin { } /** - * Executes the request and returns PluginResult. + * Executes the request and returns whether the action was valid. * * @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. + * @param args JSONArry of arguments for the plugin. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return True if the action was valid, false otherwise. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - //System.out.println("FileUtils.execute("+action+")"); - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("testSaveLocationExists")) { boolean b = DirectoryManager.testSaveLocationExists(); - return new PluginResult(status, b); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); } else if (action.equals("getFreeDiskSpace")) { long l = DirectoryManager.getFreeDiskSpace(false); - return new PluginResult(status, l); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l)); } else if (action.equals("testFileExists")) { boolean b = DirectoryManager.testFileExists(args.getString(0)); - return new PluginResult(status, b); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); } else if (action.equals("testDirectoryExists")) { boolean b = DirectoryManager.testFileExists(args.getString(0)); - return new PluginResult(status, b); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); } else if (action.equals("readAsText")) { String s = this.readAsText(args.getString(0), args.getString(1)); - return new PluginResult(status, s); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, s)); } else if (action.equals("readAsDataURL")) { String s = this.readAsDataURL(args.getString(0)); - return new PluginResult(status, s); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, s)); } else if (action.equals("write")) { long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2)); - return new PluginResult(status, fileSize); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize)); } else if (action.equals("truncate")) { long fileSize = this.truncateFile(args.getString(0), args.getLong(1)); - return new PluginResult(status, fileSize); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize)); } else if (action.equals("requestFileSystem")) { long size = args.optLong(1); - if (size != 0) { - if (size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR); - } + if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR)); + } else { + JSONObject obj = requestFileSystem(args.getInt(0)); + callbackContext.success(obj); } - JSONObject obj = requestFileSystem(args.getInt(0)); - return new PluginResult(status, obj); } else if (action.equals("resolveLocalFileSystemURI")) { JSONObject obj = resolveLocalFileSystemURI(args.getString(0)); - return new PluginResult(status, obj); + callbackContext.success(obj); } else if (action.equals("getMetadata")) { - return new PluginResult(status, getMetadata(args.getString(0))); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getMetadata(args.getString(0)))); } else if (action.equals("getFileMetadata")) { JSONObject obj = getFileMetadata(args.getString(0)); - return new PluginResult(status, obj); + callbackContext.success(obj); } else if (action.equals("getParent")) { JSONObject obj = getParent(args.getString(0)); - return new PluginResult(status, obj); + callbackContext.success(obj); } else if (action.equals("getDirectory")) { JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), true); - return new PluginResult(status, obj); + callbackContext.success(obj); } else if (action.equals("getFile")) { JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), false); - return new PluginResult(status, obj); + callbackContext.success(obj); } else if (action.equals("remove")) { boolean success; @@ -169,51 +165,54 @@ public class FileUtils extends Plugin { if (success) { notifyDelete(args.getString(0)); - return new PluginResult(status); + callbackContext.success(); } else { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); } } else if (action.equals("removeRecursively")) { boolean success = removeRecursively(args.getString(0)); if (success) { - return new PluginResult(status); + callbackContext.success(); } else { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); } } else if (action.equals("moveTo")) { JSONObject entry = transferTo(args.getString(0), args.getString(1), args.getString(2), true); - return new PluginResult(status, entry); + callbackContext.success(entry); } else if (action.equals("copyTo")) { JSONObject entry = transferTo(args.getString(0), args.getString(1), args.getString(2), false); - return new PluginResult(status, entry); + callbackContext.success(entry); } else if (action.equals("readEntries")) { JSONArray entries = readEntries(args.getString(0)); - return new PluginResult(status, entries); + callbackContext.success(entries); + } + else { + return false; } - return new PluginResult(status, result); } catch (FileNotFoundException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR); + callbackContext.error(FileUtils.NOT_FOUND_ERR); } catch (FileExistsException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.PATH_EXISTS_ERR); + callbackContext.error(FileUtils.PATH_EXISTS_ERR); } catch (NoModificationAllowedException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); } catch (JSONException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); + callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR); } catch (InvalidModificationException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.INVALID_MODIFICATION_ERR); + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); } catch (MalformedURLException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.ENCODING_ERR); + callbackContext.error(FileUtils.ENCODING_ERR); } catch (IOException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.INVALID_MODIFICATION_ERR); + callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR); } catch (EncodingException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.ENCODING_ERR); + callbackContext.error(FileUtils.ENCODING_ERR); } catch (TypeMismatchException e) { - return new PluginResult(PluginResult.Status.ERROR, FileUtils.TYPE_MISMATCH_ERR); + callbackContext.error(FileUtils.TYPE_MISMATCH_ERR); } + return true; } /** @@ -223,7 +222,7 @@ public class FileUtils extends Plugin { */ private void notifyDelete(String filePath) { String newFilePath = stripFileProtocol(filePath); - int result = this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + " = ?", new String[] { newFilePath }); } diff --git a/framework/src/org/apache/cordova/api/CallbackContext.java b/framework/src/org/apache/cordova/api/CallbackContext.java index c098d405..86cc813c 100644 --- a/framework/src/org/apache/cordova/api/CallbackContext.java +++ b/framework/src/org/apache/cordova/api/CallbackContext.java @@ -98,4 +98,14 @@ public class CallbackContext { public void error(String message) { sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message)); } + + /** + * Helper for error callbacks that just returns the Status.ERROR by default + * + * @param message The message to add to the error result. + * @param callbackId The callback id used when calling back into JavaScript. + */ + public void error(int message) { + sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message)); + } } From d81727a08cea2b6bd5ac8d12f9fc1694b5002c94 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 18:26:19 -0400 Subject: [PATCH 11/17] Port Location listeners and plugin to CordovaPlugin. --- .../cordova/CordovaLocationListener.java | 33 +++-- .../src/org/apache/cordova/GeoBroker.java | 114 +++++++++--------- 2 files changed, 70 insertions(+), 77 deletions(-) diff --git a/framework/src/org/apache/cordova/CordovaLocationListener.java b/framework/src/org/apache/cordova/CordovaLocationListener.java index 0ad441d6..7b7a9f77 100755 --- a/framework/src/org/apache/cordova/CordovaLocationListener.java +++ b/framework/src/org/apache/cordova/CordovaLocationListener.java @@ -22,7 +22,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Map; + +import org.apache.cordova.api.CallbackContext; import android.location.Location; import android.location.LocationListener; @@ -39,8 +40,8 @@ public class CordovaLocationListener implements LocationListener { private GeoBroker owner; protected boolean running = false; - public HashMap watches = new HashMap(); - private List callbacks = new ArrayList(); + public HashMap watches = new HashMap(); + private List callbacks = new ArrayList(); private String TAG = "[Cordova Location Listener]"; @@ -51,9 +52,9 @@ public class CordovaLocationListener implements LocationListener { } protected void fail(int code, String message) { - for (String callbackId: this.callbacks) + for (CallbackContext callbackContext: this.callbacks) { - this.owner.fail(code, message, callbackId); + this.owner.fail(code, message, callbackContext); } if(this.owner.isGlobalListener(this)) { @@ -62,17 +63,16 @@ public class CordovaLocationListener implements LocationListener { } this.callbacks.clear(); - Iterator it = this.watches.entrySet().iterator(); + Iterator it = this.watches.values().iterator(); while (it.hasNext()) { - Map.Entry pairs = (Map.Entry)it.next(); - this.owner.fail(code, message, (String)pairs.getValue()); + this.owner.fail(code, message, it.next()); } } private void win(Location loc) { - for (String callbackId: this.callbacks) + for (CallbackContext callbackContext: this.callbacks) { - this.owner.win(loc, callbackId); + this.owner.win(loc, callbackContext); } if(this.owner.isGlobalListener(this)) { @@ -81,10 +81,9 @@ public class CordovaLocationListener implements LocationListener { } this.callbacks.clear(); - Iterator it = this.watches.entrySet().iterator(); + Iterator it = this.watches.values().iterator(); while (it.hasNext()) { - Map.Entry pairs = (Map.Entry)it.next(); - this.owner.win(loc, (String)pairs.getValue()); + this.owner.win(loc, it.next()); } } @@ -150,14 +149,14 @@ public class CordovaLocationListener implements LocationListener { return this.watches.size() + this.callbacks.size(); } - public void addWatch(String timerId, String callbackId) { - this.watches.put(timerId, callbackId); + public void addWatch(String timerId, CallbackContext callbackContext) { + this.watches.put(timerId, callbackContext); if (this.size() == 1) { this.start(); } } - public void addCallback(String callbackId) { - this.callbacks.add(callbackId); + public void addCallback(CallbackContext callbackContext) { + this.callbacks.add(callbackContext); if (this.size() == 1) { this.start(); } diff --git a/framework/src/org/apache/cordova/GeoBroker.java b/framework/src/org/apache/cordova/GeoBroker.java index e6798a99..6bda653c 100755 --- a/framework/src/org/apache/cordova/GeoBroker.java +++ b/framework/src/org/apache/cordova/GeoBroker.java @@ -18,7 +18,8 @@ */ package org.apache.cordova; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -34,7 +35,7 @@ import android.location.LocationManager; * This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener */ -public class GeoBroker extends Plugin { +public class GeoBroker extends CordovaPlugin { private GPSListener gpsListener; private NetworkListener networkListener; private LocationManager locationManager; @@ -49,53 +50,57 @@ public class GeoBroker extends Plugin { * 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. + * @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, or false if not. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (this.locationManager == null) { this.locationManager = (LocationManager) this.cordova.getActivity().getSystemService(Context.LOCATION_SERVICE); this.networkListener = new NetworkListener(this.locationManager, this); this.gpsListener = new GPSListener(this.locationManager, this); } - + PluginResult.Status status = PluginResult.Status.NO_RESULT; String message = "Location API is not available for this device."; PluginResult result = new PluginResult(status, message); - + if ( locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) || - locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER )) { - - result.setKeepCallback(true); - - try { - if (action.equals("getLocation")) { - boolean enableHighAccuracy = args.getBoolean(0); - int maximumAge = args.getInt(1); - Location last = this.locationManager.getLastKnownLocation((enableHighAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER)); - // Check if we can use lastKnownLocation to get a quick reading and use less battery - if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) { - result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last)); - } else { - this.getCurrentLocation(callbackId, enableHighAccuracy); - } - } - else if (action.equals("addWatch")) { - String id = args.getString(0); - boolean enableHighAccuracy = args.getBoolean(1); - this.addWatch(id, callbackId, enableHighAccuracy); - } - else if (action.equals("clearWatch")) { - String id = args.getString(0); - this.clearWatch(id); - } - } catch (JSONException e) { - result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); - } + locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER )) { + + result.setKeepCallback(true); + + try { + if (action.equals("getLocation")) { + boolean enableHighAccuracy = args.getBoolean(0); + int maximumAge = args.getInt(1); + Location last = this.locationManager.getLastKnownLocation((enableHighAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER)); + // Check if we can use lastKnownLocation to get a quick reading and use less battery + if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) { + result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last)); + } else { + this.getCurrentLocation(callbackContext, enableHighAccuracy); + } + } + else if (action.equals("addWatch")) { + String id = args.getString(0); + boolean enableHighAccuracy = args.getBoolean(1); + this.addWatch(id, callbackContext, enableHighAccuracy); + } + else if (action.equals("clearWatch")) { + String id = args.getString(0); + this.clearWatch(id); + } + else { + return false; + } + } catch (JSONException e) { + result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); + } } - return result; - + callbackContext.sendPluginResult(result); + return true; + } private void clearWatch(String id) { @@ -103,33 +108,22 @@ public class GeoBroker extends Plugin { this.networkListener.clearWatch(id); } - private void getCurrentLocation(String callbackId, boolean enableHighAccuracy) { + private void getCurrentLocation(CallbackContext callbackContext, boolean enableHighAccuracy) { if (enableHighAccuracy) { - this.gpsListener.addCallback(callbackId); + this.gpsListener.addCallback(callbackContext); } else { - this.networkListener.addCallback(callbackId); + this.networkListener.addCallback(callbackContext); } } - private void addWatch(String timerId, String callbackId, boolean enableHighAccuracy) { + private void addWatch(String timerId, CallbackContext callbackContext, boolean enableHighAccuracy) { if (enableHighAccuracy) { - this.gpsListener.addWatch(timerId, callbackId); + this.gpsListener.addWatch(timerId, callbackContext); } else { - this.networkListener.addWatch(timerId, callbackId); + this.networkListener.addWatch(timerId, callbackContext); } } - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - // Starting listeners is easier to run on main thread, so don't run async. - return true; - } - /** * Called when the activity is to be shut down. * Stop listener. @@ -172,9 +166,9 @@ public class GeoBroker extends Plugin { return o; } - public void win(Location loc, String callbackId) { + public void win(Location loc, CallbackContext callbackContext) { PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc)); - this.success(result, callbackId); + callbackContext.sendPluginResult(result); } /** @@ -184,7 +178,7 @@ public class GeoBroker extends Plugin { * @param msg The error message * @throws JSONException */ - public void fail(int code, String msg, String callbackId) { + public void fail(int code, String msg, CallbackContext callbackContext) { JSONObject obj = new JSONObject(); String backup = null; try { @@ -201,9 +195,9 @@ public class GeoBroker extends Plugin { result = new PluginResult(PluginResult.Status.ERROR, backup); } - this.error(result, callbackId); + callbackContext.sendPluginResult(result); } - + public boolean isGlobalListener(CordovaLocationListener listener) { if (gpsListener != null && networkListener != null) From c55fd06b9997e9e48ef9cc803a1a612791bb7af7 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 18:28:36 -0400 Subject: [PATCH 12/17] Fix mountain of trailing whitespace. --- .../src/org/apache/cordova/Globalization.java | 456 +++++++++--------- 1 file changed, 228 insertions(+), 228 deletions(-) diff --git a/framework/src/org/apache/cordova/Globalization.java b/framework/src/org/apache/cordova/Globalization.java index 98bf9e5a..63672c84 100644 --- a/framework/src/org/apache/cordova/Globalization.java +++ b/framework/src/org/apache/cordova/Globalization.java @@ -58,7 +58,7 @@ public class Globalization extends Plugin { public static final String GETNUMBERPATTERN = "getNumberPattern"; public static final String GETCURRENCYPATTERN = "getCurrencyPattern"; public static final String GETPREFERREDLANGUAGE = "getPreferredLanguage"; - + //GlobalizationCommand Option Parameters public static final String OPTIONS = "options"; public static final String FORMATLENGTH = "formatLength"; @@ -83,82 +83,82 @@ public class Globalization extends Plugin { public static final String PERCENT = "percent"; public static final String CURRENCY = "currency"; public static final String CURRENCYCODE = "currencyCode"; - + @Override - public PluginResult execute(String action, JSONArray data, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; + public PluginResult execute(String action, JSONArray data, String callbackId) { + PluginResult.Status status = PluginResult.Status.OK; JSONObject obj = new JSONObject(); - try{ - if (action.equals(GETLOCALENAME)){ - obj = getLocaleName(); - return new PluginResult(status, obj); + try{ + if (action.equals(GETLOCALENAME)){ + obj = getLocaleName(); + return new PluginResult(status, obj); }else if (action.equals(GETPREFERREDLANGUAGE)){ obj = getPreferredLanguage(); return new PluginResult(status, obj); } else if (action.equalsIgnoreCase(DATETOSTRING)) { - obj = getDateToString(data); - return new PluginResult(PluginResult.Status.OK, obj); - }else if(action.equalsIgnoreCase(STRINGTODATE)){ - obj = getStringtoDate(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getDateToString(data); + return new PluginResult(PluginResult.Status.OK, obj); + }else if(action.equalsIgnoreCase(STRINGTODATE)){ + obj = getStringtoDate(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETDATEPATTERN)){ - obj = getDatePattern(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getDatePattern(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETDATENAMES)){ - obj = getDateNames(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getDateNames(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(ISDAYLIGHTSAVINGSTIME)){ - obj = getIsDayLightSavingsTime(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getIsDayLightSavingsTime(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETFIRSTDAYOFWEEK)){ - obj = getFirstDayOfWeek(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getFirstDayOfWeek(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(NUMBERTOSTRING)){ - obj = getNumberToString(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getNumberToString(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(STRINGTONUMBER)){ - obj = getStringToNumber(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getStringToNumber(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETNUMBERPATTERN)){ - obj = getNumberPattern(data); - return new PluginResult(PluginResult.Status.OK, obj); + obj = getNumberPattern(data); + return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETCURRENCYPATTERN)){ - obj = getCurrencyPattern(data); - return new PluginResult(PluginResult.Status.OK, obj); - } - }catch (GlobalizationError ge){ + obj = getCurrencyPattern(data); + return new PluginResult(PluginResult.Status.OK, obj); + } + }catch (GlobalizationError ge){ return new PluginResult(PluginResult.Status.ERROR, ge.toJson()); - }catch (Exception e){ - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); - } - return new PluginResult(PluginResult.Status.INVALID_ACTION); - } - /* + }catch (Exception e){ + return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + } + return new PluginResult(PluginResult.Status.INVALID_ACTION); + } + /* * @Description: Returns the string identifier for the client's current locale setting - * + * * @Return: JSONObject * Object.value {String}: The locale identifier - * + * * @throws: GlobalizationError.UNKNOWN_ERROR - */ + */ private JSONObject getLocaleName() throws GlobalizationError{ JSONObject obj = new JSONObject(); - try{ - obj.put("value",Locale.getDefault().toString());//get the locale from the Android Device - return obj; + try{ + obj.put("value",Locale.getDefault().toString());//get the locale from the Android Device + return obj; }catch(Exception e){ throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); - } + } } - /* + /* * @Description: Returns the string identifier for the client's current language - * + * * @Return: JSONObject * Object.value {String}: The language identifier - * + * * @throws: GlobalizationError.UNKNOWN_ERROR - */ + */ private JSONObject getPreferredLanguage() throws GlobalizationError { JSONObject obj = new JSONObject(); try { @@ -168,33 +168,33 @@ public class Globalization extends Plugin { throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); } } - /* - * @Description: Returns a date formatted as a string according to the client's user preferences and - * calendar using the time zone of the client. - * - * @Return: JSONObject + /* + * @Description: Returns a date formatted as a string according to the client's user preferences and + * calendar using the time zone of the client. + * + * @Return: JSONObject * Object.value {String}: The localized date string - * + * * @throws: GlobalizationError.FORMATTING_ERROR - */ - private JSONObject getDateToString(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); - try{ + */ + private JSONObject getDateToString(JSONArray options) throws GlobalizationError{ + JSONObject obj = new JSONObject(); + try{ Date date = new Date((Long)options.getJSONObject(0).get(DATE)); - + //get formatting pattern from android device (Will only have device specific formatting for short form of date) or options supplied JSONObject datePattern = getDatePattern(options); - SimpleDateFormat fmt = new SimpleDateFormat(datePattern.getString("pattern")); - - //return formatted date + SimpleDateFormat fmt = new SimpleDateFormat(datePattern.getString("pattern")); + + //return formatted date return obj.put("value",fmt.format(date)); - }catch(Exception ge){ + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); - } - } - - /* - * @Description: Parses a date formatted as a string according to the client's user + } + } + + /* + * @Description: Parses a date formatted as a string according to the client's user * preferences and calendar using the time zone of the client and returns * the corresponding date object * @Return: JSONObject @@ -207,22 +207,22 @@ public class Globalization extends Plugin { * Object.millisecond {Number}: The milliseconds (from 0 - 999), not available on all platforms * * @throws: GlobalizationError.PARSING_ERROR - */ + */ private JSONObject getStringtoDate(JSONArray options)throws GlobalizationError{ - JSONObject obj = new JSONObject(); - Date date; - try{ + JSONObject obj = new JSONObject(); + Date date; + try{ //get format pattern from android device (Will only have device specific formatting for short form of date) or options supplied - DateFormat fmt = new SimpleDateFormat(getDatePattern(options).getString("pattern")); - + DateFormat fmt = new SimpleDateFormat(getDatePattern(options).getString("pattern")); + //attempt parsing string based on user preferences date = fmt.parse(options.getJSONObject(0).get(DATESTRING).toString()); - + //set Android Time object Time time = new Time(); - time.set(date.getTime()); - - //return properties; + time.set(date.getTime()); + + //return properties; obj.put("year", time.year); obj.put("month", time.month); obj.put("day", time.monthDay); @@ -233,50 +233,50 @@ public class Globalization extends Plugin { return obj; }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.PARSING_ERROR); - } - } - - /* - * @Description: Returns a pattern string for formatting and parsing dates according to the client's + } + } + + /* + * @Description: Returns a pattern string for formatting and parsing dates according to the client's * user preferences. * @Return: JSONObject - * - * Object.pattern {String}: The date and time pattern for formatting and parsing dates. + * + * Object.pattern {String}: The date and time pattern for formatting and parsing dates. * The patterns follow Unicode Technical Standard #35 * http://unicode.org/reports/tr35/tr35-4.html * Object.timezone {String}: The abbreviated name of the time zone on the client - * Object.utc_offset {Number}: The current difference in seconds between the client's - * time zone and coordinated universal time. - * Object.dst_offset {Number}: The current daylight saving time offset in seconds - * between the client's non-daylight saving's time zone + * Object.utc_offset {Number}: The current difference in seconds between the client's + * time zone and coordinated universal time. + * Object.dst_offset {Number}: The current daylight saving time offset in seconds + * between the client's non-daylight saving's time zone * and the client's daylight saving's time zone. * * @throws: GlobalizationError.PATTERN_ERROR */ private JSONObject getDatePattern(JSONArray options) throws GlobalizationError{ JSONObject obj = new JSONObject(); - + try{ SimpleDateFormat fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getDateFormat(this.cordova.getActivity()); //default user preference for date SimpleDateFormat fmtTime = (SimpleDateFormat)android.text.format.DateFormat.getTimeFormat(this.cordova.getActivity()); //default user preference for time - + String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a - - //get Date value + options (if available) + + //get Date value + options (if available) if (options.getJSONObject(0).length() > 1){ //options were included - - //get formatLength option - if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(FORMATLENGTH)){ + + //get formatLength option + if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(FORMATLENGTH)){ String fmtOpt = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(FORMATLENGTH); if (fmtOpt.equalsIgnoreCase(MEDIUM)){//medium - fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getMediumDateFormat(this.cordova.getActivity()); + fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getMediumDateFormat(this.cordova.getActivity()); }else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)){ //long/full fmtDate = (SimpleDateFormat)android.text.format.DateFormat.getLongDateFormat(this.cordova.getActivity()); } } - - //return pattern type + + //return pattern type fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(SELECTOR)){ String selOpt = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(SELECTOR); @@ -284,57 +284,57 @@ public class Globalization extends Plugin { fmt = fmtDate.toLocalizedPattern(); }else if (selOpt.equalsIgnoreCase(TIME)){ fmt = fmtTime.toLocalizedPattern(); - } - } - } - - //TimeZone from users device - //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method - TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone()); - + } + } + } + + //TimeZone from users device + //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method + TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone()); + obj.put("pattern", fmt); obj.put("timezone", tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()),TimeZone.SHORT)); obj.put("utc_offset", tz.getRawOffset()/1000); - obj.put("dst_offset", tz.getDSTSavings()/1000); + obj.put("dst_offset", tz.getDSTSavings()/1000); return obj; - - }catch(Exception ge){ + + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.PATTERN_ERROR); - } + } } - - /* - * @Description: Returns an array of either the names of the months or days of the week + + /* + * @Description: Returns an array of either the names of the months or days of the week * according to the client's user preferences and calendar * @Return: JSONObject - * Object.value {Array{String}}: The array of names starting from either - * the first month in the year or the + * Object.value {Array{String}}: The array of names starting from either + * the first month in the year or the * first day of the week. - * + * * @throws: GlobalizationError.UNKNOWN_ERROR */ private JSONObject getDateNames(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); + JSONObject obj = new JSONObject(); //String[] value; - JSONArray value = new JSONArray(); + JSONArray value = new JSONArray(); List namesList = new ArrayList(); final Map namesMap; // final needed for sorting with anonymous comparator - try{ + try{ int type = 0; //default wide - int item = 0; //default months - + int item = 0; //default months + //get options if available if (options.getJSONObject(0).length() > 0){ //get type if available - if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ + if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ String t = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(TYPE); if (t.equalsIgnoreCase(NARROW)){type++;} //DateUtils.LENGTH_MEDIUM } //get item if available - if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(ITEM)){ + if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(ITEM)){ String t = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(ITEM); if (t.equalsIgnoreCase(DAYS)){item += 10;} //Days of week start at 1 - } + } } //determine return value int method = item + type; @@ -345,40 +345,40 @@ public class Globalization extends Plugin { } else if (method == 11) { //days and narrow namesMap = Calendar.getInstance().getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); } else { //default: months and wide - namesMap = Calendar.getInstance().getDisplayNames(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); + namesMap = Calendar.getInstance().getDisplayNames(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); } // save names as a list for(String name : namesMap.keySet()) { namesList.add(name); } - + // sort the list according to values in namesMap Collections.sort(namesList, new Comparator() { public int compare(String arg0, String arg1) { return namesMap.get(arg0).compareTo(namesMap.get(arg1)); } }); - - // convert nameList into JSONArray of String objects + + // convert nameList into JSONArray of String objects for (int i = 0; i < namesList.size(); i ++){ value.put(namesList.get(i)); - } + } - //return array of names - return obj.put("value", value); - }catch(Exception ge){ + //return array of names + return obj.put("value", value); + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); - } + } } - - /* - * @Description: Returns whether daylight savings time is in effect for a given date using the client's + + /* + * @Description: Returns whether daylight savings time is in effect for a given date using the client's * time zone and calendar. * @Return: JSONObject - * Object.dst {Boolean}: The value "true" indicates that daylight savings time is - * in effect for the given date and "false" indicate that it is not. * - * + * Object.dst {Boolean}: The value "true" indicates that daylight savings time is + * in effect for the given date and "false" indicate that it is not. * + * * @throws: GlobalizationError.UNKNOWN_ERROR */ private JSONObject getIsDayLightSavingsTime(JSONArray options) throws GlobalizationError{ @@ -388,112 +388,112 @@ public class Globalization extends Plugin { Date date = new Date((Long)options.getJSONObject(0).get(DATE)); //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone()); - dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings - - return obj.put("dst",dst); - }catch(Exception ge){ + dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings + + return obj.put("dst",dst); + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); - } - } - - /* - * @Description: Returns the first day of the week according to the client's user preferences and calendar. + } + } + + /* + * @Description: Returns the first day of the week according to the client's user preferences and calendar. * The days of the week are numbered starting from 1 where 1 is considered to be Sunday. * @Return: JSONObject * Object.value {Number}: The number of the first day of the week. - * + * * @throws: GlobalizationError.UNKNOWN_ERROR */ private JSONObject getFirstDayOfWeek(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); - try{ + JSONObject obj = new JSONObject(); + try{ int value = Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek(); //get first day of week based on user locale settings return obj.put("value", value); - }catch(Exception ge){ + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR); - } - } - - /* - * @Description: Returns a number formatted as a string according to the client's user preferences. + } + } + + /* + * @Description: Returns a number formatted as a string according to the client's user preferences. * @Return: JSONObject - * Object.value {String}: The formatted number string. - * + * Object.value {String}: The formatted number string. + * * @throws: GlobalizationError.FORMATTING_ERROR */ private JSONObject getNumberToString(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); + JSONObject obj = new JSONObject(); String value = ""; try{ DecimalFormat fmt = getNumberFormatInstance(options);//returns Decimal/Currency/Percent instance value = fmt.format(options.getJSONObject(0).get(NUMBER)); - return obj.put("value", value); - }catch(Exception ge){ + return obj.put("value", value); + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); - } - } - - /* - * @Description: Parses a number formatted as a string according to the client's user preferences and + } + } + + /* + * @Description: Parses a number formatted as a string according to the client's user preferences and * returns the corresponding number. - * @Return: JSONObject + * @Return: JSONObject * Object.value {Number}: The parsed number. - * + * * @throws: GlobalizationError.PARSING_ERROR */ private JSONObject getStringToNumber(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); + JSONObject obj = new JSONObject(); Number value; try{ DecimalFormat fmt = getNumberFormatInstance(options); //returns Decimal/Currency/Percent instance - value = fmt.parse((String)options.getJSONObject(0).get(NUMBERSTRING)); - return obj.put("value", value); - }catch(Exception ge){ + value = fmt.parse((String)options.getJSONObject(0).get(NUMBERSTRING)); + return obj.put("value", value); + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.PARSING_ERROR); - } + } } - - /* - * @Description: Returns a pattern string for formatting and parsing numbers according to the client's user + + /* + * @Description: Returns a pattern string for formatting and parsing numbers according to the client's user * preferences. * @Return: JSONObject - * Object.pattern {String}: The number pattern for formatting and parsing numbers. - * The patterns follow Unicode Technical Standard #35. + * Object.pattern {String}: The number pattern for formatting and parsing numbers. + * The patterns follow Unicode Technical Standard #35. * http://unicode.org/reports/tr35/tr35-4.html - * Object.symbol {String}: The symbol to be used when formatting and parsing + * Object.symbol {String}: The symbol to be used when formatting and parsing * e.g., percent or currency symbol. - * Object.fraction {Number}: The number of fractional digits to use when parsing and + * Object.fraction {Number}: The number of fractional digits to use when parsing and * formatting numbers. * Object.rounding {Number}: The rounding increment to use when parsing and formatting. * Object.positive {String}: The symbol to use for positive numbers when parsing and formatting. * Object.negative: {String}: The symbol to use for negative numbers when parsing and formatting. * Object.decimal: {String}: The decimal symbol to use for parsing and formatting. * Object.grouping: {String}: The grouping symbol to use for parsing and formatting. - * + * * @throws: GlobalizationError.PATTERN_ERROR */ private JSONObject getNumberPattern(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); - try{ - //uses java.text.DecimalFormat to format value - DecimalFormat fmt = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); //default format + JSONObject obj = new JSONObject(); + try{ + //uses java.text.DecimalFormat to format value + DecimalFormat fmt = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); //default format String symbol = String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator()); - //get Date value + options (if available) + //get Date value + options (if available) if (options.getJSONObject(0).length() > 0){ //options were included - if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ + if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ String fmtOpt = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(TYPE); if (fmtOpt.equalsIgnoreCase(CURRENCY)){ fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); symbol = fmt.getDecimalFormatSymbols().getCurrencySymbol(); }else if(fmtOpt.equalsIgnoreCase(PERCENT)){ fmt = (DecimalFormat) DecimalFormat.getPercentInstance(Locale.getDefault()); - symbol = String.valueOf(fmt.getDecimalFormatSymbols().getPercent()); + symbol = String.valueOf(fmt.getDecimalFormatSymbols().getPercent()); } } - } - - //return properties + } + + //return properties obj.put("pattern", fmt.toPattern()); obj.put("symbol", symbol); obj.put("fraction", fmt.getMinimumFractionDigits()); @@ -501,79 +501,79 @@ public class Globalization extends Plugin { obj.put("positive", fmt.getPositivePrefix()); obj.put("negative", fmt.getNegativePrefix()); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); - obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); - - return obj; - }catch(Exception ge){ + obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); + + return obj; + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.PATTERN_ERROR); - } - } - - /* + } + } + + /* * @Description: Returns a pattern string for formatting and parsing currency values according to the client's * user preferences and ISO 4217 currency code. * @Return: JSONObject - * Object.pattern {String}: The currency pattern for formatting and parsing currency values. - * The patterns follow Unicode Technical Standard #35 + * Object.pattern {String}: The currency pattern for formatting and parsing currency values. + * The patterns follow Unicode Technical Standard #35 * http://unicode.org/reports/tr35/tr35-4.html * Object.code {String}: The ISO 4217 currency code for the pattern. - * Object.fraction {Number}: The number of fractional digits to use when parsing and + * Object.fraction {Number}: The number of fractional digits to use when parsing and * formatting currency. * Object.rounding {Number}: The rounding increment to use when parsing and formatting. * Object.decimal: {String}: The decimal symbol to use for parsing and formatting. * Object.grouping: {String}: The grouping symbol to use for parsing and formatting. - * + * * @throws: GlobalizationError.FORMATTING_ERROR */ private JSONObject getCurrencyPattern(JSONArray options) throws GlobalizationError{ - JSONObject obj = new JSONObject(); - try{ + JSONObject obj = new JSONObject(); + try{ //get ISO 4217 currency code - String code = options.getJSONObject(0).getString(CURRENCYCODE); - - //uses java.text.DecimalFormat to format value + String code = options.getJSONObject(0).getString(CURRENCYCODE); + + //uses java.text.DecimalFormat to format value DecimalFormat fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault()); - + //set currency format Currency currency = Currency.getInstance(code); fmt.setCurrency(currency); - - //return properties + + //return properties obj.put("pattern", fmt.toPattern()); obj.put("code", currency.getCurrencyCode()); obj.put("fraction", fmt.getMinimumFractionDigits()); obj.put("rounding", new Integer(0)); obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator())); - obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); - - return obj; - }catch(Exception ge){ + obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator())); + + return obj; + }catch(Exception ge){ throw new GlobalizationError(GlobalizationError.FORMATTING_ERROR); - } + } } - - /* + + /* * @Description: Parses a JSONArray from user options and returns the correct Instance of Decimal/Percent/Currency. * @Return: DecimalFormat : The Instance to use. - * + * * @throws: JSONException */ - private DecimalFormat getNumberFormatInstance(JSONArray options) throws JSONException{ + private DecimalFormat getNumberFormatInstance(JSONArray options) throws JSONException{ DecimalFormat fmt = (DecimalFormat)DecimalFormat.getInstance(Locale.getDefault()); //default format - try{ + try{ if (options.getJSONObject(0).length() > 1){ - //options were included - if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ + //options were included + if (!((JSONObject)options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)){ String fmtOpt = (String)((JSONObject)options.getJSONObject(0).get(OPTIONS)).get(TYPE); if (fmtOpt.equalsIgnoreCase(CURRENCY)){ fmt = (DecimalFormat)DecimalFormat.getCurrencyInstance(Locale.getDefault()); }else if(fmtOpt.equalsIgnoreCase(PERCENT)){ - fmt = (DecimalFormat)DecimalFormat.getPercentInstance(Locale.getDefault()); + fmt = (DecimalFormat)DecimalFormat.getPercentInstance(Locale.getDefault()); } } } - - }catch (JSONException je){} + + }catch (JSONException je){} return fmt; } } From 7379d2135d0256acae97deeec9ee9689a3288af5 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Thu, 11 Oct 2012 18:32:35 -0400 Subject: [PATCH 13/17] Port Globalization to CordovaPlugin. --- .../src/org/apache/cordova/Globalization.java | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/framework/src/org/apache/cordova/Globalization.java b/framework/src/org/apache/cordova/Globalization.java index 63672c84..737e2123 100644 --- a/framework/src/org/apache/cordova/Globalization.java +++ b/framework/src/org/apache/cordova/Globalization.java @@ -33,7 +33,8 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -44,7 +45,7 @@ import android.text.format.Time; /** * */ -public class Globalization extends Plugin { +public class Globalization extends CordovaPlugin { //GlobalizationCommand Plugin Actions public static final String GETLOCALENAME = "getLocaleName"; public static final String DATETOSTRING = "dateToString"; @@ -85,54 +86,45 @@ public class Globalization extends Plugin { public static final String CURRENCYCODE = "currencyCode"; @Override - public PluginResult execute(String action, JSONArray data, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; + public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { JSONObject obj = new JSONObject(); try{ if (action.equals(GETLOCALENAME)){ obj = getLocaleName(); - return new PluginResult(status, obj); }else if (action.equals(GETPREFERREDLANGUAGE)){ obj = getPreferredLanguage(); - return new PluginResult(status, obj); } else if (action.equalsIgnoreCase(DATETOSTRING)) { obj = getDateToString(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(STRINGTODATE)){ obj = getStringtoDate(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETDATEPATTERN)){ obj = getDatePattern(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETDATENAMES)){ obj = getDateNames(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(ISDAYLIGHTSAVINGSTIME)){ obj = getIsDayLightSavingsTime(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETFIRSTDAYOFWEEK)){ obj = getFirstDayOfWeek(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(NUMBERTOSTRING)){ obj = getNumberToString(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(STRINGTONUMBER)){ obj = getStringToNumber(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETNUMBERPATTERN)){ obj = getNumberPattern(data); - return new PluginResult(PluginResult.Status.OK, obj); }else if(action.equalsIgnoreCase(GETCURRENCYPATTERN)){ obj = getCurrencyPattern(data); - return new PluginResult(PluginResult.Status.OK, obj); + }else { + return false; } + + callbackContext.success(obj); }catch (GlobalizationError ge){ - return new PluginResult(PluginResult.Status.ERROR, ge.toJson()); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, ge.toJson())); }catch (Exception e){ - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } - return new PluginResult(PluginResult.Status.INVALID_ACTION); + return true; } /* * @Description: Returns the string identifier for the client's current locale setting From 17d64cfcbe771932047900737aefa7dda0560182 Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Fri, 12 Oct 2012 10:05:26 -0400 Subject: [PATCH 14/17] Port NetworkManager to CordovaPlugin. --- .../org/apache/cordova/NetworkManager.java | 53 ++++++++----------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/framework/src/org/apache/cordova/NetworkManager.java b/framework/src/org/apache/cordova/NetworkManager.java index f473abec..5d879180 100755 --- a/framework/src/org/apache/cordova/NetworkManager.java +++ b/framework/src/org/apache/cordova/NetworkManager.java @@ -18,8 +18,9 @@ */ package org.apache.cordova; +import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; @@ -31,7 +32,7 @@ import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; -public class NetworkManager extends Plugin { +public class NetworkManager extends CordovaPlugin { public static int NOT_REACHABLE = 0; public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; @@ -68,7 +69,7 @@ public class NetworkManager extends Plugin { private static final String LOG_TAG = "NetworkManager"; - private String connectionCallbackId; + private CallbackContext connectionCallbackContext; private boolean registered = false; ConnectivityManager sockMan; @@ -86,11 +87,12 @@ public class NetworkManager extends Plugin { * get file paths associated with the Activity. * * @param cordova The context of the main Activity. + * @param webView The CordovaWebView Cordova is running in. */ - public void setContext(CordovaInterface cordova) { - super.setContext(cordova); + public void initialize(CordovaInterface cordova, CordovaWebView webView) { + super.initialize(cordova, webView); this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); - this.connectionCallbackId = null; + this.connectionCallbackContext = null; // We need to listen to connectivity events to update navigator.connection IntentFilter intentFilter = new IntentFilter(); @@ -101,7 +103,7 @@ public class NetworkManager extends Plugin { @Override public void onReceive(Context context, Intent intent) { // (The null check is for the ARM Emulator, please use Intel Emulator for better results) - if(webView != null) + if(NetworkManager.this.webView != null) updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO)); } }; @@ -114,34 +116,21 @@ public class NetworkManager extends Plugin { /** * 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. + * @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 PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.INVALID_ACTION; - String result = "Unsupported Operation: " + action; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("getConnectionInfo")) { - this.connectionCallbackId = callbackId; + this.connectionCallbackContext = callbackContext; NetworkInfo info = sockMan.getActiveNetworkInfo(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, this.getConnectionInfo(info)); pluginResult.setKeepCallback(true); - return pluginResult; + callbackContext.sendPluginResult(pluginResult); + return true; } - - return new PluginResult(status, result); - } - - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - return true; + return false; } /** @@ -206,15 +195,15 @@ public class NetworkManager extends Plugin { * @param connection the network info to set as navigator.connection */ private void sendUpdate(String type) { - if (connectionCallbackId != null) { + if (connectionCallbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, type); result.setKeepCallback(true); - this.success(result, this.connectionCallbackId); + connectionCallbackContext.sendPluginResult(result); } webView.postMessage("networkconnection", type); } - + /** * Determine the type of connection * From 621e1163f85e257a59f2da8f6830dece43a977dd Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Fri, 12 Oct 2012 16:58:15 -0400 Subject: [PATCH 15/17] Port Notification to CordovaPlugin. --- .../src/org/apache/cordova/Notification.java | 108 ++++++------------ 1 file changed, 36 insertions(+), 72 deletions(-) diff --git a/framework/src/org/apache/cordova/Notification.java b/framework/src/org/apache/cordova/Notification.java index 7a06a997..8d44d2e9 100755 --- a/framework/src/org/apache/cordova/Notification.java +++ b/framework/src/org/apache/cordova/Notification.java @@ -18,8 +18,9 @@ */ package org.apache.cordova; +import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaInterface; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -35,7 +36,7 @@ import android.os.Vibrator; /** * This class provides access to notifications on the device. */ -public class Notification extends Plugin { +public class Notification extends CordovaPlugin { public int confirmResult = -1; public ProgressDialog spinnerDialog = null; @@ -50,15 +51,12 @@ public class Notification extends Plugin { /** * 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. + * @param action The action to execute. + * @param args JSONArray of arguments for the plugin. + * @param callbackContext The callback context used when calling back into JavaScript. + * @return True when the action was valid, false otherwise. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("beep")) { this.beep(args.getLong(0)); @@ -67,16 +65,12 @@ public class Notification extends Plugin { this.vibrate(args.getLong(0)); } else if (action.equals("alert")) { - this.alert(args.getString(0), args.getString(1), args.getString(2), callbackId); - PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); - r.setKeepCallback(true); - return r; + this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext); + return true; } else if (action.equals("confirm")) { - this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackId); - PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); - r.setKeepCallback(true); - return r; + this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackContext); + return true; } else if (action.equals("activityStart")) { this.activityStart(args.getString(0), args.getString(1)); @@ -93,43 +87,16 @@ public class Notification extends Plugin { else if (action.equals("progressStop")) { this.progressStop(); } - return new PluginResult(status, result); - } catch (JSONException e) { - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); - } - } + else { + return false; + } - /** - * Identifies if action to be executed returns a value and should be run synchronously. - * - * @param action The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { - if (action.equals("alert")) { - return true; - } - else if (action.equals("confirm")) { - return true; - } - else if (action.equals("activityStart")) { - return true; - } - else if (action.equals("activityStop")) { - return true; - } - else if (action.equals("progressStart")) { - return true; - } - else if (action.equals("progressValue")) { - return true; - } - else if (action.equals("progressStop")) { - return true; - } - else { - return false; + // Only alert and confirm are async. + callbackContext.success(); + } catch (JSONException e) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } + return true; } //-------------------------------------------------------------------------- @@ -177,15 +144,14 @@ public class Notification extends Plugin { /** * Builds and shows a native Android alert with given Strings - * @param message The message the alert should display - * @param title The title of the alert - * @param buttonLabel The label of the button - * @param callbackId The callback id + * @param message The message the alert should display + * @param title The title of the alert + * @param buttonLabel The label of the button + * @param callbackContext The callback context */ - public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) { + public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; - final Notification notification = this; Runnable runnable = new Runnable() { public void run() { @@ -198,7 +164,7 @@ public class Notification extends Plugin { new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - notification.success(new PluginResult(PluginResult.Status.OK, 0), callbackId); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0)); } }); dlg.create(); @@ -213,15 +179,14 @@ public class Notification extends Plugin { * This dialog only shows up to 3 buttons. Any labels after that will be ignored. * The index of the button pressed will be returned to the JavaScript callback identified by callbackId. * - * @param message The message the dialog should display - * @param title The title of the dialog - * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) - * @param callbackId The callback id + * @param message The message the dialog should display + * @param title The title of the dialog + * @param buttonLabels A comma separated list of button labels (Up to 3 buttons) + * @param callbackContext The callback context. */ - public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) { + public synchronized void confirm(final String message, final String title, String buttonLabels, final CallbackContext callbackContext) { final CordovaInterface cordova = this.cordova; - final Notification notification = this; final String[] fButtons = buttonLabels.split(","); Runnable runnable = new Runnable() { @@ -237,7 +202,7 @@ public class Notification extends Plugin { new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1)); } }); } @@ -248,7 +213,7 @@ public class Notification extends Plugin { new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2)); } }); } @@ -259,7 +224,7 @@ public class Notification extends Plugin { new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3)); } } ); @@ -283,14 +248,13 @@ public class Notification extends Plugin { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } - final Notification notification = this; final CordovaInterface cordova = this.cordova; Runnable runnable = new Runnable() { public void run() { - notification.spinnerDialog = ProgressDialog.show(cordova.getActivity(), title, message, true, true, + Notification.this.spinnerDialog = ProgressDialog.show(cordova.getActivity(), title, message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { - notification.spinnerDialog = null; + Notification.this.spinnerDialog = null; } }); } From 29a0b010daaab5a4451cc4e087dc5159f87e321f Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Fri, 12 Oct 2012 17:00:14 -0400 Subject: [PATCH 16/17] Port SplashScreen to CordovaPlugin. Untested, no tests for it. --- .../src/org/apache/cordova/SplashScreen.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/framework/src/org/apache/cordova/SplashScreen.java b/framework/src/org/apache/cordova/SplashScreen.java index 93ab6288..66b5baeb 100644 --- a/framework/src/org/apache/cordova/SplashScreen.java +++ b/framework/src/org/apache/cordova/SplashScreen.java @@ -19,26 +19,25 @@ package org.apache.cordova; -import org.apache.cordova.api.Plugin; -import org.apache.cordova.api.PluginResult; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.json.JSONArray; -public class SplashScreen extends Plugin { +public class SplashScreen extends CordovaPlugin { @Override - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("hide")) { this.webView.postMessage("splashscreen", "hide"); } else if (action.equals("show")){ this.webView.postMessage("splashscreen", "show"); } else { - status = PluginResult.Status.INVALID_ACTION; + return false; } - return new PluginResult(status, result); + + callbackContext.success(); + return true; } } From fe1f57c23f74bcefa9247fad214e4288042dae4c Mon Sep 17 00:00:00 2001 From: Braden Shepherdson Date: Fri, 12 Oct 2012 17:05:35 -0400 Subject: [PATCH 17/17] Port Storage to use CordovaPlugin. --- framework/src/org/apache/cordova/Storage.java | 40 +++++++------------ 1 file changed, 15 insertions(+), 25 deletions(-) diff --git a/framework/src/org/apache/cordova/Storage.java b/framework/src/org/apache/cordova/Storage.java index ea385442..0c382810 100755 --- a/framework/src/org/apache/cordova/Storage.java +++ b/framework/src/org/apache/cordova/Storage.java @@ -20,7 +20,8 @@ package org.apache.cordova; import java.io.File; -import org.apache.cordova.api.Plugin; +import org.apache.cordova.api.CallbackContext; +import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; @@ -35,7 +36,7 @@ import android.database.sqlite.*; * Android 3.0 devices. It is not used for other versions of Android, since * HTML5 database is built in to the browser. */ -public class Storage extends Plugin { +public class Storage extends CordovaPlugin { // Data Definition Language private static final String ALTER = "alter"; @@ -60,14 +61,11 @@ public class Storage extends Plugin { * 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. + * @param callbackContext + * The callback context used when calling back into JavaScript. + * @return True if the action was valid, false otherwise. */ - public PluginResult execute(String action, JSONArray args, String callbackId) { - PluginResult.Status status = PluginResult.Status.OK; - String result = ""; - + public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("openDatabase")) { this.openDatabase(args.getString(0), args.getString(1), @@ -86,21 +84,13 @@ public class Storage extends Plugin { } this.executeSql(args.getString(0), s, args.getString(2)); } - return new PluginResult(status, result); + else { + return false; + } + callbackContext.success(); } catch (JSONException e) { - return new PluginResult(PluginResult.Status.JSON_EXCEPTION); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } - } - - /** - * Identifies if action to be executed returns a value and should be run - * synchronously. - * - * @param action - * The action to execute - * @return T=returns value - */ - public boolean isSynch(String action) { return true; } @@ -169,7 +159,7 @@ public class Storage extends Plugin { try { if (isDDL(query)) { this.myDb.execSQL(query); - this.sendJavascript("cordova.require('cordova/plugin/android/storage').completeQuery('" + tx_id + "', '');"); + this.webView.sendJavascript("cordova.require('cordova/plugin/android/storage').completeQuery('" + tx_id + "', '');"); } else { Cursor myCursor = this.myDb.rawQuery(query, params); @@ -182,7 +172,7 @@ public class Storage extends Plugin { System.out.println("Storage.executeSql(): Error=" + ex.getMessage()); // Send error message back to JavaScript - this.sendJavascript("cordova.require('cordova/plugin/android/storage').failQuery('" + ex.getMessage() + "','" + tx_id + "');"); + this.webView.sendJavascript("cordova.require('cordova/plugin/android/storage').failQuery('" + ex.getMessage() + "','" + tx_id + "');"); } } @@ -240,7 +230,7 @@ public class Storage extends Plugin { } // Let JavaScript know that there are no more rows - this.sendJavascript("cordova.require('cordova/plugin/android/storage').completeQuery('" + tx_id + "', " + result + ");"); + this.webView.sendJavascript("cordova.require('cordova/plugin/android/storage').completeQuery('" + tx_id + "', " + result + ");"); } }