Changing all tabs to spaces

This commit is contained in:
macdonst 2012-06-05 09:49:50 -04:00
parent adfdb16dc5
commit 6d1e0356ac
57 changed files with 2837 additions and 2864 deletions

View File

@ -1,33 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>Cordova</name> <name>Cordova</name>
<comment></comment> <comment></comment>
<projects> <projects>
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name> <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name> <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name> <name>org.eclipse.jdt.core.javabuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name> <name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature> <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
</natures> </natures>
</projectDescription> </projectDescription>

View File

@ -18,16 +18,16 @@
under the License. under the License.
--> -->
<cordova> <cordova>
<!-- <!--
access elements control the Android whitelist. access elements control the Android whitelist.
Domains are assumed blocked unless set otherwise Domains are assumed blocked unless set otherwise
--> -->
<access origin="http://127.0.0.1*"/> <!-- allow local pages --> <access origin="http://127.0.0.1*"/> <!-- allow local pages -->
<!-- <access origin="https://example.com" /> allow any secure requests to example.com --> <!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
<!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www --> <!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
<!-- <access origin=".*"/> Allow all domains, suggested development use only --> <!-- <access origin=".*"/> Allow all domains, suggested development use only -->
<log level="DEBUG"/> <log level="DEBUG"/>
<preference name="classicRender" value="true" /> <preference name="classicRender" value="true" />

View File

@ -23,31 +23,31 @@ import org.json.JSONObject;
public class PluginResult extends org.apache.cordova.api.PluginResult { public class PluginResult extends org.apache.cordova.api.PluginResult {
public PluginResult(Status status) { public PluginResult(Status status) {
super(status); super(status);
} }
public PluginResult(Status status, String message) { public PluginResult(Status status, String message) {
super(status, message);
}
public PluginResult(Status status, JSONArray message) {
super(status, message); super(status, message);
} }
public PluginResult(Status status, JSONObject message) { public PluginResult(Status status, JSONArray message) {
super(status, message); super(status, message);
} }
public PluginResult(Status status, int i) { public PluginResult(Status status, JSONObject message) {
super(status, message);
}
public PluginResult(Status status, int i) {
super(status, i); super(status, i);
} }
public PluginResult(Status status, float f) { public PluginResult(Status status, float f) {
super(status, f); super(status, f);
} }
public PluginResult(Status status, boolean b) { public PluginResult(Status status, boolean b) {
super(status, b); super(status, b);
} }
} }

View File

@ -18,12 +18,7 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.Plugin; import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
@ -36,8 +31,6 @@ import android.hardware.Sensor;
import android.hardware.SensorEvent; import android.hardware.SensorEvent;
import android.hardware.SensorEventListener; import android.hardware.SensorEventListener;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.location.Location;
import android.util.Log;
import android.content.Context; import android.content.Context;
/** /**
@ -134,42 +127,42 @@ public class AccelListener extends Plugin implements SensorEventListener {
* @return status of listener * @return status of listener
*/ */
private int start() { private int start() {
// If already starting or running, then just return // If already starting or running, then just return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) { if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
return this.status; return this.status;
} }
this.setStatus(AccelListener.STARTING); this.setStatus(AccelListener.STARTING);
// Get accelerometer from sensor manager // Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener // If found, then register as listener
if ((list != null) && (list.size() > 0)) { if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0); this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI); this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
this.setStatus(AccelListener.STARTING); this.setStatus(AccelListener.STARTING);
} else { } else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START); this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to."); this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
return this.status; return this.status;
} }
// Wait until running // Wait until running
long timeout = 2000; long timeout = 2000;
while ((this.status == STARTING) && (timeout > 0)) { while ((this.status == STARTING) && (timeout > 0)) {
timeout = timeout - 100; timeout = timeout - 100;
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (timeout == 0) { if (timeout == 0) {
this.setStatus(AccelListener.ERROR_FAILED_TO_START); this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "Accelerometer could not be started."); this.fail(AccelListener.ERROR_FAILED_TO_START, "Accelerometer could not be started.");
} }
return this.status; return this.status;
} }
/** /**
@ -190,7 +183,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
* @param accuracy * @param accuracy
*/ */
public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Only look at accelerometer events // Only look at accelerometer events
if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) { if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return; return;
} }

View File

