This commit is contained in:
Joe Bowser 2012-10-12 14:26:57 -07:00
commit 0ffffa9029
19 changed files with 688 additions and 759 deletions

View File

@ -20,8 +20,9 @@ package org.apache.cordova;
import java.util.List; import java.util.List;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface; 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.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -33,11 +34,14 @@ import android.hardware.SensorEvent;
import android.hardware.SensorEventListener; import android.hardware.SensorEventListener;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
/** /**
* This class listens to the accelerometer sensor and stores the latest * This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z. * 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 STOPPED = 0;
public static int STARTING = 1; public static int STARTING = 1;
@ -52,7 +56,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
private SensorManager sensorManager; // Sensor manager private SensorManager sensorManager; // Sensor manager
private Sensor mSensor; // Acceleration sensor returned by 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. * Create an accelerometer listener.
@ -70,29 +74,25 @@ public class AccelListener extends Plugin implements SensorEventListener {
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param cordova The context of the main Activity. * @param cordova The context of the main Activity.
* @param webView The associated CordovaWebView.
*/ */
@Override
public void setContext(CordovaInterface cordova) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.setContext(cordova); super.initialize(cordova, webView);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE); 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 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. * @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) { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
PluginResult.Status status = PluginResult.Status.NO_RESULT;
String message = "";
PluginResult result = new PluginResult(status, message);
result.setKeepCallback(true);
if (action.equals("start")) { if (action.equals("start")) {
this.callbackId = callbackId; this.callbackContext = callbackContext;
if (this.status != AccelListener.RUNNING) { if (this.status != AccelListener.RUNNING) {
// If not running, then this is an async call, so don't worry about waiting // 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 // 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 { } else {
// Unsupported action // 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;
} }
/** /**
@ -149,20 +153,15 @@ public class AccelListener extends Plugin implements SensorEventListener {
return this.status; return this.status;
} }
// Wait until running // Set a timeout callback on the main thread.
long timeout = 2000; Handler handler = new Handler(Looper.getMainLooper());
while ((this.status == STARTING) && (timeout > 0)) { handler.postDelayed(new Runnable() {
timeout = timeout - 100; @Override
try { public void run() {
Thread.sleep(100); AccelListener.this.timeout();
} 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.");
} }
}, 2000);
return this.status; return this.status;
} }
@ -177,6 +176,18 @@ public class AccelListener extends Plugin implements SensorEventListener {
this.accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE; 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. * 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); PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj);
err.setKeepCallback(true); err.setKeepCallback(true);
callbackContext.sendPluginResult(err);
this.error(err, this.callbackId);
} }
private void win() { private void win() {
// Success return object // Success return object
PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON()); PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON());
result.setKeepCallback(true); result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
this.success(result, this.callbackId);
} }
private void setStatus(int status) { private void setStatus(int status) {

View File

@ -18,12 +18,14 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import android.content.Context; import android.content.Context;
import android.media.AudioManager; import android.media.AudioManager;
import java.util.ArrayList; import java.util.ArrayList;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -40,7 +42,7 @@ import java.util.HashMap;
* android_asset: file name must start with /android_asset/sound.mp3 * android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3 * sdcard: file name is just sound.mp3
*/ */
public class AudioHandler extends Plugin { public class AudioHandler extends CordovaPlugin {
public static String TAG = "AudioHandler"; public static String TAG = "AudioHandler";
HashMap<String, AudioPlayer> players; // Audio player object HashMap<String, AudioPlayer> players; // Audio player object
@ -58,10 +60,10 @@ public class AudioHandler extends Plugin {
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @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. * @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; PluginResult.Status status = PluginResult.Status.OK;
String result = ""; String result = "";
@ -91,11 +93,13 @@ public class AudioHandler extends Plugin {
} }
} else if (action.equals("getCurrentPositionAudio")) { } else if (action.equals("getCurrentPositionAudio")) {
float f = this.getCurrentPositionAudio(args.getString(0)); 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")) { else if (action.equals("getDurationAudio")) {
float f = this.getDurationAudio(args.getString(0), args.getString(1)); 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")) { else if (action.equals("create")) {
String id = args.getString(0); String id = args.getString(0);
@ -105,29 +109,21 @@ public class AudioHandler extends Plugin {
} }
else if (action.equals("release")) { else if (action.equals("release")) {
boolean b = this.release(args.getString(0)); 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);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} }
else { // Unrecognized action.
return false;
} }
/** callbackContext.sendPluginResult(new PluginResult(status, result));
* Identifies if action to be executed returns a value and should be run synchronously. } catch (JSONException e) {
* @param action The action to execute e.printStackTrace();
* @return T=returns value callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
*/
public boolean isSynch(String action) {
if (action.equals("getCurrentPositionAudio")) {
return true;
} }
else if (action.equals("getDurationAudio")) {
return true; return true;
} }
return false;
}
/** /**
* Stop all audio players and recorders. * Stop all audio players and recorders.

View File

@ -31,8 +31,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import org.apache.cordova.AudioPlayer.MODE;
/** /**
* This class implements the audio playback and recording capabilities used by Cordova. * This class implements the audio playback and recording capabilities used by Cordova.
* It is called by the AudioHandler Cordova class. * It is called by the AudioHandler Cordova class.
@ -135,7 +133,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
switch (this.mode) { switch (this.mode) {
case PLAY: case PLAY:
Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode."); 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; break;
case NONE: case NONE:
this.audioFile = file; this.audioFile = file;
@ -153,11 +151,11 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); 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; break;
case RECORD: case RECORD:
Log.d(LOG_TAG, "AudioPlayer Error: Already recording."); 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)) { if (this.readyPlayer(this.audioFile)) {
this.player.seekTo(milliseconds); this.player.seekTo(milliseconds);
Log.d(LOG_TAG, "Send a onStatus update for the new seek"); 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 { else {
this.seekOnPrepared = milliseconds; this.seekOnPrepared = milliseconds;
@ -242,7 +240,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
} }
else { else {
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal()); 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 { else {
Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal()); 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() { public long getCurrentPosition() {
if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) { if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {
int curPos = this.player.getCurrentPosition(); 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; return curPos;
} }
else { else {
@ -359,7 +357,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.prepareOnly = true; this.prepareOnly = true;
// Send status notification to JavaScript // 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(); this.player.release();
// Send error notification to JavaScript // 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; return false;
} }
@ -398,7 +396,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
*/ */
private void setState(STATE state) { private void setState(STATE state) {
if (this.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; this.state = state;
} }
@ -411,7 +409,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
private void setMode(MODE mode) { private void setMode(MODE mode) {
if (this.mode != mode) { if (this.mode != mode) {
//mode is not part of the expected behavior, so no notification //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; this.mode = mode;
} }
@ -447,7 +445,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
break; break;
case RECORD: case RECORD:
Log.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode."); 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 false; //player is not ready
} }
return true; return true;
@ -468,7 +466,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
try { try {
this.loadAudioFile(file); this.loadAudioFile(file);
} catch (Exception e) { } 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; return false;
case MEDIA_LOADING: case MEDIA_LOADING:
@ -493,14 +491,14 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
try { try {
this.loadAudioFile(file); this.loadAudioFile(file);
} catch (Exception e) { } 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 //if we had to prepare= the file, we won't be in the correct state for playback
return false; return false;
} }
default: default:
Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state); 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; return false;
@ -526,7 +524,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
else { else {
if (file.startsWith("/android_asset/")) { if (file.startsWith("/android_asset/")) {
String f = file.substring(15); 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()); this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
} }
else { else {

View File

@ -18,7 +18,8 @@
*/ */
package org.apache.cordova; 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.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -30,13 +31,13 @@ import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.util.Log; import android.util.Log;
public class BatteryListener extends Plugin { public class BatteryListener extends CordovaPlugin {
private static final String LOG_TAG = "BatteryManager"; private static final String LOG_TAG = "BatteryManager";
BroadcastReceiver receiver; BroadcastReceiver receiver;
private String batteryCallbackId = null; private CallbackContext batteryCallbackContext = null;
/** /**
* Constructor. * 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 action The action to execute.
* @param args JSONArry of arguments for the plugin. * @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. * @return True if the action was valid, false if not.
*/ */
public PluginResult execute(String action, JSONArray args, String callbackId) { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
String result = "Unsupported Operation: " + action;
if (action.equals("start")) { if (action.equals("start")) {
if (this.batteryCallbackId != null) { if (this.batteryCallbackContext != null) {
return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running."); 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 // We need to listen to power events to update battery status
IntentFilter intentFilter = new IntentFilter(); 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 // 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 pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true); pluginResult.setKeepCallback(true);
return pluginResult; callbackContext.sendPluginResult(pluginResult);
return true;
} }
else if (action.equals("stop")) { else if (action.equals("stop")) {
removeBatteryListener(); removeBatteryListener();
this.sendUpdate(new JSONObject(), false); // release status callback in JS side this.sendUpdate(new JSONObject(), false); // release status callback in JS side
this.batteryCallbackId = null; this.batteryCallbackContext = null;
return new PluginResult(PluginResult.Status.OK); 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 * @param connection the network info to set as navigator.connection
*/ */
private void sendUpdate(JSONObject info, boolean keepCallback) { private void sendUpdate(JSONObject info, boolean keepCallback) {
if (this.batteryCallbackId != null) { if (this.batteryCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, info); PluginResult result = new PluginResult(PluginResult.Status.OK, info);
result.setKeepCallback(keepCallback); result.setKeepCallback(keepCallback);
this.success(result, this.batteryCallbackId); this.batteryCallbackContext.sendPluginResult(result);
} }
} }
} }

View File

@ -27,8 +27,9 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64; 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.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; 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 * and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed. * 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 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) 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 int mediaType; // What type of media to retrieve
private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album 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 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 int numPics;
private MediaScannerConnection conn; // Used to update gallery app with newly-written files private MediaScannerConnection conn; // Used to update gallery app with newly-written files
@ -112,13 +113,11 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @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; this.callbackContext = callbackContext;
String result = "";
this.callbackId = callbackId;
try { try {
if (action.equals("takePicture")) { if (action.equals("takePicture")) {
@ -138,7 +137,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
this.targetHeight = args.getInt(4); this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5); this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6); 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.correctOrientation = args.getBoolean(8);
this.saveToPhotoAlbum = args.getBoolean(9); this.saveToPhotoAlbum = args.getBoolean(9);
@ -159,12 +158,14 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
} }
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true); r.setKeepCallback(true);
return r; callbackContext.sendPluginResult(r);
return true;
} }
return new PluginResult(status, result); return false;
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); 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); this.imageUri = Uri.fromFile(photo);
if (this.cordova != null) { 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 // else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity"); // 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.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
if (this.cordova != null) { 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); 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) { if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && rotate == 0) {
writeUncompressedImage(uri); writeUncompressedImage(uri);
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); this.callbackContext.success(uri.toString());
} else { } else {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString())); 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 // 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); 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 // 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 // and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) { if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); this.callbackContext.success(uri.toString());
} }
else { else {
// This is a special case to just return the path as no scaling, // This is a special case to just return the path as no scaling,
// rotating or compression needs to be done // rotating or compression needs to be done
if (this.targetHeight == -1 && this.targetWidth == -1 && if (this.targetHeight == -1 && this.targetWidth == -1 &&
this.mQuality == 100 && destType == FILE_URI && !this.correctOrientation) { 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 { } else {
// Get the path to the image. Makes loading so much easier. // Get the path to the image. Makes loading so much easier.
String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova); 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 // 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. // 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) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
this.failPicture("Error retrieving image."); this.failPicture("Error retrieving image.");
} }
} }
else { else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); this.callbackContext.success(uri.toString());
} }
} }
if (bitmap != null) { if (bitmap != null) {
@ -732,7 +733,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
byte[] code = jpeg_data.toByteArray(); byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code); byte[] output = Base64.encodeBase64(code);
String js_out = new String(output); 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; js_out = null;
output = null; output = null;
code = null; code = null;
@ -749,7 +750,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
* @param err * @param err
*/ */
public void failPicture(String 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) { private void scanForGallery(Uri newImage) {
@ -757,7 +758,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
if(this.conn != null) { if(this.conn != null) {
this.conn.disconnect(); this.conn.disconnect();
} }
this.conn = new MediaScannerConnection(this.ctx.getActivity().getApplicationContext(), this); this.conn = new MediaScannerConnection(this.cordova.getActivity().getApplicationContext(), this);
conn.connect(); conn.connect();
} }

View File

@ -23,8 +23,9 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; 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.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -41,7 +42,7 @@ import android.os.Environment;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Log; 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_3GPP = "video/3gpp";
private static final String VIDEO_MP4 = "video/mp4"; 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_APPLICATION_BUSY = 1;
// private static final int CAPTURE_INVALID_ARGUMENT = 2; // private static final int CAPTURE_INVALID_ARGUMENT = 2;
private static final int CAPTURE_NO_MEDIA_FILES = 3; 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 long limit; // the number of pics/vids/clips to take
private double duration; // optional duration parameter for video recording private double duration; // optional duration parameter for video recording
private JSONArray results; // The array of results to be returned to the user 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 int numPics; // Number of pictures before capture activity
//private CordovaInterface cordova; //private CordovaInterface cordova;
@ -77,8 +76,8 @@ public class Capture extends Plugin {
// } // }
@Override @Override
public PluginResult execute(String action, JSONArray args, String callbackId) { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackId = callbackId; this.callbackContext = callbackContext;
this.limit = 1; this.limit = 1;
this.duration = 0.0f; this.duration = 0.0f;
this.results = new JSONArray(); this.results = new JSONArray();
@ -92,10 +91,11 @@ public class Capture extends Plugin {
if (action.equals("getFormatData")) { if (action.equals("getFormatData")) {
try { try {
JSONObject obj = getFormatData(args.getString(0), args.getString(1)); JSONObject obj = getFormatData(args.getString(0), args.getString(1));
return new PluginResult(PluginResult.Status.OK, obj); callbackContext.success(obj);
} catch (JSONException e) { } catch (JSONException e) {
return new PluginResult(PluginResult.Status.ERROR); callbackContext.error("");
} }
return true;
} }
else if (action.equals("captureAudio")) { else if (action.equals("captureAudio")) {
this.captureAudio(); this.captureAudio();
@ -106,10 +106,11 @@ public class Capture extends Plugin {
else if (action.equals("captureVideo")) { else if (action.equals("captureVideo")) {
this.captureVideo(duration); this.captureVideo(duration);
} }
else {
return false;
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); return true;
r.setKeepCallback(true);
return r;
} }
/** /**
@ -199,7 +200,7 @@ public class Capture extends Plugin {
private void captureAudio() { private void captureAudio() {
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION); 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 // Specify file so that large image is captured and returned
File photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), "Capture.jpg"); File photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), "Capture.jpg");
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); 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 // Introduced in API 8
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration); //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) { if (results.length() >= limit) {
// Send Uri back to JavaScript for listening to audio // 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 { } else {
// still need to capture more audio clips // still need to capture more audio clips
captureAudio(); captureAudio();
@ -298,7 +298,7 @@ public class Capture extends Plugin {
if (results.length() >= limit) { if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image // 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 { } else {
// still need to capture more images // still need to capture more images
captureImage(); captureImage();
@ -315,7 +315,7 @@ public class Capture extends Plugin {
if (results.length() >= limit) { if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing video // 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 { } else {
// still need to capture more video clips // still need to capture more video clips
captureVideo(duration); captureVideo(duration);
@ -326,7 +326,7 @@ public class Capture extends Plugin {
else if (resultCode == Activity.RESULT_CANCELED) { else if (resultCode == Activity.RESULT_CANCELED) {
// If we have partial results send them back to the user // If we have partial results send them back to the user
if (results.length() > 0) { 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 // user canceled the action
else { else {
@ -337,7 +337,7 @@ public class Capture extends Plugin {
else { else {
// If we have partial results send them back to the user // If we have partial results send them back to the user
if (results.length() > 0) { 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 // something bad happened
else { else {
@ -401,7 +401,7 @@ public class Capture extends Plugin {
* @param err * @param err
*/ */
public void fail(JSONObject err) { public void fail(JSONObject err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId); this.callbackContext.error(err);
} }

View File

@ -20,8 +20,9 @@ package org.apache.cordova;
import java.util.List; import java.util.List;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface; 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.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -33,12 +34,13 @@ import android.hardware.SensorEventListener;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.content.Context; 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. * 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 STOPPED = 0;
public static int STARTING = 1; public static int STARTING = 1;
@ -56,6 +58,8 @@ public class CompassListener extends Plugin implements SensorEventListener {
private SensorManager sensorManager;// Sensor manager private SensorManager sensorManager;// Sensor manager
Sensor mSensor; // Compass sensor returned by sensor manager Sensor mSensor; // Compass sensor returned by sensor manager
private CallbackContext callbackContext;
/** /**
* Constructor. * Constructor.
*/ */
@ -70,9 +74,10 @@ public class CompassListener extends Plugin implements SensorEventListener {
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param cordova The context of the main Activity. * @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/ */
public void setContext(CordovaInterface cordova) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.setContext(cordova); super.initialize(cordova, webView);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE); this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
} }
@ -81,13 +86,10 @@ public class CompassListener extends Plugin implements SensorEventListener {
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackS=Context The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @return True if the action was valid.
*/ */
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 = "";
try { try {
if (action.equals("start")) { if (action.equals("start")) {
this.start(); this.start();
@ -97,69 +99,43 @@ public class CompassListener extends Plugin implements SensorEventListener {
} }
else if (action.equals("getStatus")) { else if (action.equals("getStatus")) {
int i = this.getStatus(); int i = this.getStatus();
return new PluginResult(status, i); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, i));
} }
else if (action.equals("getHeading")) { else if (action.equals("getHeading")) {
// If not running, then this is an async call, so don't worry about waiting // If not running, then this is an async call, so don't worry about waiting
if (this.status != CompassListener.RUNNING) { if (this.status != CompassListener.RUNNING) {
int r = this.start(); int r = this.start();
if (r == CompassListener.ERROR_FAILED_TO_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 // Set a timeout callback on the main thread.
long timeout = 2000; Handler handler = new Handler(Looper.getMainLooper());
while ((this.status == STARTING) && (timeout > 0)) { handler.postDelayed(new Runnable() {
timeout = timeout - 100; @Override
try { public void run() {
Thread.sleep(100); CompassListener.this.timeout();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}, 2000);
} }
if (timeout == 0) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, getCompassHeading()));
return new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START);
}
}
return new PluginResult(status, getCompassHeading());
} }
else if (action.equals("setTimeout")) { else if (action.equals("setTimeout")) {
this.setTimeout(args.getLong(0)); this.setTimeout(args.getLong(0));
} }
else if (action.equals("getTimeout")) { else if (action.equals("getTimeout")) {
long l = this.getTimeout(); long l = this.getTimeout();
return new PluginResult(status, l); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
} else { } else {
// Unsupported action // Unsupported action
return new PluginResult(PluginResult.Status.INVALID_ACTION); return false;
} }
return new PluginResult(status, result);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); 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; 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;
}
/** /**
* Called when listener is to be shut down and object is being destroyed. * Called when listener is to be shut down and object is being destroyed.
@ -225,6 +201,16 @@ public class CompassListener extends Plugin implements SensorEventListener {
// TODO Auto-generated method stub // 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. * Sensor listener event.
* *

View File

@ -18,14 +18,15 @@
*/ */
package org.apache.cordova; 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.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import android.util.Log; import android.util.Log;
public class ContactManager extends Plugin { public class ContactManager extends CordovaPlugin {
private ContactAccessor contactAccessor; private ContactAccessor contactAccessor;
private static final String LOG_TAG = "Contact Query"; private static final String LOG_TAG = "Contact Query";
@ -48,20 +49,18 @@ public class ContactManager extends Plugin {
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArray 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. * @return True if the action was valid, false otherwise.
*/ */
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 = "";
/** /**
* Check to see if we are on an Android 1.X device. If we are return an error as we * 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. * do not support this as of Cordova 1.0.
*/ */
if (android.os.Build.VERSION.RELEASE.startsWith("1.")) { 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 { try {
if (action.equals("search")) { if (action.equals("search")) {
JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1));
return new PluginResult(status, res); callbackContext.success(res);
} }
else if (action.equals("save")) { else if (action.equals("save")) {
String id = contactAccessor.save(args.getJSONObject(0)); String id = contactAccessor.save(args.getJSONObject(0));
if (id != null) { if (id != null) {
JSONObject res = contactAccessor.getContactById(id); JSONObject res = contactAccessor.getContactById(id);
if (res != null) { if (res != null) {
return new PluginResult(status, res); callbackContext.success(res);
} }
} }
} }
else if (action.equals("remove")) { else if (action.equals("remove")) {
if (contactAccessor.remove(args.getString(0))) { if (contactAccessor.remove(args.getString(0))) {
return new PluginResult(status, result); callbackContext.success();
} }
} }
// If we get to this point an error has occurred else {
return new PluginResult(PluginResult.Status.ERROR, ContactManager.UNKNOWN_ERROR); return false;
}
} catch (JSONException e) { } catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), 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;
} }
} }