@ -45,30 +45,30 @@ public class App extends Plugin {
String result = ""; String result = "";
try { try {
if (action.equals("clearCache")) { if (action.equals("clearCache")) {
this.clearCache(); this.clearCache();
}
else if (action.equals("loadUrl")) {
this.loadUrl(args.getString(0), args.optJSONObject(1));
} }
else if (action.equals("cancelLoadUrl")) { else if (action.equals("loadUrl")) {
this.cancelLoadUrl(); this.loadUrl(args.getString(0), args.optJSONObject(1));
} }
else if (action.equals("clearHistory")) { else if (action.equals("cancelLoadUrl")) {
this.clearHistory(); this.cancelLoadUrl();
}
else if (action.equals("clearHistory")) {
this.clearHistory();
} }
else if (action.equals("backHistory")) { else if (action.equals("backHistory")) {
this.backHistory(); this.backHistory();
} }
else if (action.equals("overrideBackbutton")) { else if (action.equals("overrideBackbutton")) {
this.overrideBackbutton(args.getBoolean(0)); this.overrideBackbutton(args.getBoolean(0));
} }
else if (action.equals("isBackbuttonOverridden")) { else if (action.equals("isBackbuttonOverridden")) {
boolean b = this.isBackbuttonOverridden(); boolean b = this.isBackbuttonOverridden();
return new PluginResult(status, b); return new PluginResult(status, b);
} }
else if (action.equals("exitApp")) { else if (action.equals("exitApp")) {
this.exitApp(); this.exitApp();
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} catch (JSONException e) { } catch (JSONException e) {
@ -80,85 +80,85 @@ public class App extends Plugin {
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/** /**
* Clear the resource cache. * Clear the resource cache.
*/ */
public void clearCache() { public void clearCache() {
((DroidGap)this.ctx).clearCache(); ((DroidGap)this.ctx).clearCache();
} }
/** /**
* Load the url into the webview. * Load the url into the webview.
* *
* @param url * @param url
* @param props Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...) * @param props Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...)
* @throws JSONException * @throws JSONException
*/ */
public void loadUrl(String url, JSONObject props) throws JSONException { public void loadUrl(String url, JSONObject props) throws JSONException {
LOG.d("App", "App.loadUrl("+url+","+props+")"); LOG.d("App", "App.loadUrl("+url+","+props+")");
int wait = 0; int wait = 0;
boolean openExternal = false; boolean openExternal = false;
boolean clearHistory = false; boolean clearHistory = false;
// If there are properties, then set them on the Activity // If there are properties, then set them on the Activity
HashMap<String, Object> params = new HashMap<String, Object>(); HashMap<String, Object> params = new HashMap<String, Object>();
if (props != null) { if (props != null) {
JSONArray keys = props.names(); JSONArray keys = props.names();
for (int i=0; i<keys.length(); i++) { for (int i=0; i<keys.length(); i++) {
String key = keys.getString(i); String key = keys.getString(i);
if (key.equals("wait")) { if (key.equals("wait")) {
wait = props.getInt(key); wait = props.getInt(key);
} }
else if (key.equalsIgnoreCase("openexternal")) { else if (key.equalsIgnoreCase("openexternal")) {
openExternal = props.getBoolean(key); openExternal = props.getBoolean(key);
} }
else if (key.equalsIgnoreCase("clearhistory")) { else if (key.equalsIgnoreCase("clearhistory")) {
clearHistory = props.getBoolean(key); clearHistory = props.getBoolean(key);
} }
else { else {
Object value = props.get(key); Object value = props.get(key);
if (value == null) { if (value == null) {
} }
else if (value.getClass().equals(String.class)) { else if (value.getClass().equals(String.class)) {
params.put(key, (String)value); params.put(key, (String)value);
} }
else if (value.getClass().equals(Boolean.class)) { else if (value.getClass().equals(Boolean.class)) {
params.put(key, (Boolean)value); params.put(key, (Boolean)value);
} }
else if (value.getClass().equals(Integer.class)) { else if (value.getClass().equals(Integer.class)) {
params.put(key, (Integer)value); params.put(key, (Integer)value);
} }
} }
} }
} }
// If wait property, then delay loading // If wait property, then delay loading
if (wait > 0) { if (wait > 0) {
try { try {
synchronized(this) { synchronized(this) {
this.wait(wait); this.wait(wait);
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
((DroidGap)this.ctx).showWebPage(url, openExternal, clearHistory, params); ((DroidGap)this.ctx).showWebPage(url, openExternal, clearHistory, params);
} }
/** /**
* Cancel loadUrl before it has been loaded. * Cancel loadUrl before it has been loaded.
*/ */
public void cancelLoadUrl() { public void cancelLoadUrl() {
((DroidGap)this.ctx).cancelLoadUrl(); ((DroidGap)this.ctx).cancelLoadUrl();
} }
/** /**
* Clear page history for the app. * Clear page history for the app.
*/ */
public void clearHistory() { public void clearHistory() {
((DroidGap)this.ctx).clearHistory(); ((DroidGap)this.ctx).clearHistory();
} }
/** /**
@ -176,8 +176,8 @@ public class App extends Plugin {
* @param override T=override, F=cancel override * @param override T=override, F=cancel override
*/ */
public void overrideBackbutton(boolean override) { public void overrideBackbutton(boolean override) {
LOG.i("DroidGap", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!"); LOG.i("DroidGap", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!");
((DroidGap)this.ctx).bound = override; ((DroidGap)this.ctx).bound = override;
} }
/** /**
@ -186,13 +186,13 @@ public class App extends Plugin {
* @return boolean * @return boolean
*/ */
public boolean isBackbuttonOverridden() { public boolean isBackbuttonOverridden() {
return ((DroidGap)this.ctx).bound; return ((DroidGap)this.ctx).bound;
} }
/** /**
* Exit the Android application. * Exit the Android application.
*/ */
public void exitApp() { public void exitApp() {
((DroidGap)this.ctx).endActivity(); ((DroidGap)this.ctx).endActivity();
} }
} }

View File

@ -22,14 +22,12 @@ 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.LOG;
import org.apache.cordova.api.Plugin; 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;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry;
/** /**
* This class called by CordovaActivity to play and record audio. * This class called by CordovaActivity to play and record audio.
@ -45,97 +43,97 @@ import java.util.Map.Entry;
public class AudioHandler extends Plugin { public class AudioHandler extends Plugin {
public static String TAG = "AudioHandler"; public static String TAG = "AudioHandler";
HashMap<String,AudioPlayer> players; // Audio player object HashMap<String,AudioPlayer> players; // Audio player object
ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in
/** /**
* Constructor. * Constructor.
*/ */
public AudioHandler() { public AudioHandler() {
this.players = new HashMap<String,AudioPlayer>(); this.players = new HashMap<String,AudioPlayer>();
this.pausedForPhone = new ArrayList<AudioPlayer>(); this.pausedForPhone = new ArrayList<AudioPlayer>();
} }
/** /**
* 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 callbackId 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 PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK; PluginResult.Status status = PluginResult.Status.OK;
String result = ""; String result = "";
try { try {
if (action.equals("startRecordingAudio")) { if (action.equals("startRecordingAudio")) {
this.startRecordingAudio(args.getString(0), args.getString(1)); this.startRecordingAudio(args.getString(0), args.getString(1));
} }
else if (action.equals("stopRecordingAudio")) { else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0)); this.stopRecordingAudio(args.getString(0));
} }
else if (action.equals("startPlayingAudio")) { else if (action.equals("startPlayingAudio")) {
this.startPlayingAudio(args.getString(0), args.getString(1)); this.startPlayingAudio(args.getString(0), args.getString(1));
} }
else if (action.equals("seekToAudio")) { else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1)); this.seekToAudio(args.getString(0), args.getInt(1));
} }
else if (action.equals("pausePlayingAudio")) { else if (action.equals("pausePlayingAudio")) {
this.pausePlayingAudio(args.getString(0)); this.pausePlayingAudio(args.getString(0));
} }
else if (action.equals("stopPlayingAudio")) { else if (action.equals("stopPlayingAudio")) {
this.stopPlayingAudio(args.getString(0)); this.stopPlayingAudio(args.getString(0));
} else if (action.equals("setVolume")) { } else if (action.equals("setVolume")) {
try { try {
this.setVolume(args.getString(0), Float.parseFloat(args.getString(1))); this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
//no-op //no-op
} }
} 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); return new PluginResult(status, f);
} }
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); return new PluginResult(status, f);
} }
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); return new PluginResult(status, b);
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION); return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} }
} }
/** /**
* Identifies if action to be executed returns a value and should be run synchronously. * Identifies if action to be executed returns a value and should be run synchronously.
* *
* @param action The action to execute * @param action The action to execute
* @return T=returns value * @return T=returns value
*/ */
public boolean isSynch(String action) { public boolean isSynch(String action) {
if (action.equals("getCurrentPositionAudio")) { if (action.equals("getCurrentPositionAudio")) {
return true; return true;
} }
else if (action.equals("getDurationAudio")) { else if (action.equals("getDurationAudio")) {
return true; return true;
} }
return false; return false;
} }
/** /**
* Stop all audio players and recorders. * Stop all audio players and recorders.
*/ */
public void onDestroy() { public void onDestroy() {
for (AudioPlayer audio : this.players.values()) { for (AudioPlayer audio : this.players.values()) {
audio.destroy(); audio.destroy();
} }
this.players.clear(); this.players.clear();
} }
/** /**
* Called when a message is sent to plugin. * Called when a message is sent to plugin.
@ -175,140 +173,140 @@ public class AudioHandler extends Plugin {
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/** /**
* Release the audio player instance to save memory. * Release the audio player instance to save memory.
* *
* @param id The id of the audio player * @param id The id of the audio player
*/ */
private boolean release(String id) { private boolean release(String id) {
if (!this.players.containsKey(id)) { if (!this.players.containsKey(id)) {
return false; return false;
} }
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
this.players.remove(id); this.players.remove(id);
audio.destroy(); audio.destroy();
return true; return true;
} }
/** /**
* Start recording and save the specified file. * Start recording and save the specified file.
* *
* @param id The id of the audio player * @param id The id of the audio player
* @param file The name of the file * @param file The name of the file
*/ */
public void startRecordingAudio(String id, String file) { public void startRecordingAudio(String id, String file) {
// If already recording, then just return; // If already recording, then just return;
if (this.players.containsKey(id)) { if (this.players.containsKey(id)) {
return; return;
} }
AudioPlayer audio = new AudioPlayer(this, id); AudioPlayer audio = new AudioPlayer(this, id);
this.players.put(id, audio); this.players.put(id, audio);
audio.startRecording(file); audio.startRecording(file);
} }
/** /**
* Stop recording and save to the file specified when recording started. * Stop recording and save to the file specified when recording started.
* *
* @param id The id of the audio player * @param id The id of the audio player
*/ */
public void stopRecordingAudio(String id) { public void stopRecordingAudio(String id) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
audio.stopRecording(); audio.stopRecording();
this.players.remove(id); this.players.remove(id);
} }
} }
/** /**
* Start or resume playing audio file. * Start or resume playing audio file.
* *
* @param id The id of the audio player * @param id The id of the audio player
* @param file The name of the audio file. * @param file The name of the audio file.
*/ */
public void startPlayingAudio(String id, String file) { public void startPlayingAudio(String id, String file) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio == null) { if (audio == null) {
audio = new AudioPlayer(this, id); audio = new AudioPlayer(this, id);
this.players.put(id, audio); this.players.put(id, audio);
} }
audio.startPlaying(file); audio.startPlaying(file);
} }
/** /**
* Seek to a location. * Seek to a location.
* *
* *
* @param id The id of the audio player * @param id The id of the audio player
* @param miliseconds int: number of milliseconds to skip 1000 = 1 second * @param miliseconds int: number of milliseconds to skip 1000 = 1 second
*/ */
public void seekToAudio(String id, int milliseconds) { public void seekToAudio(String id, int milliseconds) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
audio.seekToPlaying(milliseconds); audio.seekToPlaying(milliseconds);
} }
} }
/** /**
* Pause playing. * Pause playing.
* *
* @param id The id of the audio player * @param id The id of the audio player
*/ */
public void pausePlayingAudio(String id) { public void pausePlayingAudio(String id) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
audio.pausePlaying(); audio.pausePlaying();
} }
} }
/** /**
* Stop playing the audio file. * Stop playing the audio file.
* *
* @param id The id of the audio player * @param id The id of the audio player
*/ */
public void stopPlayingAudio(String id) { public void stopPlayingAudio(String id) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
audio.stopPlaying(); audio.stopPlaying();
//audio.destroy(); //audio.destroy();
//this.players.remove(id); //this.players.remove(id);
} }
} }
/** /**
* Get current position of playback. * Get current position of playback.
* *
* @param id The id of the audio player * @param id The id of the audio player
* @return position in msec * @return position in msec
*/ */
public float getCurrentPositionAudio(String id) { public float getCurrentPositionAudio(String id) {
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
return(audio.getCurrentPosition()/1000.0f); return(audio.getCurrentPosition()/1000.0f);
} }
return -1; return -1;
} }
/** /**
* Get the duration of the audio file. * Get the duration of the audio file.
* *
* @param id The id of the audio player * @param id The id of the audio player
* @param file The name of the audio file. * @param file The name of the audio file.
* @return The duration in msec. * @return The duration in msec.
*/ */
public float getDurationAudio(String id, String file) { public float getDurationAudio(String id, String file) {
// Get audio file // Get audio file
AudioPlayer audio = this.players.get(id); AudioPlayer audio = this.players.get(id);
if (audio != null) { if (audio != null) {
return(audio.getDuration(file)); return(audio.getDuration(file));
} }
// If not already open, then open the file // If not already open, then open the file
else { else {
audio = new AudioPlayer(this, id); audio = new AudioPlayer(this, id);
this.players.put(id, audio); this.players.put(id, audio);
return(audio.getDuration(file)); return(audio.getDuration(file));
} }
} }
/** /**
@ -317,16 +315,16 @@ public class AudioHandler extends Plugin {
* @param output 1=earpiece, 2=speaker * @param output 1=earpiece, 2=speaker
*/ */
public void setAudioOutputDevice(int output) { public void setAudioOutputDevice(int output) {
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE); AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
if (output == 2) { if (output == 2) {
audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL); audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);
} }
else if (output == 1) { else if (output == 1) {
audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
} }
else { else {
System.out.println("AudioHandler.setAudioOutputDevice() Error: Unknown output device."); System.out.println("AudioHandler.setAudioOutputDevice() Error: Unknown output device.");
} }
} }
/** /**
@ -335,16 +333,16 @@ public class AudioHandler extends Plugin {
* @return 1=earpiece, 2=speaker * @return 1=earpiece, 2=speaker
*/ */
public int getAudioOutputDevice() { public int getAudioOutputDevice() {
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE); AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) { if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) {
return 1; return 1;
} }
else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER) { else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER) {
return 2; return 2;
} }
else { else {
return -1; return -1;
} }
} }
/** /**

View File

@ -45,119 +45,119 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
private static final String LOG_TAG = "AudioPlayer"; private static final String LOG_TAG = "AudioPlayer";
// AudioPlayer states // AudioPlayer states
public static int MEDIA_NONE = 0; public static int MEDIA_NONE = 0;
public static int MEDIA_STARTING = 1; public static int MEDIA_STARTING = 1;
public static int MEDIA_RUNNING = 2; public static int MEDIA_RUNNING = 2;
public static int MEDIA_PAUSED = 3; public static int MEDIA_PAUSED = 3;
public static int MEDIA_STOPPED = 4; public static int MEDIA_STOPPED = 4;
// AudioPlayer message ids // AudioPlayer message ids
private static int MEDIA_STATE = 1; private static int MEDIA_STATE = 1;
private static int MEDIA_DURATION = 2; private static int MEDIA_DURATION = 2;
private static int MEDIA_POSITION = 3; private static int MEDIA_POSITION = 3;
private static int MEDIA_ERROR = 9; private static int MEDIA_ERROR = 9;
// Media error codes // Media error codes
private static int MEDIA_ERR_NONE_ACTIVE = 0; private static int MEDIA_ERR_NONE_ACTIVE = 0;
private static int MEDIA_ERR_ABORTED = 1; private static int MEDIA_ERR_ABORTED = 1;
private static int MEDIA_ERR_NETWORK = 2; private static int MEDIA_ERR_NETWORK = 2;
private static int MEDIA_ERR_DECODE = 3; private static int MEDIA_ERR_DECODE = 3;
private static int MEDIA_ERR_NONE_SUPPORTED = 4; private static int MEDIA_ERR_NONE_SUPPORTED = 4;
private AudioHandler handler; // The AudioHandler object private AudioHandler handler; // The AudioHandler object
private String id; // The id of this player (used to identify Media object in JavaScript) private String id; // The id of this player (used to identify Media object in JavaScript)
private int state = MEDIA_NONE; // State of recording or playback private int state = MEDIA_NONE; // State of recording or playback
private String audioFile = null; // File name to play or record to private String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object private MediaRecorder recorder = null; // Audio recording object
private String tempFile = null; // Temporary recording file name private String tempFile = null; // Temporary recording file name
private MediaPlayer mPlayer = null; // Audio player object private MediaPlayer mPlayer = null; // Audio player object
private boolean prepareOnly = false; private boolean prepareOnly = false;
/** /**
* Constructor. * Constructor.
* *
* @param handler The audio handler object * @param handler The audio handler object
* @param id The id of this audio player * @param id The id of this audio player
*/ */
public AudioPlayer(AudioHandler handler, String id) { public AudioPlayer(AudioHandler handler, String id) {
this.handler = handler; this.handler = handler;
this.id = id; this.id = id;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
this.tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording.mp3"; this.tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording.mp3";
} else { } else {
this.tempFile = "/data/data/" + handler.ctx.getPackageName() + "/cache/tmprecording.mp3"; this.tempFile = "/data/data/" + handler.ctx.getPackageName() + "/cache/tmprecording.mp3";
} }
} }
/** /**
* Destroy player and stop audio playing or recording. * Destroy player and stop audio playing or recording.
*/ */
public void destroy() { public void destroy() {
// Stop any play or record // Stop any play or record
if (this.mPlayer != null) { if (this.mPlayer != null) {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) { if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
this.mPlayer.stop(); this.mPlayer.stop();
this.setState(MEDIA_STOPPED); this.setState(MEDIA_STOPPED);
} }
this.mPlayer.release(); this.mPlayer.release();
this.mPlayer = null; this.mPlayer = null;
} }
if (this.recorder != null) { if (this.recorder != null) {
this.stopRecording(); this.stopRecording();
this.recorder.release(); this.recorder.release();
this.recorder = null; this.recorder = null;
} }
} }
/** /**
* Start recording the specified file. * Start recording the specified file.
* *
* @param file The name of the file * @param file The name of the file
*/ */
public void startRecording(String file) { public void startRecording(String file) {
if (this.mPlayer != null) { if (this.mPlayer != null) {
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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
// Make sure we're not already recording // Make sure we're not already recording
else if (this.recorder == null) { else if (this.recorder == null) {
this.audioFile = file; this.audioFile = file;
this.recorder = new MediaRecorder(); this.recorder = new MediaRecorder();
this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC); this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
this.recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // THREE_GPP); this.recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // THREE_GPP);
this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); //AMR_NB); this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); //AMR_NB);
this.recorder.setOutputFile(this.tempFile); this.recorder.setOutputFile(this.tempFile);
try { try {
this.recorder.prepare(); this.recorder.prepare();
this.recorder.start(); this.recorder.start();
this.setState(MEDIA_RUNNING); this.setState(MEDIA_RUNNING);
return; return;
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
e.printStackTrace(); e.printStackTrace();
} 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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
else { else {
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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
} }
/** /**
* Save temporary recorded file to specified name * Save temporary recorded file to specified name
* *
* @param file * @param file
*/ */
public void moveFile(String file) { public void moveFile(String file) {
/* this is a hack to save the file as the specified name */ /* this is a hack to save the file as the specified name */
File f = new File(this.tempFile); File f = new File(this.tempFile);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
f.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath() f.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + file)); + File.separator + file));
@ -165,66 +165,66 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
f.renameTo(new File("/data/data/" + handler.ctx.getPackageName() + "/cache/" + file)); f.renameTo(new File("/data/data/" + handler.ctx.getPackageName() + "/cache/" + file));
} }
} }
/** /**
* Stop recording and save to the file specified when recording started. * Stop recording and save to the file specified when recording started.
*/ */
public void stopRecording() { public void stopRecording() {
if (this.recorder != null) { if (this.recorder != null) {
try{ try{
if (this.state == MEDIA_RUNNING) { if (this.state == MEDIA_RUNNING) {
this.recorder.stop(); this.recorder.stop();
this.setState(MEDIA_STOPPED); this.setState(MEDIA_STOPPED);
} }
this.moveFile(this.audioFile); this.moveFile(this.audioFile);
} }
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
/** /**
* Start or resume playing audio file. * Start or resume playing audio file.
* *
* @param file The name of the audio file. * @param file The name of the audio file.
*/ */
public void startPlaying(String file) { public void startPlaying(String file) {
if (this.recorder != null) { if (this.recorder != null) {
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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
// If this is a new request to play audio, or stopped // If this is a new request to play audio, or stopped
else if ((this.mPlayer == null) || (this.state == MEDIA_STOPPED)) { else if ((this.mPlayer == null) || (this.state == MEDIA_STOPPED)) {
try { try {
// If stopped, then reset player // If stopped, then reset player
if (this.mPlayer != null) { if (this.mPlayer != null) {
this.mPlayer.reset(); this.mPlayer.reset();
} }
// Otherwise, create a new one // Otherwise, create a new one
else { else {
this.mPlayer = new MediaPlayer(); this.mPlayer = new MediaPlayer();
} }
this.audioFile = file; this.audioFile = file;
// If streaming file // If streaming file
if (this.isStreaming(file)) { if (this.isStreaming(file)) {
this.mPlayer.setDataSource(file); this.mPlayer.setDataSource(file);
this.mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); this.mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
this.setState(MEDIA_STARTING); this.setState(MEDIA_STARTING);
this.mPlayer.setOnPreparedListener(this); this.mPlayer.setOnPreparedListener(this);
this.mPlayer.prepareAsync(); this.mPlayer.prepareAsync();
} }
// If local file // If local file
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.getBaseContext().getAssets().openFd(f); android.content.res.AssetFileDescriptor fd = this.handler.ctx.getBaseContext().getAssets().openFd(f);
this.mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); this.mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
} }
else { else {
File fp = new File(file); File fp = new File(file);
if (fp.exists()) { if (fp.exists()) {
@ -235,83 +235,83 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.mPlayer.setDataSource("/sdcard/" + file); this.mPlayer.setDataSource("/sdcard/" + file);
} }
} }
this.setState(MEDIA_STARTING); this.setState(MEDIA_STARTING);
this.mPlayer.setOnPreparedListener(this); this.mPlayer.setOnPreparedListener(this);
this.mPlayer.prepare(); this.mPlayer.prepare();
// Get duration // Get duration
this.duration = getDurationInSeconds(); this.duration = getDurationInSeconds();
} }
} }
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
} }
// If we have already have created an audio player // If we have already have created an audio player
else { else {
// If player has been paused, then resume playback // If player has been paused, then resume playback
if ((this.state == MEDIA_PAUSED) || (this.state == MEDIA_STARTING)) { if ((this.state == MEDIA_PAUSED) || (this.state == MEDIA_STARTING)) {
this.mPlayer.start(); this.mPlayer.start();
this.setState(MEDIA_RUNNING); this.setState(MEDIA_RUNNING);
} }
else { else {
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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
} }
} }
/** /**
* Seek or jump to a new time in the track. * Seek or jump to a new time in the track.
*/ */
public void seekToPlaying(int milliseconds) { public void seekToPlaying(int milliseconds) {
if (this.mPlayer != null) { if (this.mPlayer != null) {
this.mPlayer.seekTo(milliseconds); this.mPlayer.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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+milliseconds/1000.0f+");");
} }
} }
/** /**
* Pause playing. * Pause playing.
*/ */
public void pausePlaying() { public void pausePlaying() {
// If playing, then pause // If playing, then pause
if (this.state == MEDIA_RUNNING) { if (this.state == MEDIA_RUNNING) {
this.mPlayer.pause(); this.mPlayer.pause();
this.setState(MEDIA_PAUSED); this.setState(MEDIA_PAUSED);
} }
else { else {
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: "+this.state); Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: "+this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});");
} }
} }
/** /**
* Stop playing the audio file. * Stop playing the audio file.
*/ */
public void stopPlaying() { public void stopPlaying() {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) { if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
this.mPlayer.stop(); this.mPlayer.stop();
this.setState(MEDIA_STOPPED); this.setState(MEDIA_STOPPED);
} }
else { else {
Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: "+this.state); Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: "+this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});");
} }
} }
/** /**
* Callback to be invoked when playback of a media source has completed. * Callback to be invoked when playback of a media source has completed.
* *
* @param mPlayer The MediaPlayer that reached the end of the file * @param mPlayer The MediaPlayer that reached the end of the file
*/ */
public void onCompletion(MediaPlayer mPlayer) { public void onCompletion(MediaPlayer mPlayer) {
this.setState(MEDIA_STOPPED); this.setState(MEDIA_STOPPED);
} }
/** /**
@ -319,32 +319,32 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
* *
* @return position in msec or -1 if not playing * @return position in msec or -1 if not playing
*/ */
public long getCurrentPosition() { public long getCurrentPosition() {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) { if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
int curPos = this.mPlayer.getCurrentPosition(); int curPos = this.mPlayer.getCurrentPosition();
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+curPos/1000.0f+");"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+curPos/1000.0f+");");
return curPos; return curPos;
} }
else { else {
return -1; return -1;
} }
} }
/** /**
* Determine if playback file is streaming or local. * Determine if playback file is streaming or local.
* It is streaming if file name starts with "http://" * It is streaming if file name starts with "http://"
* *
* @param file The file name * @param file The file name
* @return T=streaming, F=local * @return T=streaming, F=local
*/ */
public boolean isStreaming(String file) { public boolean isStreaming(String file) {
if (file.contains("http://") || file.contains("https://")) { if (file.contains("http://") || file.contains("https://")) {
return true; return true;
} }
else { else {
return false; return false;
} }
} }
/** /**
* Get the duration of the audio file. * Get the duration of the audio file.
@ -354,113 +354,113 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
* -1=can't be determined * -1=can't be determined
* -2=not allowed * -2=not allowed
*/ */
public float getDuration(String file) { public float getDuration(String file) {
// Can't get duration of recording // Can't get duration of recording
if (this.recorder != null) { if (this.recorder != null) {
return(-2); // not allowed return(-2); // not allowed
} }
// If audio file already loaded and started, then return duration // If audio file already loaded and started, then return duration
if (this.mPlayer != null) { if (this.mPlayer != null) {
return this.duration; return this.duration;
} }
// If no player yet, then create one // If no player yet, then create one
else { else {
this.prepareOnly = true; this.prepareOnly = true;
this.startPlaying(file); this.startPlaying(file);
// This will only return value for local, since streaming // This will only return value for local, since streaming
// file hasn't been read yet. // file hasn't been read yet.
return this.duration; return this.duration;
} }
} }
/** /**
* Callback to be invoked when the media source is ready for playback. * Callback to be invoked when the media source is ready for playback.
* *
* @param mPlayer The MediaPlayer that is ready for playback * @param mPlayer The MediaPlayer that is ready for playback
*/ */
public void onPrepared(MediaPlayer mPlayer) { public void onPrepared(MediaPlayer mPlayer) {
// Listen for playback completion // Listen for playback completion
this.mPlayer.setOnCompletionListener(this); this.mPlayer.setOnCompletionListener(this);
// If start playing after prepared // If start playing after prepared
if (!this.prepareOnly) { if (!this.prepareOnly) {
// Start playing // Start playing
this.mPlayer.start(); this.mPlayer.start();
// Set player init flag // Set player init flag
this.setState(MEDIA_RUNNING); this.setState(MEDIA_RUNNING);
} }
// Save off duration // Save off duration
this.duration = getDurationInSeconds(); this.duration = getDurationInSeconds();
this.prepareOnly = false; this.prepareOnly = false;
// 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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_DURATION+","+this.duration+");");
} }
/** /**
* By default Android returns the length of audio in mills but we want seconds * By default Android returns the length of audio in mills but we want seconds
* *
* @return length of clip in seconds * @return length of clip in seconds
*/ */
private float getDurationInSeconds() { private float getDurationInSeconds() {
return (this.mPlayer.getDuration() / 1000.0f); return (this.mPlayer.getDuration() / 1000.0f);
} }
/** /**
* Callback to be invoked when there has been an error during an asynchronous operation * Callback to be invoked when there has been an error during an asynchronous operation
* (other errors will throw exceptions at method call time). * (other errors will throw exceptions at method call time).
* *
* @param mPlayer the MediaPlayer the error pertains to * @param mPlayer the MediaPlayer the error pertains to
* @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED) * @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
* @param arg2 an extra code, specific to the error. * @param arg2 an extra code, specific to the error.
*/ */
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) { public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")"); Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")");
// TODO: Not sure if this needs to be sent? // TODO: Not sure if this needs to be sent?
this.mPlayer.stop(); this.mPlayer.stop();
this.mPlayer.release(); this.mPlayer.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.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":"+arg1+"});");
return false; return false;
} }
/** /**
* Set the state and send it to JavaScript. * Set the state and send it to JavaScript.
* *
* @param state * @param state
*/ */
private void setState(int state) { private void setState(int state) {
if (this.state != state) { if (this.state != state) {
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");");
} }
this.state = state; this.state = state;
} }
/** /**
* Get the audio state. * Get the audio state.
* *
* @return int * @return int
*/ */
public int getState() { public int getState() {
return this.state; return this.state;
} }
/** /**
* Set the volume for audio player * Set the volume for audio player
* *
* @param volume * @param volume
*/ */
public void setVolume(float volume) { public void setVolume(float volume) {
this.mPlayer.setVolume(volume, volume); this.mPlayer.setVolume(volume, volume);
} }