View File

@ -22,7 +22,8 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import org.apache.cordova.api.CallbackContext;
import android.location.Location; import android.location.Location;
import android.location.LocationListener; import android.location.LocationListener;
@ -39,8 +40,8 @@ public class CordovaLocationListener implements LocationListener {
private GeoBroker owner; private GeoBroker owner;
protected boolean running = false; protected boolean running = false;
public HashMap<String, String> watches = new HashMap<String, String>(); public HashMap<String, CallbackContext> watches = new HashMap<String, CallbackContext>();
private List<String> callbacks = new ArrayList<String>(); private List<CallbackContext> callbacks = new ArrayList<CallbackContext>();
private String TAG = "[Cordova Location Listener]"; private String TAG = "[Cordova Location Listener]";
@ -51,9 +52,9 @@ public class CordovaLocationListener implements LocationListener {
} }
protected void fail(int code, String message) { 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)) if(this.owner.isGlobalListener(this))
{ {
@ -62,17 +63,16 @@ public class CordovaLocationListener implements LocationListener {
} }
this.callbacks.clear(); this.callbacks.clear();
Iterator it = this.watches.entrySet().iterator(); Iterator<CallbackContext> it = this.watches.values().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next(); this.owner.fail(code, message, it.next());
this.owner.fail(code, message, (String)pairs.getValue());
} }
} }
private void win(Location loc) { 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)) if(this.owner.isGlobalListener(this))
{ {
@ -81,10 +81,9 @@ public class CordovaLocationListener implements LocationListener {
} }
this.callbacks.clear(); this.callbacks.clear();
Iterator it = this.watches.entrySet().iterator(); Iterator<CallbackContext> it = this.watches.values().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next(); this.owner.win(loc, it.next());
this.owner.win(loc, (String)pairs.getValue());
} }
} }
@ -150,14 +149,14 @@ public class CordovaLocationListener implements LocationListener {
return this.watches.size() + this.callbacks.size(); return this.watches.size() + this.callbacks.size();
} }
public void addWatch(String timerId, String callbackId) { public void addWatch(String timerId, CallbackContext callbackContext) {
this.watches.put(timerId, callbackId); this.watches.put(timerId, callbackContext);
if (this.size() == 1) { if (this.size() == 1) {
this.start(); this.start();
} }
} }
public void addCallback(String callbackId) { public void addCallback(CallbackContext callbackContext) {
this.callbacks.add(callbackId); this.callbacks.add(callbackContext);
if (this.size() == 1) { if (this.size() == 1) {
this.start(); this.start();
} }

View File

@ -20,9 +20,10 @@ package org.apache.cordova;
import java.util.TimeZone; 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.LOG;
import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -35,7 +36,7 @@ import android.content.IntentFilter;
import android.provider.Settings; import android.provider.Settings;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
public class Device extends Plugin { public class Device extends CordovaPlugin {
public static final String TAG = "Device"; public static final String TAG = "Device";
public static String cordovaVersion = "2.1.0"; // Cordova version 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. * get file paths associated with the Activity.
* *
* @param cordova The context of the main Activity. * @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/ */
public void setContext(CordovaInterface cordova) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.setContext(cordova); super.initialize(cordova, webView);
Device.uuid = getUuid(); Device.uuid = getUuid();
this.initTelephonyReceiver(); this.initTelephonyReceiver();
} }
@ -67,13 +69,10 @@ public class Device extends Plugin {
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @return True if the action was valid, false if not.
*/ */
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 = "";
try { try {
if (action.equals("getDeviceInfo")) { if (action.equals("getDeviceInfo")) {
JSONObject r = new JSONObject(); JSONObject r = new JSONObject();
@ -85,26 +84,16 @@ public class Device extends Plugin {
//JSONObject pg = new JSONObject(); //JSONObject pg = new JSONObject();
//pg.put("version", Device.CordovaVersion); //pg.put("version", Device.CordovaVersion);
//r.put("cordova", pg); //r.put("cordova", pg);
return new PluginResult(status, r); callbackContext.success(r);
}
return new PluginResult(status, result);
} catch (JSONException e) {
return 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;
} }
else {
return false; return false;
} }
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return true;
}
/** /**
* Unregister receiver. * Unregister receiver.

View File

@ -25,8 +25,9 @@ import java.net.URLDecoder;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface; 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.api.PluginResult;
import org.apache.cordova.file.EncodingException; import org.apache.cordova.file.EncodingException;
import org.apache.cordova.file.FileExistsException; 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. * This class provides SD card file and directory services to JavaScript.
* Only files on the SD card can be accessed. * Only files on the SD card can be accessed.
*/ */
public class FileUtils extends Plugin { public class FileUtils extends CordovaPlugin {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static final String LOG_TAG = "FileUtils"; private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data"; // The column name where the file path is stored 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 action The action to execute.
* @param args JSONArry of arguments for the plugin. * @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. * @return True if the action was valid, false otherwise.
*/ */
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 = "";
//System.out.println("FileUtils.execute("+action+")");
try { try {
if (action.equals("testSaveLocationExists")) { if (action.equals("testSaveLocationExists")) {
boolean b = DirectoryManager.testSaveLocationExists(); boolean b = DirectoryManager.testSaveLocationExists();
return new PluginResult(status, b); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
} }
else if (action.equals("getFreeDiskSpace")) { else if (action.equals("getFreeDiskSpace")) {
long l = DirectoryManager.getFreeDiskSpace(false); long l = DirectoryManager.getFreeDiskSpace(false);
return new PluginResult(status, l); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
} }
else if (action.equals("testFileExists")) { else if (action.equals("testFileExists")) {
boolean b = DirectoryManager.testFileExists(args.getString(0)); 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")) { else if (action.equals("testDirectoryExists")) {
boolean b = DirectoryManager.testFileExists(args.getString(0)); 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")) { else if (action.equals("readAsText")) {
String s = this.readAsText(args.getString(0), args.getString(1)); 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")) { else if (action.equals("readAsDataURL")) {
String s = this.readAsDataURL(args.getString(0)); 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")) { else if (action.equals("write")) {
long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2)); 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")) { else if (action.equals("truncate")) {
long fileSize = this.truncateFile(args.getString(0), args.getLong(1)); 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")) { else if (action.equals("requestFileSystem")) {
long size = args.optLong(1); long size = args.optLong(1);
if (size != 0) { if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
if (size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
return new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR); } else {
}
}
JSONObject obj = requestFileSystem(args.getInt(0)); JSONObject obj = requestFileSystem(args.getInt(0));
return new PluginResult(status, obj); callbackContext.success(obj);
}
} }
else if (action.equals("resolveLocalFileSystemURI")) { else if (action.equals("resolveLocalFileSystemURI")) {
JSONObject obj = resolveLocalFileSystemURI(args.getString(0)); JSONObject obj = resolveLocalFileSystemURI(args.getString(0));
return new PluginResult(status, obj); callbackContext.success(obj);
} }
else if (action.equals("getMetadata")) { 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")) { else if (action.equals("getFileMetadata")) {
JSONObject obj = getFileMetadata(args.getString(0)); JSONObject obj = getFileMetadata(args.getString(0));
return new PluginResult(status, obj); callbackContext.success(obj);
} }
else if (action.equals("getParent")) { else if (action.equals("getParent")) {
JSONObject obj = getParent(args.getString(0)); JSONObject obj = getParent(args.getString(0));
return new PluginResult(status, obj); callbackContext.success(obj);
} }
else if (action.equals("getDirectory")) { else if (action.equals("getDirectory")) {
JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), true); 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")) { else if (action.equals("getFile")) {
JSONObject obj = getFile(args.getString(0), args.getString(1), args.optJSONObject(2), false); 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")) { else if (action.equals("remove")) {
boolean success; boolean success;
@ -169,51 +165,54 @@ public class FileUtils extends Plugin {
if (success) { if (success) {
notifyDelete(args.getString(0)); notifyDelete(args.getString(0));
return new PluginResult(status); callbackContext.success();
} else { } else {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
} }
} }
else if (action.equals("removeRecursively")) { else if (action.equals("removeRecursively")) {
boolean success = removeRecursively(args.getString(0)); boolean success = removeRecursively(args.getString(0));
if (success) { if (success) {
return new PluginResult(status); callbackContext.success();
} else { } else {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
} }
} }
else if (action.equals("moveTo")) { else if (action.equals("moveTo")) {
JSONObject entry = transferTo(args.getString(0), args.getString(1), args.getString(2), true); 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")) { else if (action.equals("copyTo")) {
JSONObject entry = transferTo(args.getString(0), args.getString(1), args.getString(2), false); 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")) { else if (action.equals("readEntries")) {
JSONArray entries = readEntries(args.getString(0)); 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) { } catch (FileNotFoundException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR); callbackContext.error(FileUtils.NOT_FOUND_ERR);
} catch (FileExistsException e) { } catch (FileExistsException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.PATH_EXISTS_ERR); callbackContext.error(FileUtils.PATH_EXISTS_ERR);
} catch (NoModificationAllowedException e) { } catch (NoModificationAllowedException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
} catch (JSONException e) { } catch (JSONException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NO_MODIFICATION_ALLOWED_ERR); callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
} catch (InvalidModificationException e) { } catch (InvalidModificationException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.INVALID_MODIFICATION_ERR); callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.ENCODING_ERR); callbackContext.error(FileUtils.ENCODING_ERR);
} catch (IOException e) { } catch (IOException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.INVALID_MODIFICATION_ERR); callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
} catch (EncodingException e) { } catch (EncodingException e) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.ENCODING_ERR); callbackContext.error(FileUtils.ENCODING_ERR);
} catch (TypeMismatchException e) { } 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) { private void notifyDelete(String filePath) {
String newFilePath = stripFileProtocol(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 + " = ?", MediaStore.Images.Media.DATA + " = ?",
new String[] { newFilePath }); new String[] { newFilePath });
} }