View File

@ -59,9 +59,9 @@ public class BatteryListener extends Plugin {
String result = "Unsupported Operation: " + action; String result = "Unsupported Operation: " + action;
if (action.equals("start")) { if (action.equals("start")) {
if (this.batteryCallbackId != null) { if (this.batteryCallbackId != null) {
return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running."); return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running.");
} }
this.batteryCallbackId = callbackId; this.batteryCallbackId = callbackId;
// We need to listen to power events to update battery status // We need to listen to power events to update battery status
@ -147,10 +147,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.batteryCallbackId != 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.success(result, this.batteryCallbackId);
} }
} }
} }

View File

@ -25,11 +25,8 @@ import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.net.URLEncoder;
import java.util.LinkedList; import java.util.LinkedList;
import android.util.Log;
/** /**
* This class provides a way for Java to run JavaScript in the web page that has loaded Cordova. * This class provides a way for Java to run JavaScript in the web page that has loaded Cordova.
* The CallbackServer class implements an XHR server and a polling server with a list of JavaScript * The CallbackServer class implements an XHR server and a polling server with a list of JavaScript
@ -56,306 +53,306 @@ import android.util.Log;
*/ */
public class CallbackServer implements Runnable { public class CallbackServer implements Runnable {
private static final String LOG_TAG = "CallbackServer"; private static final String LOG_TAG = "CallbackServer";
/** /**
* The list of JavaScript statements to be sent to JavaScript. * The list of JavaScript statements to be sent to JavaScript.
*/ */
private LinkedList<String> javascript; private LinkedList<String> javascript;
/** /**
* The port to listen on. * The port to listen on.
*/ */
private int port; private int port;
/** /**
* The server thread. * The server thread.
*/ */
private Thread serverThread; private Thread serverThread;
/** /**
* Indicates the server is running. * Indicates the server is running.
*/ */
private boolean active; private boolean active;
/** /**
* Indicates that the JavaScript statements list is empty * Indicates that the JavaScript statements list is empty
*/ */
private boolean empty; private boolean empty;
/** /**
* Indicates that polling should be used instead of XHR. * Indicates that polling should be used instead of XHR.
*/ */
private boolean usePolling = true; private boolean usePolling = true;
/** /**
* Security token to prevent other apps from accessing this callback server via XHR * Security token to prevent other apps from accessing this callback server via XHR
*/ */
private String token; private String token;
/** /**
* Constructor. * Constructor.
*/ */
public CallbackServer() { public CallbackServer() {
//System.out.println("CallbackServer()"); //System.out.println("CallbackServer()");
this.active = false; this.active = false;
this.empty = true; this.empty = true;
this.port = 0; this.port = 0;
this.javascript = new LinkedList<String>(); this.javascript = new LinkedList<String>();
} }
/** /**
* Init callback server and start XHR if running local app. * Init callback server and start XHR if running local app.
* *
* If Cordova app is loaded from file://, then we can use XHR * If Cordova app is loaded from file://, then we can use XHR
* otherwise we have to use polling due to cross-domain security restrictions. * otherwise we have to use polling due to cross-domain security restrictions.
* *
* @param url The URL of the Cordova app being loaded * @param url The URL of the Cordova app being loaded
*/ */
public void init(String url) { public void init(String url) {
//System.out.println("CallbackServer.start("+url+")"); //System.out.println("CallbackServer.start("+url+")");
this.active = false; this.active = false;
this.empty = true; this.empty = true;
this.port = 0; this.port = 0;
this.javascript = new LinkedList<String>(); this.javascript = new LinkedList<String>();
// Determine if XHR or polling is to be used // Determine if XHR or polling is to be used
if ((url != null) && !url.startsWith("file://")) { if ((url != null) && !url.startsWith("file://")) {
this.usePolling = true; this.usePolling = true;
this.stopServer(); this.stopServer();
} }
else if (android.net.Proxy.getDefaultHost() != null) { else if (android.net.Proxy.getDefaultHost() != null) {
this.usePolling = true; this.usePolling = true;
this.stopServer(); this.stopServer();
} }
else { else {
this.usePolling = false; this.usePolling = false;
this.startServer(); this.startServer();
} }
} }
/** /**
* Re-init when loading a new HTML page into webview. * Re-init when loading a new HTML page into webview.
* *
* @param url The URL of the Cordova app being loaded * @param url The URL of the Cordova app being loaded
*/ */
public void reinit(String url) { public void reinit(String url) {
this.stopServer(); this.stopServer();
this.init(url); this.init(url);
} }
/** /**
* Return if polling is being used instead of XHR. * Return if polling is being used instead of XHR.
* *
* @return * @return
*/ */
public boolean usePolling() { public boolean usePolling() {
return this.usePolling; return this.usePolling;
} }
/** /**
* Get the port that this server is running on. * Get the port that this server is running on.
* *
* @return * @return
*/ */
public int getPort() { public int getPort() {
return this.port; return this.port;
} }
/** /**
* Get the security token that this server requires when calling getJavascript(). * Get the security token that this server requires when calling getJavascript().
* *
* @return * @return
*/ */
public String getToken() { public String getToken() {
return this.token; return this.token;
} }
/** /**
* Start the server on a new thread. * Start the server on a new thread.
*/ */
public void startServer() { public void startServer() {
//System.out.println("CallbackServer.startServer()"); //System.out.println("CallbackServer.startServer()");
this.active = false; this.active = false;
// Start server on new thread // Start server on new thread
this.serverThread = new Thread(this); this.serverThread = new Thread(this);
this.serverThread.start(); this.serverThread.start();
} }
/** /**
* Restart the server on a new thread. * Restart the server on a new thread.
*/ */
public void restartServer() { public void restartServer() {
// Stop server // Stop server
this.stopServer(); this.stopServer();
// Start server again // Start server again
this.startServer(); this.startServer();
} }
/** /**
* Start running the server. * Start running the server.
* This is called automatically when the server thread is started. * This is called automatically when the server thread is started.
*/ */
public void run() { public void run() {
// Start server // Start server
try { try {
this.active = true; this.active = true;
String request; String request;
ServerSocket waitSocket = new ServerSocket(0); ServerSocket waitSocket = new ServerSocket(0);
this.port = waitSocket.getLocalPort(); this.port = waitSocket.getLocalPort();
//System.out.println("CallbackServer -- using port " +this.port); //System.out.println("CallbackServer -- using port " +this.port);
this.token = java.util.UUID.randomUUID().toString(); this.token = java.util.UUID.randomUUID().toString();
//System.out.println("CallbackServer -- using token "+this.token); //System.out.println("CallbackServer -- using token "+this.token);
while (this.active) { while (this.active) {
//System.out.println("CallbackServer: Waiting for data on socket"); //System.out.println("CallbackServer: Waiting for data on socket");
Socket connection = waitSocket.accept(); Socket connection = waitSocket.accept();
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()),40); BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()),40);
DataOutputStream output = new DataOutputStream(connection.getOutputStream()); DataOutputStream output = new DataOutputStream(connection.getOutputStream());
request = xhrReader.readLine(); request = xhrReader.readLine();
String response = ""; String response = "";
//System.out.println("CallbackServerRequest="+request); //System.out.println("CallbackServerRequest="+request);
if (this.active && (request != null)) { if (this.active && (request != null)) {
if (request.contains("GET")) { if (request.contains("GET")) {
// Get requested file // Get requested file
String[] requestParts = request.split(" "); String[] requestParts = request.split(" ");
// Must have security token // Must have security token
if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) { if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) {
//System.out.println("CallbackServer -- Processing GET request"); //System.out.println("CallbackServer -- Processing GET request");
// Wait until there is some data to send, or send empty data every 10 sec // Wait until there is some data to send, or send empty data every 10 sec
// to prevent XHR timeout on the client // to prevent XHR timeout on the client
synchronized (this) { synchronized (this) {
while (this.empty) { while (this.empty) {
try { try {
this.wait(10000); // prevent timeout from happening this.wait(10000); // prevent timeout from happening
//System.out.println("CallbackServer>>> break <<<"); //System.out.println("CallbackServer>>> break <<<");
break; break;
} }
catch (Exception e) { } catch (Exception e) { }
} }
} }
// If server is still running // If server is still running
if (this.active) { if (this.active) {
// If no data, then send 404 back to client before it times out // If no data, then send 404 back to client before it times out
if (this.empty) { if (this.empty) {
//System.out.println("CallbackServer -- sending data 0"); //System.out.println("CallbackServer -- sending data 0");
response = "HTTP/1.1 404 NO DATA\r\n\r\n "; // need to send content otherwise some Android devices fail, so send space response = "HTTP/1.1 404 NO DATA\r\n\r\n "; // need to send content otherwise some Android devices fail, so send space
} }
else { else {
//System.out.println("CallbackServer -- sending item"); //System.out.println("CallbackServer -- sending item");
response = "HTTP/1.1 200 OK\r\n\r\n"; response = "HTTP/1.1 200 OK\r\n\r\n";
String js = this.getJavascript(); String js = this.getJavascript();
if (js != null) { if (js != null) {
response += encode(js, "UTF-8"); response += encode(js, "UTF-8");
} }
} }
} }
else { else {
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n "; response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
} }
} }
else { else {
response = "HTTP/1.1 403 Forbidden\r\n\r\n "; response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
} }
} }
else { else {
response = "HTTP/1.1 400 Bad Request\r\n\r\n "; response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
} }
//System.out.println("CallbackServer: response="+response); //System.out.println("CallbackServer: response="+response);
//System.out.println("CallbackServer: closing output"); //System.out.println("CallbackServer: closing output");
output.writeBytes(response); output.writeBytes(response);
output.flush(); output.flush();
} }
output.close(); output.close();
xhrReader.close(); xhrReader.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
this.active = false; this.active = false;
//System.out.println("CallbackServer.startServer() - EXIT"); //System.out.println("CallbackServer.startServer() - EXIT");
} }
/** /**
* Stop server. * Stop server.
* This stops the thread that the server is running on. * This stops the thread that the server is running on.
*/ */
public void stopServer() { public void stopServer() {
//System.out.println("CallbackServer.stopServer()"); //System.out.println("CallbackServer.stopServer()");
if (this.active) { if (this.active) {
this.active = false; this.active = false;
// Break out of server wait // Break out of server wait
synchronized (this) { synchronized (this) {
this.notify(); this.notify();
} }
} }
} }
/** /**
* Destroy * Destroy
*/ */
public void destroy() { public void destroy() {
this.stopServer(); this.stopServer();
} }
/** /**
* Get the number of JavaScript statements. * Get the number of JavaScript statements.
* *
* @return int * @return int
*/ */
public int getSize() { public int getSize() {
synchronized(this) { synchronized(this) {
int size = this.javascript.size(); int size = this.javascript.size();
return size; return size;
} }
} }
/** /**
* Get the next JavaScript statement and remove from list. * Get the next JavaScript statement and remove from list.
* *
* @return String * @return String
*/ */
public String getJavascript() { public String getJavascript() {
synchronized(this) { synchronized(this) {
if (this.javascript.size() == 0) { if (this.javascript.size() == 0) {
return null; return null;
} }
String statement = this.javascript.remove(0); String statement = this.javascript.remove(0);
if (this.javascript.size() == 0) { if (this.javascript.size() == 0) {
this.empty = true; this.empty = true;
} }
return statement; return statement;
} }
} }
/** /**
* Add a JavaScript statement to the list. * Add a JavaScript statement to the list.
* *
* @param statement * @param statement
*/ */
public void sendJavascript(String statement) { public void sendJavascript(String statement) {
synchronized (this) { synchronized (this) {
this.javascript.add(statement); this.javascript.add(statement);
this.empty = false; this.empty = false;
this.notify(); this.notify();
} }
} }
/* The Following code has been modified from original implementation of URLEncoder */ /* The Following code has been modified from original implementation of URLEncoder */
/* start */ /* start */
/* /*
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
@ -371,7 +368,7 @@ public class CallbackServer implements Runnable {
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
static final String digits = "0123456789ABCDEF"; static final String digits = "0123456789ABCDEF";
/** /**
* This will encode the return value to JavaScript. We revert the encoding for * This will encode the return value to JavaScript. We revert the encoding for
@ -382,7 +379,7 @@ public class CallbackServer implements Runnable {
* @param enc encoding type * @param enc encoding type
* @return encoded string * @return encoded string
*/ */
public static String encode(String s, String enc) throws UnsupportedEncodingException { public static String encode(String s, String enc) throws UnsupportedEncodingException {
if (s == null || enc == null) { if (s == null || enc == null) {
throw new NullPointerException(); throw new NullPointerException();
} }

View File

@ -41,7 +41,6 @@ import org.json.JSONObject;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
import android.content.ContentUris; import android.content.ContentUris;
@ -1667,72 +1666,72 @@ public class ContactAccessorSdk5 extends ContactAccessor {
private int getPhoneType(String string) { private int getPhoneType(String string) {
int type = ContactsContract.CommonDataKinds.Phone.TYPE_OTHER; int type = ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
if (string != null) { if (string != null) {
if ("home".equals(string.toLowerCase())) { if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_HOME; return ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
} }
else if ("mobile".equals(string.toLowerCase())) { else if ("mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE; return ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
} }
else if ("work".equals(string.toLowerCase())) { else if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK; return ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
} }
else if ("work fax".equals(string.toLowerCase())) { else if ("work fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK; return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
} }
else if ("home fax".equals(string.toLowerCase())) { else if ("home fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME; return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME;
} }
else if ("fax".equals(string.toLowerCase())) { else if ("fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK; return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
} }
else if ("pager".equals(string.toLowerCase())) { else if ("pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_PAGER; return ContactsContract.CommonDataKinds.Phone.TYPE_PAGER;
} }
else if ("other".equals(string.toLowerCase())) { else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER; return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
} }
else if ("car".equals(string.toLowerCase())) { else if ("car".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CAR; return ContactsContract.CommonDataKinds.Phone.TYPE_CAR;
} }
else if ("company main".equals(string.toLowerCase())) { else if ("company main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN; return ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN;
} }
else if ("isdn".equals(string.toLowerCase())) { else if ("isdn".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ISDN; return ContactsContract.CommonDataKinds.Phone.TYPE_ISDN;
} }
else if ("main".equals(string.toLowerCase())) { else if ("main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MAIN; return ContactsContract.CommonDataKinds.Phone.TYPE_MAIN;
} }
else if ("other fax".equals(string.toLowerCase())) { else if ("other fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX; return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX;
} }
else if ("radio".equals(string.toLowerCase())) { else if ("radio".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_RADIO; return ContactsContract.CommonDataKinds.Phone.TYPE_RADIO;
} }
else if ("telex".equals(string.toLowerCase())) { else if ("telex".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TELEX; return ContactsContract.CommonDataKinds.Phone.TYPE_TELEX;
} }
else if ("work mobile".equals(string.toLowerCase())) { else if ("work mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE; return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;
} }
else if ("work pager".equals(string.toLowerCase())) { else if ("work pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER; return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER;
} }
else if ("assistant".equals(string.toLowerCase())) { else if ("assistant".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT; return ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT;
} }
else if ("mms".equals(string.toLowerCase())) { else if ("mms".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MMS; return ContactsContract.CommonDataKinds.Phone.TYPE_MMS;
} }
else if ("callback".equals(string.toLowerCase())) { else if ("callback".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK; return ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK;
} }
else if ("tty ttd".equals(string.toLowerCase())) { else if ("tty ttd".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD; return ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD;
} }
else if ("custom".equals(string.toLowerCase())) { else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM; return ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM;
} }
} }
return type; return type;
} }

View File

@ -45,15 +45,15 @@ public class CordovaLocationListener implements LocationListener {
private String TAG = "[Cordova Location Listener]"; private String TAG = "[Cordova Location Listener]";
public CordovaLocationListener(LocationManager manager, GeoBroker broker, String tag) { public CordovaLocationListener(LocationManager manager, GeoBroker broker, String tag) {
this.locationManager = manager; this.locationManager = manager;
this.owner = broker; this.owner = broker;
this.TAG = tag; this.TAG = tag;
} }
protected void fail(int code, String message) { protected void fail(int code, String message) {
for (String callbackId: this.callbacks) for (String callbackId: this.callbacks)
{ {
this.owner.fail(code, message, callbackId); this.owner.fail(code, message, callbackId);
} }
this.callbacks.clear(); this.callbacks.clear();
@ -65,9 +65,9 @@ public class CordovaLocationListener implements LocationListener {
} }
private void win(Location loc) { private void win(Location loc) {
for (String callbackId: this.callbacks) for (String callbackId: this.callbacks)
{ {
this.owner.win(loc, callbackId); this.owner.win(loc, callbackId);
} }
this.callbacks.clear(); this.callbacks.clear();
@ -82,117 +82,117 @@ public class CordovaLocationListener implements LocationListener {
* Location Listener Methods * Location Listener Methods
*/ */
/** /**
* Called when the provider is disabled by the user. * Called when the provider is disabled by the user.
* *
* @param provider * @param provider
*/ */
public void onProviderDisabled(String provider) { public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider '" + provider + "' disabled."); Log.d(TAG, "Location provider '" + provider + "' disabled.");
this.fail(POSITION_UNAVAILABLE, "GPS provider disabled."); this.fail(POSITION_UNAVAILABLE, "GPS provider disabled.");
} }
/** /**
* Called when the provider is enabled by the user. * Called when the provider is enabled by the user.
* *
* @param provider * @param provider
*/ */
public void onProviderEnabled(String provider) { public void onProviderEnabled(String provider) {
Log.d(TAG, "Location provider "+ provider + " has been enabled"); Log.d(TAG, "Location provider "+ provider + " has been enabled");
} }
/** /**
* Called when the provider status changes. This method is called when a * Called when the provider status changes. This method is called when a
* provider is unable to fetch a location or if the provider has recently * provider is unable to fetch a location or if the provider has recently
* become available after a period of unavailability. * become available after a period of unavailability.
* *
* @param provider * @param provider
* @param status * @param status
* @param extras * @param extras
*/ */
public void onStatusChanged(String provider, int status, Bundle extras) { public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "The status of the provider " + provider + " has changed"); Log.d(TAG, "The status of the provider " + provider + " has changed");
if (status == 0) { if (status == 0) {
Log.d(TAG, provider + " is OUT OF SERVICE"); Log.d(TAG, provider + " is OUT OF SERVICE");
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Provider " + provider + " is out of service."); this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Provider " + provider + " is out of service.");
} }
else if (status == 1) { else if (status == 1) {
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE"); Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE");
} }
else { else {
Log.d(TAG, provider + " is AVAILABLE"); Log.d(TAG, provider + " is AVAILABLE");
} }
} }
/** /**
* Called when the location has changed. * Called when the location has changed.
* *
* @param location * @param location
*/ */
public void onLocationChanged(Location location) { public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!"); Log.d(TAG, "The location has been updated!");
this.win(location); this.win(location);
} }
// PUBLIC // PUBLIC
public int size() { public int size() {
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, String callbackId) {
this.watches.put(timerId, callbackId); this.watches.put(timerId, callbackId);
if (this.size() == 1) { if (this.size() == 1) {
this.start(); this.start();
} }
} }
public void addCallback(String callbackId) { public void addCallback(String callbackId) {
this.callbacks.add(callbackId); this.callbacks.add(callbackId);
if (this.size() == 1) { if (this.size() == 1) {
this.start(); this.start();
} }
} }
public void clearWatch(String timerId) { public void clearWatch(String timerId) {
if (this.watches.containsKey(timerId)) { if (this.watches.containsKey(timerId)) {
this.watches.remove(timerId); this.watches.remove(timerId);
} }
if (this.size() == 0) { if (this.size() == 0) {
this.stop(); this.stop();
} }
} }
/** /**
* Destroy listener. * Destroy listener.
*/ */
public void destroy() { public void destroy() {
this.stop(); this.stop();
} }
// LOCAL // LOCAL
/** /**
* Start requesting location updates. * Start requesting location updates.
* *
* @param interval * @param interval
*/ */
protected void start() { protected void start() {
if (!this.running) { if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) { if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true; this.running = true;
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this); this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
} else { } else {
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Network provider is not available."); this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Network provider is not available.");
} }
} }
} }
/** /**
* Stop receiving location updates. * Stop receiving location updates.
*/ */
private void stop() { private void stop() {
if (this.running) { if (this.running) {
this.locationManager.removeUpdates(this); this.locationManager.removeUpdates(this);
this.running = false; this.running = false;
} }
} }
} }

View File

@ -27,7 +27,6 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import android.net.http.SslError; import android.net.http.SslError;
import android.util.Log;
import android.view.View; import android.view.View;
import android.webkit.HttpAuthHandler; import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler; import android.webkit.SslErrorHandler;

View File

@ -32,105 +32,105 @@ import android.os.StatFs;
*/ */
public class DirectoryManager { public class DirectoryManager {
private static final String LOG_TAG = "DirectoryManager"; private static final String LOG_TAG = "DirectoryManager";
/** /**
* Determine if a file or directory exists. * Determine if a file or directory exists.
* *
* @param name The name of the file to check. * @param name The name of the file to check.
* @return T=exists, F=not found * @return T=exists, F=not found
*/ */
protected static boolean testFileExists(String name) { protected static boolean testFileExists(String name) {
boolean status; boolean status;
// If SD card exists // If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) { if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory(); File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name); File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists(); status = newPath.exists();
} }
// If no SD card // If no SD card
else{ else{
status = false; status = false;
} }
return status; return status;
} }
/** /**
* Get the free disk space * Get the free disk space
* *
* @return Size in KB or -1 if not available * @return Size in KB or -1 if not available
*/ */
protected static long getFreeDiskSpace(boolean checkInternal) { protected static long getFreeDiskSpace(boolean checkInternal) {
String status = Environment.getExternalStorageState(); String status = Environment.getExternalStorageState();
long freeSpace = 0; long freeSpace = 0;
// If SD card exists // If SD card exists
if (status.equals(Environment.MEDIA_MOUNTED)) { if (status.equals(Environment.MEDIA_MOUNTED)) {
freeSpace = freeSpaceCalculation(Environment.getExternalStorageDirectory().getPath()); freeSpace = freeSpaceCalculation(Environment.getExternalStorageDirectory().getPath());
} }
else if (checkInternal) { else if (checkInternal) {
freeSpace = freeSpaceCalculation("/"); freeSpace = freeSpaceCalculation("/");
} }
// If no SD card and we haven't been asked to check the internal directory then return -1 // If no SD card and we haven't been asked to check the internal directory then return -1
else { else {
return -1; return -1;
} }
return freeSpace; return freeSpace;
} }
/** /**
* Given a path return the number of free KB * Given a path return the number of free KB
* *
* @param path to the file system * @param path to the file system
* @return free space in KB * @return free space in KB
*/ */
private static long freeSpaceCalculation(String path) { private static long freeSpaceCalculation(String path) {
StatFs stat = new StatFs(path); StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize(); long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks(); long availableBlocks = stat.getAvailableBlocks();
return availableBlocks*blockSize/1024; return availableBlocks*blockSize/1024;
} }
/** /**
* Determine if SD card exists. * Determine if SD card exists.
* *
* @return T=exists, F=not found * @return T=exists, F=not found
*/ */
protected static boolean testSaveLocationExists() { protected static boolean testSaveLocationExists() {
String sDCardStatus = Environment.getExternalStorageState(); String sDCardStatus = Environment.getExternalStorageState();
boolean status; boolean status;
// If SD card is mounted // If SD card is mounted
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) { if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
status = true; status = true;
} }
// If no SD card // If no SD card
else { else {
status = false; status = false;
} }
return status; return status;
} }
/** /**
* Create a new file object from two file paths. * Create a new file object from two file paths.
* *
* @param file1 Base file path * @param file1 Base file path
* @param file2 Remaining file path * @param file2 Remaining file path
* @return File object * @return File object
*/ */
private static File constructFilePaths (String file1, String file2) { private static File constructFilePaths (String file1, String file2) {
File newPath; File newPath;
if (file2.startsWith(file1)) { if (file2.startsWith(file1)) {
newPath = new File(file2); newPath = new File(file2);
} }
else { else {
newPath = new File(file1+"/"+file2); newPath = new File(file1+"/"+file2);
} }
return newPath; return newPath;
} }
/** /**
* Determine if we can use the SD Card to store the temporary file. If not then use * Determine if we can use the SD Card to store the temporary file. If not then use

View File

@ -350,7 +350,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* Create and initialize web container with default web view objects. * Create and initialize web container with default web view objects.
*/ */
public void init() { public void init() {
this.init(new WebView(DroidGap.this), new CordovaWebViewClient(this), new CordovaChromeClient(DroidGap.this)); this.init(new WebView(DroidGap.this), new CordovaWebViewClient(this), new CordovaChromeClient(DroidGap.this));
} }
/** /**
@ -364,7 +364,7 @@ public class DroidGap extends Activity implements CordovaInterface {
LOG.d(TAG, "DroidGap.init()"); LOG.d(TAG, "DroidGap.init()");
// Set up web container // Set up web container
this.appView = webView; this.appView = webView;
this.appView.setId(100); this.appView.setId(100);
this.appView.setLayoutParams(new LinearLayout.LayoutParams( this.appView.setLayoutParams(new LinearLayout.LayoutParams(
@ -372,8 +372,8 @@ public class DroidGap extends Activity implements CordovaInterface {
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT,
1.0F)); 1.0F));
this.appView.setWebChromeClient(webChromeClient); this.appView.setWebChromeClient(webChromeClient);
this.setWebViewClient(this.appView, webViewClient); this.setWebViewClient(this.appView, webViewClient);
this.appView.setInitialScale(0); this.appView.setInitialScale(0);
this.appView.setVerticalScrollBarEnabled(false); this.appView.setVerticalScrollBarEnabled(false);
@ -817,7 +817,7 @@ public class DroidGap extends Activity implements CordovaInterface {
// Forward to plugins // Forward to plugins
if (this.pluginManager != null) { if (this.pluginManager != null) {
this.pluginManager.onPause(this.keepRunning); this.pluginManager.onPause(this.keepRunning);
} }
// If app doesn't want to run in background // If app doesn't want to run in background
@ -837,7 +837,7 @@ public class DroidGap extends Activity implements CordovaInterface {
//Forward to plugins //Forward to plugins
if (this.pluginManager != null) { if (this.pluginManager != null) {
this.pluginManager.onNewIntent(intent); this.pluginManager.onNewIntent(intent);
} }
} }
@ -862,7 +862,7 @@ public class DroidGap extends Activity implements CordovaInterface {
// Forward to plugins // Forward to plugins
if (this.pluginManager != null) { if (this.pluginManager != null) {
this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning); this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning);
} }
// If app doesn't want to run in background // If app doesn't want to run in background
@ -931,7 +931,7 @@ public class DroidGap extends Activity implements CordovaInterface {
@Deprecated @Deprecated
public void addService(String serviceType, String className) { public void addService(String serviceType, String className) {
if (this.pluginManager != null) { if (this.pluginManager != null) {
this.pluginManager.addService(serviceType, className); this.pluginManager.addService(serviceType, className);
} }
} }
@ -1370,22 +1370,19 @@ public class DroidGap extends Activity implements CordovaInterface {
*/ */
@Override @Override
public boolean onCreateOptionsMenu(Menu menu) public boolean onCreateOptionsMenu(Menu menu) {
{
this.postMessage("onCreateOptionsMenu", menu); this.postMessage("onCreateOptionsMenu", menu);
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) public boolean onPrepareOptionsMenu(Menu menu) {
{
this.postMessage("onPrepareOptionsMenu", menu); this.postMessage("onPrepareOptionsMenu", menu);
return super.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu);
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) public boolean onOptionsItemSelected(MenuItem item) {
{
this.postMessage("onOptionsItemSelected", item); this.postMessage("onOptionsItemSelected", item);
return true; return true;
} }
@ -1442,9 +1439,9 @@ public class DroidGap extends Activity implements CordovaInterface {
// Set Runnable to remove splash screen just in case // Set Runnable to remove splash screen just in case
final Handler handler = new Handler(); final Handler handler = new Handler();
handler.postDelayed(new Runnable() { handler.postDelayed(new Runnable() {
public void run() { public void run() {
removeSplashScreen(); removeSplashScreen();
} }
}, time); }, time);
} }
} }

View File

@ -41,7 +41,6 @@ import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.os.Environment; import android.os.Environment;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap; import android.webkit.MimeTypeMap;

View File

@ -26,25 +26,25 @@ import android.location.LocationManager;
* *
*/ */
public class GPSListener extends CordovaLocationListener { public class GPSListener extends CordovaLocationListener {
public GPSListener(LocationManager locationManager, GeoBroker m) { public GPSListener(LocationManager locationManager, GeoBroker m) {
super(locationManager, m, "[Cordova GPSListener]"); super(locationManager, m, "[Cordova GPSListener]");
} }
/** /**
* Start requesting location updates. * Start requesting location updates.
* *
* @param interval * @param interval
*/ */
@Override @Override
protected void start() { protected void start() {
if (!this.running) { if (!this.running) {
if (this.locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) { if (this.locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
this.running = true; this.running = true;
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, this); this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, this);
} else { } else {
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "GPS provider is not available."); this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "GPS provider is not available.");
} }
} }
} }
} }

View File

@ -54,11 +54,11 @@ public class GeoBroker extends Plugin {
* @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 PluginResult execute(String action, JSONArray args, String callbackId) {
if (this.locationManager == null) { if (this.locationManager == null) {
this.locationManager = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE); this.locationManager = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);
this.networkListener = new NetworkListener(this.locationManager, this); this.networkListener = new NetworkListener(this.locationManager, this);
this.gpsListener = new GPSListener(this.locationManager, this); this.gpsListener = new GPSListener(this.locationManager, this);
} }
PluginResult.Status status = PluginResult.Status.NO_RESULT; PluginResult.Status status = PluginResult.Status.NO_RESULT;
String message = ""; String message = "";
PluginResult result = new PluginResult(status, message); PluginResult result = new PluginResult(status, message);
@ -66,53 +66,53 @@ public class GeoBroker extends Plugin {
try { try {
if (action.equals("getLocation")) { if (action.equals("getLocation")) {
boolean enableHighAccuracy = args.getBoolean(0); boolean enableHighAccuracy = args.getBoolean(0);
int maximumAge = args.getInt(1); int maximumAge = args.getInt(1);
Location last = this.locationManager.getLastKnownLocation((enableHighAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER)); Location last = this.locationManager.getLastKnownLocation((enableHighAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER));
// Check if we can use lastKnownLocation to get a quick reading and use less battery // Check if we can use lastKnownLocation to get a quick reading and use less battery
if ((System.currentTimeMillis() - last.getTime()) <= maximumAge) { if ((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(callbackId, 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, callbackId, 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);
} }
} 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; return result;
} }
private void clearWatch(String id) { private void clearWatch(String id) {
this.gpsListener.clearWatch(id); this.gpsListener.clearWatch(id);
this.networkListener.clearWatch(id); this.networkListener.clearWatch(id);
}
private void getCurrentLocation(String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addCallback(callbackId);
} else {
this.networkListener.addCallback(callbackId);
}
}
private void addWatch(String timerId, String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addWatch(timerId, callbackId);
} else {
this.networkListener.addWatch(timerId, callbackId);
}
} }
/** private void getCurrentLocation(String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addCallback(callbackId);
} else {
this.networkListener.addCallback(callbackId);
}
}
private void addWatch(String timerId, String callbackId, boolean enableHighAccuracy) {
if (enableHighAccuracy) {
this.gpsListener.addWatch(timerId, callbackId);
} else {
this.networkListener.addWatch(timerId, callbackId);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously. * Identifies if action to be executed returns a value and should be run synchronously.
* *
* @param action The action to execute * @param action The action to execute
@ -128,34 +128,34 @@ public class GeoBroker extends Plugin {
* Stop listener. * Stop listener.
*/ */
public void onDestroy() { public void onDestroy() {
this.networkListener.destroy(); this.networkListener.destroy();
this.gpsListener.destroy(); this.gpsListener.destroy();
this.networkListener = null; this.networkListener = null;
this.gpsListener = null; this.gpsListener = null;
} }
public JSONObject returnLocationJSON(Location loc) { public JSONObject returnLocationJSON(Location loc) {
JSONObject o = new JSONObject(); JSONObject o = new JSONObject();
try { try {
o.put("latitude", loc.getLatitude()); o.put("latitude", loc.getLatitude());
o.put("longitude", loc.getLongitude()); o.put("longitude", loc.getLongitude());
o.put("altitude", (loc.hasAltitude() ? loc.getAltitude() : null)); o.put("altitude", (loc.hasAltitude() ? loc.getAltitude() : null));
o.put("accuracy", loc.getAccuracy()); o.put("accuracy", loc.getAccuracy());
o.put("heading", (loc.hasBearing() ? (loc.hasSpeed() ? loc.getBearing() : null) : null)); o.put("heading", (loc.hasBearing() ? (loc.hasSpeed() ? loc.getBearing() : null) : null));
o.put("speed", loc.getSpeed()); o.put("speed", loc.getSpeed());
o.put("timestamp", loc.getTime()); o.put("timestamp", loc.getTime());
} catch (JSONException e) { } catch (JSONException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return o; return o;
} }
public void win(Location loc, String callbackId) { public void win(Location loc, String callbackId) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc)); PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
this.success(result, callbackId); this.success(result, callbackId);
} }
/** /**
* Location failed. Send error back to JavaScript. * Location failed. Send error back to JavaScript.
@ -165,22 +165,22 @@ public class GeoBroker extends Plugin {
* @throws JSONException * @throws JSONException
*/ */
public void fail(int code, String msg, String callbackId) { public void fail(int code, String msg, String callbackId) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
String backup = null; String backup = null;
try { try {
obj.put("code", code); obj.put("code", code);
obj.put("message", msg); obj.put("message", msg);
} catch (JSONException e) { } catch (JSONException e) {
obj = null; obj = null;
backup = "{'code':" + code + ",'message':'" + msg.replaceAll("'", "\'") + "'}"; backup = "{'code':" + code + ",'message':'" + msg.replaceAll("'", "\'") + "'}";
} }
PluginResult result; PluginResult result;
if (obj != null) { if (obj != null) {
result = new PluginResult(PluginResult.Status.ERROR, obj); result = new PluginResult(PluginResult.Status.ERROR, obj);
} else { } else {
result = new PluginResult(PluginResult.Status.ERROR, backup); result = new PluginResult(PluginResult.Status.ERROR, backup);
} }
this.error(result, callbackId); this.error(result, callbackId);
} }
} }

View File

@ -29,52 +29,52 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class HttpHandler { public class HttpHandler {
protected Boolean get(String url, String file) protected Boolean get(String url, String file)
{ {
HttpEntity entity = getHttpEntity(url); HttpEntity entity = getHttpEntity(url);
try { try {
writeToDisk(entity, file); writeToDisk(entity, file);
} catch (Exception e) { e.printStackTrace(); return false; } } catch (Exception e) { e.printStackTrace(); return false; }
try { try {
entity.consumeContent(); entity.consumeContent();
} catch (Exception e) { e.printStackTrace(); return false; } } catch (Exception e) { e.printStackTrace(); return false; }
return true; return true;
} }
private HttpEntity getHttpEntity(String url) private HttpEntity getHttpEntity(String url)
/** /**
* get the http entity at a given url * get the http entity at a given url
*/ */
{ {
HttpEntity entity=null; HttpEntity entity=null;
try { try {
DefaultHttpClient httpclient = new DefaultHttpClient(); DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url); HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget); HttpResponse response = httpclient.execute(httpget);
entity = response.getEntity(); entity = response.getEntity();
} catch (Exception e) { e.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; }
return entity; return entity;
} }
private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException
/** /**
* writes a HTTP entity to the specified filename and location on disk * writes a HTTP entity to the specified filename and location on disk
*/ */
{ {
int i=0; int i=0;
String FilePath="/sdcard/" + file; String FilePath="/sdcard/" + file;
InputStream in = entity.getContent(); InputStream in = entity.getContent();
byte buff[] = new byte[1024]; byte buff[] = new byte[1024];
FileOutputStream out= FileOutputStream out=
new FileOutputStream(FilePath); new FileOutputStream(FilePath);
do { do {
int numread = in.read(buff); int numread = in.read(buff);
if (numread <= 0) if (numread <= 0)
break; break;
out.write(buff, 0, numread); out.write(buff, 0, numread);
i++; i++;
} while (true); } while (true);
out.flush(); out.flush();
out.close(); out.close();
} }
} }

View File

@ -20,7 +20,6 @@ package org.apache.cordova;
import org.apache.cordova.api.LOG; import org.apache.cordova.api.LOG;
import android.content.Context; import android.content.Context;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout; import android.widget.LinearLayout;
/** /**

View File

@ -26,7 +26,7 @@ import android.location.LocationManager;
* *
*/ */
public class NetworkListener extends CordovaLocationListener { public class NetworkListener extends CordovaLocationListener {
public NetworkListener(LocationManager locationManager, GeoBroker m) { public NetworkListener(LocationManager locationManager, GeoBroker m) {
super(locationManager, m, "[Cordova NetworkListener]"); super(locationManager, m, "[Cordova NetworkListener]");
} }
} }

View File

@ -18,15 +18,12 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import java.lang.reflect.Field;
import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
public class StandAlone extends DroidGap { public class StandAlone extends DroidGap {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html"); super.loadUrl("file:///android_asset/www/index.html");

View File

@ -37,203 +37,203 @@ import android.database.sqlite.*;
*/ */
public class Storage extends Plugin { public class Storage extends Plugin {
// Data Definition Language // Data Definition Language
private static final String ALTER = "alter"; private static final String ALTER = "alter";
private static final String CREATE = "create"; private static final String CREATE = "create";
private static final String DROP = "drop"; private static final String DROP = "drop";
private static final String TRUNCATE = "truncate"; private static final String TRUNCATE = "truncate";
SQLiteDatabase myDb = null; // Database object SQLiteDatabase myDb = null; // Database object
String path = null; // Database path String path = null; // Database path
String dbName = null; // Database name String dbName = null; // Database name
/** /**
* Constructor. * Constructor.
*/ */
public Storage() { public Storage() {
} }
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action * @param action
* 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 callbackId
* The callback id used when calling back into JavaScript. * 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 PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK; PluginResult.Status status = PluginResult.Status.OK;
String result = ""; 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),
args.getString(2), args.getLong(3)); args.getString(2), args.getLong(3));
} else if (action.equals("executeSql")) { } else if (action.equals("executeSql")) {
String[] s = null; String[] s = null;
if (args.isNull(1)) { if (args.isNull(1)) {
s = new String[0]; s = new String[0];
} else { } else {
JSONArray a = args.getJSONArray(1); JSONArray a = args.getJSONArray(1);
int len = a.length(); int len = a.length();
s = new String[len]; s = new String[len];
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
s[i] = a.getString(i); s[i] = a.getString(i);
} }
} }
this.executeSql(args.getString(0), s, args.getString(2)); this.executeSql(args.getString(0), s, args.getString(2));
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} catch (JSONException e) { } catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION); return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} }
} }
/** /**
* Identifies if action to be executed returns a value and should be run * Identifies if action to be executed returns a value and should be run
* synchronously. * synchronously.
* *
* @param action * @param action
* The action to execute * The action to execute
* @return T=returns value * @return T=returns value
*/ */
public boolean isSynch(String action) { public boolean isSynch(String action) {
return true; return true;
} }
/** /**
* Clean up and close database. * Clean up and close database.
*/ */
@Override @Override
public void onDestroy() { public void onDestroy() {
if (this.myDb != null) { if (this.myDb != null) {
this.myDb.close(); this.myDb.close();
this.myDb = null; this.myDb = null;
} }
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// LOCAL METHODS // LOCAL METHODS
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
/** /**
* Open database. * Open database.
* *
* @param db * @param db
* The name of the database * The name of the database
* @param version * @param version
* The version * The version
* @param display_name * @param display_name
* The display name * The display name
* @param size * @param size
* The size in bytes * The size in bytes
*/ */
public void openDatabase(String db, String version, String display_name, public void openDatabase(String db, String version, String display_name,
long size) { long size) {
// If database is open, then close it // If database is open, then close it
if (this.myDb != null) { if (this.myDb != null) {
this.myDb.close(); this.myDb.close();
} }
// If no database path, generate from application package // If no database path, generate from application package
if (this.path == null) { if (this.path == null) {
this.path = this.ctx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); this.path = this.ctx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
} }
this.dbName = this.path + File.pathSeparator + db + ".db"; this.dbName = this.path + File.pathSeparator + db + ".db";
this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null); this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null);
} }
/** /**
* Execute SQL statement. * Execute SQL statement.
* *
* @param query * @param query
* The SQL query * The SQL query
* @param params * @param params
* Parameters for the query * Parameters for the query
* @param tx_id * @param tx_id
* Transaction id * Transaction id
*/ */
public void executeSql(String query, String[] params, String tx_id) { public void executeSql(String query, String[] params, String tx_id) {
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.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);
this.processResults(myCursor, tx_id); this.processResults(myCursor, tx_id);
myCursor.close(); myCursor.close();
} }
} }
catch (SQLiteException ex) { catch (SQLiteException ex) {
ex.printStackTrace(); ex.printStackTrace();
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.sendJavascript("cordova.require('cordova/plugin/android/storage').failQuery('" + ex.getMessage() + "','" + tx_id + "');");
} }
} }
/** /**
* Checks to see the the query is a Data Definintion command * Checks to see the the query is a Data Definintion command
* *
* @param query to be executed * @param query to be executed
* @return true if it is a DDL command, false otherwise * @return true if it is a DDL command, false otherwise
*/ */
private boolean isDDL(String query) { private boolean isDDL(String query) {
String cmd = query.toLowerCase(); String cmd = query.toLowerCase();
if (cmd.startsWith(DROP) || cmd.startsWith(CREATE) || cmd.startsWith(ALTER) || cmd.startsWith(TRUNCATE)) { if (cmd.startsWith(DROP) || cmd.startsWith(CREATE) || cmd.startsWith(ALTER) || cmd.startsWith(TRUNCATE)) {
return true; return true;
} }
return false; return false;
} }
/** /**
* Process query results. * Process query results.
* *
* @param cur * @param cur
* Cursor into query results * Cursor into query results
* @param tx_id * @param tx_id
* Transaction id * Transaction id
*/ */
public void processResults(Cursor cur, String tx_id) { public void processResults(Cursor cur, String tx_id) {
String result = "[]"; String result = "[]";
// If query result has rows // If query result has rows
if (cur.moveToFirst()) { if (cur.moveToFirst()) {
JSONArray fullresult = new JSONArray(); JSONArray fullresult = new JSONArray();
String key = ""; String key = "";
String value = ""; String value = "";
int colCount = cur.getColumnCount(); int colCount = cur.getColumnCount();
// Build up JSON result object for each row // Build up JSON result object for each row
do { do {
JSONObject row = new JSONObject(); JSONObject row = new JSONObject();
try { try {
for (int i = 0; i < colCount; ++i) { for (int i = 0; i < colCount; ++i) {
key = cur.getColumnName(i); key = cur.getColumnName(i);
value = cur.getString(i); value = cur.getString(i);
row.put(key, value); row.put(key, value);
} }
fullresult.put(row); fullresult.put(row);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
} while (cur.moveToNext()); } while (cur.moveToNext());
result = fullresult.toString(); result = fullresult.toString();
} }
// 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.sendJavascript("cordova.require('cordova/plugin/android/storage').completeQuery('" + tx_id + "', " + result + ");");
} }
} }

View File