View File

@ -18,7 +18,8 @@
*/ */
package org.apache.cordova; 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.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; 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 * 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 GPSListener gpsListener;
private NetworkListener networkListener; private NetworkListener networkListener;
private LocationManager locationManager; private LocationManager locationManager;
@ -50,10 +51,10 @@ public class GeoBroker extends Plugin {
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @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) { if (this.locationManager == null) {
this.locationManager = (LocationManager) this.cordova.getActivity().getSystemService(Context.LOCATION_SERVICE); this.locationManager = (LocationManager) this.cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
this.networkListener = new NetworkListener(this.locationManager, this); this.networkListener = new NetworkListener(this.locationManager, this);
@ -78,23 +79,27 @@ public class GeoBroker extends Plugin {
if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) { if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) {
result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last)); result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
} else { } else {
this.getCurrentLocation(callbackId, enableHighAccuracy); this.getCurrentLocation(callbackContext, enableHighAccuracy);
} }
} }
else if (action.equals("addWatch")) { else if (action.equals("addWatch")) {
String id = args.getString(0); String id = args.getString(0);
boolean enableHighAccuracy = args.getBoolean(1); boolean enableHighAccuracy = args.getBoolean(1);
this.addWatch(id, callbackId, enableHighAccuracy); this.addWatch(id, callbackContext, enableHighAccuracy);
} }
else if (action.equals("clearWatch")) { else if (action.equals("clearWatch")) {
String id = args.getString(0); String id = args.getString(0);
this.clearWatch(id); this.clearWatch(id);
} }
else {
return false;
}
} catch (JSONException e) { } catch (JSONException e) {
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
} }
} }
return result; callbackContext.sendPluginResult(result);
return true;
} }
@ -103,33 +108,22 @@ public class GeoBroker extends Plugin {
this.networkListener.clearWatch(id); this.networkListener.clearWatch(id);
} }
private void getCurrentLocation(String callbackId, boolean enableHighAccuracy) { private void getCurrentLocation(CallbackContext callbackContext, boolean enableHighAccuracy) {
if (enableHighAccuracy) { if (enableHighAccuracy) {
this.gpsListener.addCallback(callbackId); this.gpsListener.addCallback(callbackContext);
} else { } 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) { if (enableHighAccuracy) {
this.gpsListener.addWatch(timerId, callbackId); this.gpsListener.addWatch(timerId, callbackContext);
} else { } 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. * Called when the activity is to be shut down.
* Stop listener. * Stop listener.
@ -172,9 +166,9 @@ public class GeoBroker extends Plugin {
return o; 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)); 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 * @param msg The error message
* @throws JSONException * @throws JSONException
*/ */
public void fail(int code, String msg, String callbackId) { public void fail(int code, String msg, CallbackContext callbackContext) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
String backup = null; String backup = null;
try { try {
@ -201,7 +195,7 @@ public class GeoBroker extends Plugin {
result = new PluginResult(PluginResult.Status.ERROR, backup); result = new PluginResult(PluginResult.Status.ERROR, backup);
} }
this.error(result, callbackId); callbackContext.sendPluginResult(result);
} }
public boolean isGlobalListener(CordovaLocationListener listener) public boolean isGlobalListener(CordovaLocationListener listener)

View File

@ -33,7 +33,8 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.TimeZone; 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.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; 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 //GlobalizationCommand Plugin Actions
public static final String GETLOCALENAME = "getLocaleName"; public static final String GETLOCALENAME = "getLocaleName";
public static final String DATETOSTRING = "dateToString"; public static final String DATETOSTRING = "dateToString";
@ -85,54 +86,45 @@ public class Globalization extends Plugin {
public static final String CURRENCYCODE = "currencyCode"; public static final String CURRENCYCODE = "currencyCode";
@Override @Override
public PluginResult execute(String action, JSONArray data, String callbackId) { public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
PluginResult.Status status = PluginResult.Status.OK;
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try{ try{
if (action.equals(GETLOCALENAME)){ if (action.equals(GETLOCALENAME)){
obj = getLocaleName(); obj = getLocaleName();
return new PluginResult(status, obj);
}else if (action.equals(GETPREFERREDLANGUAGE)){ }else if (action.equals(GETPREFERREDLANGUAGE)){
obj = getPreferredLanguage(); obj = getPreferredLanguage();
return new PluginResult(status, obj);
} else if (action.equalsIgnoreCase(DATETOSTRING)) { } else if (action.equalsIgnoreCase(DATETOSTRING)) {
obj = getDateToString(data); obj = getDateToString(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(STRINGTODATE)){ }else if(action.equalsIgnoreCase(STRINGTODATE)){
obj = getStringtoDate(data); obj = getStringtoDate(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(GETDATEPATTERN)){ }else if(action.equalsIgnoreCase(GETDATEPATTERN)){
obj = getDatePattern(data); obj = getDatePattern(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(GETDATENAMES)){ }else if(action.equalsIgnoreCase(GETDATENAMES)){
obj = getDateNames(data); obj = getDateNames(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(ISDAYLIGHTSAVINGSTIME)){ }else if(action.equalsIgnoreCase(ISDAYLIGHTSAVINGSTIME)){
obj = getIsDayLightSavingsTime(data); obj = getIsDayLightSavingsTime(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(GETFIRSTDAYOFWEEK)){ }else if(action.equalsIgnoreCase(GETFIRSTDAYOFWEEK)){
obj = getFirstDayOfWeek(data); obj = getFirstDayOfWeek(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(NUMBERTOSTRING)){ }else if(action.equalsIgnoreCase(NUMBERTOSTRING)){
obj = getNumberToString(data); obj = getNumberToString(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(STRINGTONUMBER)){ }else if(action.equalsIgnoreCase(STRINGTONUMBER)){
obj = getStringToNumber(data); obj = getStringToNumber(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(GETNUMBERPATTERN)){ }else if(action.equalsIgnoreCase(GETNUMBERPATTERN)){
obj = getNumberPattern(data); obj = getNumberPattern(data);
return new PluginResult(PluginResult.Status.OK, obj);
}else if(action.equalsIgnoreCase(GETCURRENCYPATTERN)){ }else if(action.equalsIgnoreCase(GETCURRENCYPATTERN)){
obj = getCurrencyPattern(data); obj = getCurrencyPattern(data);
return new PluginResult(PluginResult.Status.OK, obj); }else {
return false;
} }
callbackContext.success(obj);
}catch (GlobalizationError ge){ }catch (GlobalizationError ge){
return new PluginResult(PluginResult.Status.ERROR, ge.toJson()); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, ge.toJson()));
}catch (Exception e){ }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 * @Description: Returns the string identifier for the client's current locale setting

View File

@ -18,8 +18,9 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface; 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.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
@ -31,7 +32,7 @@ import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.util.Log; import android.util.Log;
public class NetworkManager extends Plugin { public class NetworkManager extends CordovaPlugin {
public static int NOT_REACHABLE = 0; public static int NOT_REACHABLE = 0;
public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; 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 static final String LOG_TAG = "NetworkManager";
private String connectionCallbackId; private CallbackContext connectionCallbackContext;
private boolean registered = false; private boolean registered = false;
ConnectivityManager sockMan; ConnectivityManager sockMan;
@ -86,11 +87,12 @@ public class NetworkManager extends Plugin {
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param cordova The context of the main Activity. * @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/ */
public void setContext(CordovaInterface cordova) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.setContext(cordova); super.initialize(cordova, webView);
this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 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 // We need to listen to connectivity events to update navigator.connection
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
@ -101,7 +103,7 @@ public class NetworkManager extends Plugin {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// (The null check is for the ARM Emulator, please use Intel Emulator for better results) // (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)); updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
} }
}; };
@ -116,33 +118,20 @@ public class NetworkManager extends Plugin {
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @return True if the action was valid, false otherwise.
*/ */
public PluginResult execute(String action, JSONArray args, String callbackId) { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
String result = "Unsupported Operation: " + action;
if (action.equals("getConnectionInfo")) { if (action.equals("getConnectionInfo")) {
this.connectionCallbackId = callbackId; this.connectionCallbackContext = callbackContext;
NetworkInfo info = sockMan.getActiveNetworkInfo(); NetworkInfo info = sockMan.getActiveNetworkInfo();
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, this.getConnectionInfo(info)); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, this.getConnectionInfo(info));
pluginResult.setKeepCallback(true); pluginResult.setKeepCallback(true);
return pluginResult; callbackContext.sendPluginResult(pluginResult);
}
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 true;
} }
return false;
}
/** /**
* Stop network receiver. * Stop network receiver.
@ -206,10 +195,10 @@ public class NetworkManager extends Plugin {
* @param connection the network info to set as navigator.connection * @param connection the network info to set as navigator.connection
*/ */
private void sendUpdate(String type) { private void sendUpdate(String type) {
if (connectionCallbackId != null) { if (connectionCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, type); PluginResult result = new PluginResult(PluginResult.Status.OK, type);
result.setKeepCallback(true); result.setKeepCallback(true);
this.success(result, this.connectionCallbackId); connectionCallbackContext.sendPluginResult(result);
} }
webView.postMessage("networkconnection", type); webView.postMessage("networkconnection", type);

View File

@ -18,8 +18,9 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface; 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.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -35,7 +36,7 @@ import android.os.Vibrator;
/** /**
* This class provides access to notifications on the device. * This class provides access to notifications on the device.
*/ */
public class Notification extends Plugin { public class Notification extends CordovaPlugin {
public int confirmResult = -1; public int confirmResult = -1;
public ProgressDialog spinnerDialog = null; public ProgressDialog spinnerDialog = null;
@ -51,14 +52,11 @@ public class Notification extends Plugin {
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArray 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. * @return True when the action was valid, false otherwise.
*/ */
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 = "";
try { try {
if (action.equals("beep")) { if (action.equals("beep")) {
this.beep(args.getLong(0)); this.beep(args.getLong(0));
@ -67,16 +65,12 @@ public class Notification extends Plugin {
this.vibrate(args.getLong(0)); this.vibrate(args.getLong(0));
} }
else if (action.equals("alert")) { else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackId); this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); return true;
r.setKeepCallback(true);
return r;
} }
else if (action.equals("confirm")) { else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackId); this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackContext);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); return true;
r.setKeepCallback(true);
return r;
} }
else if (action.equals("activityStart")) { else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1)); this.activityStart(args.getString(0), args.getString(1));
@ -93,43 +87,16 @@ public class Notification extends Plugin {
else if (action.equals("progressStop")) { else if (action.equals("progressStop")) {
this.progressStop(); this.progressStop();
} }
return new PluginResult(status, result);
} catch (JSONException e) {
return 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("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 { else {
return false; return false;
} }
// Only alert and confirm are async.
callbackContext.success();
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return true;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@ -180,12 +147,11 @@ public class Notification extends Plugin {
* @param message The message the alert should display * @param message The message the alert should display
* @param title The title of the alert * @param title The title of the alert
* @param buttonLabel The label of the button * @param buttonLabel The label of the button
* @param callbackId The callback id * @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 CordovaInterface cordova = this.cordova;
final Notification notification = this;
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
public void run() { public void run() {
@ -198,7 +164,7 @@ public class Notification extends Plugin {
new AlertDialog.OnClickListener() { new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 0), callbackId); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
} }
}); });
dlg.create(); dlg.create();
@ -216,12 +182,11 @@ public class Notification extends Plugin {
* @param message The message the dialog should display * @param message The message the dialog should display
* @param title The title of the dialog * @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons) * @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackId The callback id * @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 CordovaInterface cordova = this.cordova;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(","); final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
@ -237,7 +202,7 @@ public class Notification extends Plugin {
new AlertDialog.OnClickListener() { new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); 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() { new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); 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() { new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); 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.dismiss();
this.spinnerDialog = null; this.spinnerDialog = null;
} }
final Notification notification = this;
final CordovaInterface cordova = this.cordova; final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
public void run() { 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() { new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null; Notification.this.spinnerDialog = null;
} }
}); });
} }