@ -35,78 +35,78 @@ import android.content.Context;
public class TempListener extends Plugin implements SensorEventListener { public class TempListener extends Plugin implements SensorEventListener {
Sensor mSensor; Sensor mSensor;
private SensorManager sensorManager; private SensorManager sensorManager;
/** /**
* Constructor. * Constructor.
*/ */
public TempListener() { public TempListener() {
} }
/** /**
* Sets the context of the Command. This can then be used to do things like * Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param ctx The context of the main Activity. * @param ctx The context of the main Activity.
*/ */
public void setContext(CordovaInterface ctx) { public void setContext(CordovaInterface ctx) {
super.setContext(ctx); super.setContext(ctx);
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE); this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
} }
/** /**
* 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 callbackId 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 PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK; PluginResult.Status status = PluginResult.Status.OK;
String result = ""; String result = "";
if (action.equals("start")) { if (action.equals("start")) {
this.start(); this.start();
} }
else if (action.equals("stop")) { else if (action.equals("stop")) {
this.stop(); this.stop();
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} }
/** /**
* Called by AccelBroker when listener is to be shut down. * Called by AccelBroker when listener is to be shut down.
* Stop listener. * Stop listener.
*/ */
public void onDestroy() { public void onDestroy() {
this.stop(); this.stop();
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
public void start() { public void start() {
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_TEMPERATURE); List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_TEMPERATURE);
if (list.size() > 0) { if (list.size() > 0) {
this.mSensor = list.get(0); this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_NORMAL); this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_NORMAL);
} }
} }
public void stop() { public void stop() {
this.sensorManager.unregisterListener(this); this.sensorManager.unregisterListener(this);
} }
public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
public void onSensorChanged(SensorEvent event) { public void onSensorChanged(SensorEvent event) {
// We want to know what temp this is. // We want to know what temp this is.
float temp = event.values[0]; float temp = event.values[0];
this.sendJavascript("gotTemp(" + temp + ");"); this.sendJavascript("gotTemp(" + temp + ");");
} }
} }

View File

@ -20,8 +20,6 @@ package org.apache.cordova.api;
import java.util.HashMap; import java.util.HashMap;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
@ -30,7 +28,6 @@ import android.content.IntentFilter;
import android.content.res.AssetManager; import android.content.res.AssetManager;
import android.content.res.Resources; import android.content.res.Resources;
import android.database.Cursor; import android.database.Cursor;
import android.hardware.SensorManager;
import android.net.Uri; import android.net.Uri;

View File

@ -29,39 +29,39 @@ import android.webkit.WebView;
*/ */
public interface IPlugin { public interface IPlugin {
/** /**
* 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 callbackId 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.
*/ */
PluginResult execute(String action, JSONArray args, String callbackId); PluginResult execute(String action, JSONArray args, String callbackId);
/** /**
* Identifies if action to be executed returns a value and should be run synchronously. * Identifies if action to be executed returns a value and should be run synchronously.
* *
* @param action The action to execute * @param action The action to execute
* @return T=returns value * @return T=returns value
*/ */
public boolean isSynch(String action); public boolean isSynch(String action);
/** /**
* Sets the context of the Plugin. This can then be used to do things like * Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param ctx The context of the main Activity. * @param ctx The context of the main Activity.
*/ */
void setContext(CordovaInterface ctx); void setContext(CordovaInterface ctx);
/** /**
* Sets the main View of the application, this is the WebView within which * Sets the main View of the application, this is the WebView within which
* a Cordova app runs. * a Cordova app runs.
* *
* @param webView The Cordova WebView * @param webView The Cordova WebView
*/ */
void setView(WebView webView); void setView(WebView webView);
/** /**
* Called when the system is about to start resuming a previous activity. * Called when the system is about to start resuming a previous activity.

View File

@ -31,49 +31,49 @@ import android.webkit.WebView;
*/ */
public abstract class Plugin implements IPlugin { public abstract class Plugin implements IPlugin {
public String id; public String id;
public WebView webView; // WebView object public WebView webView; // WebView object
public CordovaInterface ctx; // CordovaActivity object public CordovaInterface ctx; // CordovaActivity object
/** /**
* 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 callbackId 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 abstract PluginResult execute(String action, JSONArray args, String callbackId); public abstract PluginResult execute(String action, JSONArray args, String callbackId);
/** /**
* Identifies if action to be executed returns a value and should be run synchronously. * Identifies if action to be executed returns a value and should be run synchronously.
* *
* @param action The action to execute * @param action The action to execute
* @return T=returns value * @return T=returns value
*/ */
public boolean isSynch(String action) { public boolean isSynch(String action) {
return false; return false;
} }
/** /**
* Sets the context of the Plugin. This can then be used to do things like * Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity. * get file paths associated with the Activity.
* *
* @param ctx The context of the main Activity. * @param ctx The context of the main Activity.
*/ */
public void setContext(CordovaInterface ctx) { public void setContext(CordovaInterface ctx) {
this.ctx = ctx; this.ctx = ctx;
} }
/** /**
* Sets the main View of the application, this is the WebView within which * Sets the main View of the application, this is the WebView within which
* a Cordova app runs. * a Cordova app runs.
* *
* @param webView The Cordova WebView * @param webView The Cordova WebView
*/ */
public void setView(WebView webView) { public void setView(WebView webView) {
this.webView = webView; this.webView = webView;
} }
/** /**
* Called when the system is about to start resuming a previous activity. * Called when the system is about to start resuming a previous activity.
@ -131,7 +131,7 @@ public abstract class Plugin implements IPlugin {
* @return Return true to prevent the URL from loading. Default is false. * @return Return true to prevent the URL from loading. Default is false.
*/ */
public boolean onOverrideUrlLoading(String url) { public boolean onOverrideUrlLoading(String url) {
return false; return false;
} }
/** /**
@ -141,7 +141,7 @@ public abstract class Plugin implements IPlugin {
* @param statement * @param statement
*/ */
public void sendJavascript(String statement) { public void sendJavascript(String statement) {
this.ctx.sendJavascript(statement); this.ctx.sendJavascript(statement);
} }
/** /**
@ -152,10 +152,10 @@ public abstract class Plugin implements IPlugin {
* call success(...) or error(...) * call success(...) or error(...)
* *
* @param pluginResult The result to return. * @param pluginResult The result to return.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void success(PluginResult pluginResult, String callbackId) { public void success(PluginResult pluginResult, String callbackId) {
this.ctx.sendJavascript(pluginResult.toSuccessCallbackString(callbackId)); this.ctx.sendJavascript(pluginResult.toSuccessCallbackString(callbackId));
} }
/** /**
@ -165,7 +165,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void success(JSONObject message, String callbackId) { public void success(JSONObject message, String callbackId) {
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId)); this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
} }
/** /**
@ -175,17 +175,17 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void success(String message, String callbackId) { public void success(String message, String callbackId) {
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId)); this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
} }
/** /**
* Call the JavaScript error callback for this plugin. * Call the JavaScript error callback for this plugin.
* *
* @param pluginResult The result to return. * @param pluginResult The result to return.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void error(PluginResult pluginResult, String callbackId) { public void error(PluginResult pluginResult, String callbackId) {
this.ctx.sendJavascript(pluginResult.toErrorCallbackString(callbackId)); this.ctx.sendJavascript(pluginResult.toErrorCallbackString(callbackId));
} }
/** /**
@ -195,7 +195,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void error(JSONObject message, String callbackId) { public void error(JSONObject message, String callbackId) {
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId)); this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
} }
/** /**
@ -205,6 +205,6 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
*/ */
public void error(String message, String callbackId) { public void error(String message, String callbackId) {
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId)); this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
} }
} }

View File

@ -21,99 +21,97 @@ package org.apache.cordova.api;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import android.util.Log;
public class PluginResult { public class PluginResult {
private final int status; private final int status;
private final String message; private final String message;
private boolean keepCallback = false; private boolean keepCallback = false;
public PluginResult(Status status) { public PluginResult(Status status) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = "'" + PluginResult.StatusMessages[this.status] + "'"; this.message = "'" + PluginResult.StatusMessages[this.status] + "'";
} }
public PluginResult(Status status, String message) { public PluginResult(Status status, String message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = JSONObject.quote(message); this.message = JSONObject.quote(message);
} }
public PluginResult(Status status, JSONArray message) { public PluginResult(Status status, JSONArray message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = message.toString(); this.message = message.toString();
} }
public PluginResult(Status status, JSONObject message) { public PluginResult(Status status, JSONObject message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = message.toString(); this.message = message.toString();
} }
public PluginResult(Status status, int i) { public PluginResult(Status status, int i) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+i; this.message = ""+i;
} }
public PluginResult(Status status, float f) { public PluginResult(Status status, float f) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+f; this.message = ""+f;
} }
public PluginResult(Status status, boolean b) { public PluginResult(Status status, boolean b) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+b; this.message = ""+b;
} }
public void setKeepCallback(boolean b) { public void setKeepCallback(boolean b) {
this.keepCallback = b; this.keepCallback = b;
} }
public int getStatus() { public int getStatus() {
return status; return status;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public boolean getKeepCallback() { public boolean getKeepCallback() {
return this.keepCallback; return this.keepCallback;
} }
public String getJSONString() { public String getJSONString() {
return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}"; return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}";
} }
public String toSuccessCallbackString(String callbackId) { public String toSuccessCallbackString(String callbackId) {
return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");"; return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
} }
public String toErrorCallbackString(String callbackId) { public String toErrorCallbackString(String callbackId) {
return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");"; return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
} }
public static String[] StatusMessages = new String[] { public static String[] StatusMessages = new String[] {
"No result", "No result",
"OK", "OK",
"Class not found", "Class not found",
"Illegal access", "Illegal access",
"Instantiation error", "Instantiation error",
"Malformed url", "Malformed url",
"IO error", "IO error",
"Invalid action", "Invalid action",
"JSON error", "JSON error",
"Error" "Error"
}; };
public enum Status { public enum Status {
NO_RESULT, NO_RESULT,
OK, OK,
CLASS_NOT_FOUND_EXCEPTION, CLASS_NOT_FOUND_EXCEPTION,
ILLEGAL_ACCESS_EXCEPTION, ILLEGAL_ACCESS_EXCEPTION,
INSTANTIATION_EXCEPTION, INSTANTIATION_EXCEPTION,
MALFORMED_URL_EXCEPTION, MALFORMED_URL_EXCEPTION,
IO_EXCEPTION, IO_EXCEPTION,
INVALID_ACTION, INVALID_ACTION,
JSON_EXCEPTION, JSON_EXCEPTION,
ERROR ERROR
} }
} }

View File

@ -21,8 +21,8 @@ package org.apache.cordova.file;
public class EncodingException extends Exception { public class EncodingException extends Exception {
public EncodingException(String message) { public EncodingException(String message) {
super(message); super(message);
} }
} }

View File

@ -21,8 +21,8 @@ package org.apache.cordova.file;
public class FileExistsException extends Exception { public class FileExistsException extends Exception {
public FileExistsException(String msg) { public FileExistsException(String msg) {
super(msg); super(msg);
} }
} }

View File

@ -22,8 +22,8 @@ package org.apache.cordova.file;
public class InvalidModificationException extends Exception { public class InvalidModificationException extends Exception {
public InvalidModificationException(String message) { public InvalidModificationException(String message) {
super(message); super(message);
} }
} }

View File

@ -21,8 +21,8 @@ package org.apache.cordova.file;
public class NoModificationAllowedException extends Exception { public class NoModificationAllowedException extends Exception {
public NoModificationAllowedException(String message) { public NoModificationAllowedException(String message) {
super(message); super(message);
} }
} }

View File

@ -22,8 +22,8 @@ package org.apache.cordova.file;
public class TypeMismatchException extends Exception { public class TypeMismatchException extends Exception {
public TypeMismatchException(String message) { public TypeMismatchException(String message) {
super(message); super(message);
} }
} }