View File

@ -19,26 +19,25 @@
package org.apache.cordova; package org.apache.cordova;
import org.apache.cordova.api.Plugin; import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray; import org.json.JSONArray;
public class SplashScreen extends Plugin { public class SplashScreen extends CordovaPlugin {
@Override @Override
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 = "";
if (action.equals("hide")) { if (action.equals("hide")) {
this.webView.postMessage("splashscreen", "hide"); this.webView.postMessage("splashscreen", "hide");
} else if (action.equals("show")){ } else if (action.equals("show")){
this.webView.postMessage("splashscreen", "show"); this.webView.postMessage("splashscreen", "show");
} }
else { else {
status = PluginResult.Status.INVALID_ACTION; return false;
} }
return new PluginResult(status, result);
callbackContext.success();
return true;
} }
} }

View File

@ -20,7 +20,8 @@ package org.apache.cordova;
import java.io.File; 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.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; 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 * Android 3.0 devices. It is not used for other versions of Android, since
* HTML5 database is built in to the browser. * HTML5 database is built in to the browser.
*/ */
public class Storage extends Plugin { public class Storage extends CordovaPlugin {
// Data Definition Language // Data Definition Language
private static final String ALTER = "alter"; private static final String ALTER = "alter";
@ -60,14 +61,11 @@ public class Storage extends Plugin {
* The action to execute. * The action to execute.
* @param args * @param args
* JSONArry of arguments for the plugin. * JSONArry of arguments for the plugin.
* @param callbackId * @param callbackContext
* The callback id used when calling back into JavaScript. * The callback context used when calling back into JavaScript.
* @return A PluginResult object with a status and message. * @return True if the action was valid, false otherwise.
*/ */
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 = "";
try { try {
if (action.equals("openDatabase")) { if (action.equals("openDatabase")) {
this.openDatabase(args.getString(0), args.getString(1), 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)); this.executeSql(args.getString(0), s, args.getString(2));
} }
return new PluginResult(status, result); else {
return false;
}
callbackContext.success();
} catch (JSONException e) { } 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; return true;
} }
@ -169,7 +159,7 @@ public class Storage extends Plugin {
try { try {
if (isDDL(query)) { if (isDDL(query)) {
this.myDb.execSQL(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 { else {
Cursor myCursor = this.myDb.rawQuery(query, params); Cursor myCursor = this.myDb.rawQuery(query, params);
@ -182,7 +172,7 @@ public class Storage extends Plugin {
System.out.println("Storage.executeSql(): Error=" + ex.getMessage()); System.out.println("Storage.executeSql(): Error=" + ex.getMessage());
// Send error message back to JavaScript // 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 // 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 + ");");
} }
} }

View File

@ -1,5 +1,7 @@
package org.apache.cordova.api; package org.apache.cordova.api;
import org.json.JSONArray;
import android.util.Log; import android.util.Log;
import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebView;
@ -60,6 +62,15 @@ public class CallbackContext {
sendPluginResult(new PluginResult(PluginResult.Status.OK, message)); 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 * Helper for success callbacks that just returns the Status.OK by default
* *
@ -87,4 +98,14 @@ public class CallbackContext {
public void error(String message) { public void error(String message) {
sendPluginResult(new PluginResult(PluginResult.Status.ERROR, 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));
}
} }

View File

@ -33,7 +33,8 @@ public class CordovaPlugin {
public CordovaInterface cordova; 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) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
assert this.cordova == null; assert this.cordova == null;
@ -52,7 +53,7 @@ public class CordovaPlugin {
* *
* @param action The action to execute. * @param action The action to execute.
* @param rawArgs The exec() arguments in JSON form. * @param rawArgs The exec() arguments in JSON form.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid. * @return Whether the action was valid.
*/ */
public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException { public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
@ -71,7 +72,7 @@ public class CordovaPlugin {
* *
* @param action The action to execute. * @param action The action to execute.
* @param args The exec() arguments. * @param args The exec() arguments.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid. * @return Whether the action was valid.
*/ */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {