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

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information
@ -39,12 +39,12 @@
<uses-permission android:name="android.permission.RECORD_VIDEO"/> <uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" /> <uses-feature android:name="android.hardware.camera.autofocus" />
@ -57,7 +57,7 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name="org.apache.cordova.DroidGap" android:label="@string/app_name" <activity android:name="org.apache.cordova.DroidGap" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"> android:configChanges="orientation|keyboardHidden">
<intent-filter> <intent-filter>
</intent-filter> </intent-filter>
@ -65,4 +65,4 @@
</application> </application>
<uses-sdk android:minSdkVersion="2" /> <uses-sdk android:minSdkVersion="2" />
</manifest> </manifest>

View File

@ -1,4 +1,4 @@
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information
@ -51,7 +51,7 @@
--> -->
<property file="ant.properties" /> <property file="ant.properties" />
<!-- We need to setup the double quote. --> <!-- We need to setup the double quote. -->
<property name="dblQuote">"</property> <property name="dblQuote">"</property>
@ -110,10 +110,10 @@
<!-- Combine JavaScript files into one cordova-uncompressed.js file. --> <!-- Combine JavaScript files into one cordova-uncompressed.js file. -->
<target name="build-javascript" depends="clean"> <target name="build-javascript" depends="clean">
<!-- Clean up existing files --> <!-- Clean up existing files -->
<!--<delete file="assets/www/cordova_${version}.js"/>--> <!--<delete file="assets/www/cordova_${version}.js"/>-->
<!-- Create uncompressed JS file --> <!-- Create uncompressed JS file -->
<concat destfile="assets/www/cordova-${version}.js"> <concat destfile="assets/www/cordova-${version}.js">
<filelist dir="assets/js" files="cordova.android.js"/> <filelist dir="assets/js" files="cordova.android.js"/>
@ -121,8 +121,8 @@
<!-- update project files to reference cordova-x.x.x.min.js --> <!-- update project files to reference cordova-x.x.x.min.js -->
<replaceregexp match="cordova(.*)\.js" replace="cordova-${version}.js" byline="true"> <replaceregexp match="cordova(.*)\.js" replace="cordova-${version}.js" byline="true">
<fileset file="assets/www/index.html" /> <fileset file="assets/www/index.html" />
<fileset file="../bin/templates/project/cordova/templates/project/assets/www/index.html" /> <fileset file="../bin/templates/project/cordova/templates/project/assets/www/index.html" />
</replaceregexp> </replaceregexp>
<!-- This is sketchy, but it works, ${dblQuote} does not --> <!-- This is sketchy, but it works, ${dblQuote} does not -->

View File

@ -1,8 +1,8 @@
# This file is automatically generated by Android Tools. # This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED! # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
# #
# This file must be checked in Version Control Systems. # This file must be checked in Version Control Systems.
# #
# To customize properties used by the Ant build system use, # To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your # "build.properties", and override values to adapt the script to your
# project structure. # project structure.

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information
@ -21,9 +21,9 @@
android:orientation="vertical" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
> >
<WebView android:id="@+id/appView" <WebView android:id="@+id/appView"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_width="fill_parent"
/> />
</LinearLayout> </LinearLayout>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information
@ -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

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file or more contributor license agreements. See the NOTICE file
distributed with this work for additional information distributed with this work for additional information

View File

@ -20,7 +20,7 @@ package com.phonegap.api;
/** /**
* Log to Android logging system. * Log to Android logging system.
* *
* Log message can be a string or a printf formatted string with arguments. * Log message can be a string or a printf formatted string with arguments.
* See http://developer.android.com/reference/java/util/Formatter.html * See http://developer.android.com/reference/java/util/Formatter.html
*/ */

View File

@ -24,7 +24,7 @@ import android.webkit.WebView;
/** /**
* PluginManager is exposed to JavaScript in the Cordova WebView. * PluginManager is exposed to JavaScript in the Cordova WebView.
* *
* Calling native plugin code can be done by calling PluginManager.exec(...) * Calling native plugin code can be done by calling PluginManager.exec(...)
* from JavaScript. * from JavaScript.
*/ */

View File

@ -22,32 +22,32 @@ import org.json.JSONArray;
import org.json.JSONObject; 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) {
super(status);
}
public PluginResult(Status status, String message) {
super(status, message);
}
public PluginResult(Status status, JSONArray message) { public PluginResult(Status status) {
super(status);
}
public PluginResult(Status status, String 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,12 +31,10 @@ 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;
/** /**
* This class listens to the accelerometer sensor and stores the latest * This class listens to the accelerometer sensor and stores the latest
* acceleration values x,y,z. * acceleration values x,y,z.
*/ */
public class AccelListener extends Plugin implements SensorEventListener { public class AccelListener extends Plugin implements SensorEventListener {
@ -50,7 +43,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
public static int STARTING = 1; public static int STARTING = 1;
public static int RUNNING = 2; public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3; public static int ERROR_FAILED_TO_START = 3;
private float x,y,z; // most recent acceleration values private float x,y,z; // most recent acceleration values
private long timestamp; // time of most recent value private long timestamp; // time of most recent value
private int status; // status of listener private int status; // status of listener
@ -71,11 +64,11 @@ public class AccelListener extends Plugin implements SensorEventListener {
this.timestamp = 0; this.timestamp = 0;
this.setStatus(AccelListener.STOPPED); this.setStatus(AccelListener.STOPPED);
} }
/** /**
* 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) {
@ -85,7 +78,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
/** /**
* 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.
@ -95,7 +88,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
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);
result.setKeepCallback(true); result.setKeepCallback(true);
if (action.equals("start")) { if (action.equals("start")) {
this.callbackId = callbackId; this.callbackId = callbackId;
@ -115,7 +108,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
} }
return result; return 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.
@ -130,46 +123,46 @@ public class AccelListener extends Plugin implements SensorEventListener {
// //
/** /**
* Start listening for acceleration sensor. * Start listening for acceleration sensor.
* *
* @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);
// Get accelerometer from sensor manager
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
// If found, then register as listener this.setStatus(AccelListener.STARTING);
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0); // Get accelerometer from sensor manager
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI); List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
this.setStatus(AccelListener.STARTING);
} else { // If found, then register as listener
this.setStatus(AccelListener.ERROR_FAILED_TO_START); if ((list != null) && (list.size() > 0)) {
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to."); this.mSensor = list.get(0);
return this.status; this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
} this.setStatus(AccelListener.STARTING);
} else {
// Wait until running this.setStatus(AccelListener.ERROR_FAILED_TO_START);
long timeout = 2000; this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
while ((this.status == STARTING) && (timeout > 0)) { return this.status;
timeout = timeout - 100; }
try {
Thread.sleep(100); // Wait until running
} catch (InterruptedException e) { long timeout = 2000;
e.printStackTrace(); while ((this.status == STARTING) && (timeout > 0)) {
} timeout = timeout - 100;
} try {
if (timeout == 0) { Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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;
} }
/** /**
@ -185,16 +178,16 @@ public class AccelListener extends Plugin implements SensorEventListener {
/** /**
* Called when the accuracy of the sensor has changed. * Called when the accuracy of the sensor has changed.
* *
* @param sensor * @param sensor
* @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;
} }
// If not running, then just return // If not running, then just return
if (this.status == AccelListener.STOPPED) { if (this.status == AccelListener.STOPPED) {
return; return;
@ -204,7 +197,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
/** /**
* Sensor listener event. * Sensor listener event.
* *
* @param SensorEvent event * @param SensorEvent event
*/ */
public void onSensorChanged(SensorEvent event) { public void onSensorChanged(SensorEvent event) {
@ -212,14 +205,14 @@ public class AccelListener extends Plugin implements SensorEventListener {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) { if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return; return;
} }
// If not running, then just return // If not running, then just return
if (this.status == AccelListener.STOPPED) { if (this.status == AccelListener.STOPPED) {
return; return;
} }
this.setStatus(AccelListener.RUNNING); this.setStatus(AccelListener.RUNNING);
if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) { if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) {
// Save time that event was received // Save time that event was received
@ -247,7 +240,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
this.error(err, this.callbackId); this.error(err, this.callbackId);
} }
private void win() { private void win() {
// Success return object // Success return object
PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON()); PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON());
@ -259,7 +252,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
private void setStatus(int status) { private void setStatus(int status) {
this.status = status; this.status = status;
} }
private JSONObject getAccelerationJSON() { private JSONObject getAccelerationJSON() {
JSONObject r = new JSONObject(); JSONObject r = new JSONObject();
try { try {

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,87 +80,87 @@ 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.
*
* @param url
* @param props Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...)
* @throws JSONException
*/
public void loadUrl(String url, JSONObject props) throws JSONException {
LOG.d("App", "App.loadUrl("+url+","+props+")");
int wait = 0;
boolean openExternal = false;
boolean clearHistory = false;
// If there are properties, then set them on the Activity /**
HashMap<String, Object> params = new HashMap<String, Object>(); * Load the url into the webview.
if (props != null) { *
JSONArray keys = props.names(); * @param url
for (int i=0; i<keys.length(); i++) { * @param props Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...)
String key = keys.getString(i); * @throws JSONException
if (key.equals("wait")) { */
wait = props.getInt(key); public void loadUrl(String url, JSONObject props) throws JSONException {
} LOG.d("App", "App.loadUrl("+url+","+props+")");
else if (key.equalsIgnoreCase("openexternal")) { int wait = 0;
openExternal = props.getBoolean(key); boolean openExternal = false;
} boolean clearHistory = false;
else if (key.equalsIgnoreCase("clearhistory")) {
clearHistory = props.getBoolean(key);
}
else {
Object value = props.get(key);
if (value == null) {
} // If there are properties, then set them on the Activity
else if (value.getClass().equals(String.class)) { HashMap<String, Object> params = new HashMap<String, Object>();
params.put(key, (String)value); if (props != null) {
} JSONArray keys = props.names();
else if (value.getClass().equals(Boolean.class)) { for (int i=0; i<keys.length(); i++) {
params.put(key, (Boolean)value); String key = keys.getString(i);
} if (key.equals("wait")) {
else if (value.getClass().equals(Integer.class)) { wait = props.getInt(key);
params.put(key, (Integer)value); }
} else if (key.equalsIgnoreCase("openexternal")) {
} openExternal = props.getBoolean(key);
} }
} else if (key.equalsIgnoreCase("clearhistory")) {
clearHistory = props.getBoolean(key);
}
else {
Object value = props.get(key);
if (value == null) {
// If wait property, then delay loading }
else if (value.getClass().equals(String.class)) {
params.put(key, (String)value);
}
else if (value.getClass().equals(Boolean.class)) {
params.put(key, (Boolean)value);
}
else if (value.getClass().equals(Integer.class)) {
params.put(key, (Integer)value);
}
}
}
}
if (wait > 0) { // If wait property, then delay loading
try {
synchronized(this) { if (wait > 0) {
this.wait(wait); try {
} synchronized(this) {
} catch (InterruptedException e) { this.wait(wait);
e.printStackTrace(); }
} } catch (InterruptedException e) {
} 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.
*/
public void cancelLoadUrl() {
((DroidGap)this.ctx).cancelLoadUrl();
}
/**
* Cancel loadUrl before it has been loaded.
*/
public void 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();
} }
/** /**
* Go to previous page displayed. * Go to previous page displayed.
* This is the same as pressing the backbutton on Android device. * This is the same as pressing the backbutton on Android device.
@ -172,27 +172,27 @@ public class App extends Plugin {
/** /**
* Override the default behavior of the Android back button. * Override the default behavior of the Android back button.
* If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired. * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.
* *
* @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;
} }
/** /**
* Return whether the Android back button is overridden by the user. * Return whether the Android back button is overridden by the user.
* *
* @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,22 +22,20 @@ 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.
* The file can be local or over a network using http. * The file can be local or over a network using http.
* *
* Audio formats supported (tested): * Audio formats supported (tested):
* .mp3, .wav * .mp3, .wav
* *
* Local audio files must reside in one of two places: * Local audio files must reside in one of two places:
* android_asset: file name must start with /android_asset/sound.mp3 * android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3 * sdcard: file name is just sound.mp3
@ -45,112 +43,112 @@ 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.
*/
public AudioHandler() {
this.players = new HashMap<String,AudioPlayer>();
this.pausedForPhone = new ArrayList<AudioPlayer>();
}
/** /**
* Executes the request and returns PluginResult. * Constructor.
* */
* @param action The action to execute. public AudioHandler() {
* @param args JSONArry of arguments for the plugin. this.players = new HashMap<String,AudioPlayer>();
* @param callbackId The callback id used when calling back into JavaScript. this.pausedForPhone = new ArrayList<AudioPlayer>();
* @return A PluginResult object with a status and message. }
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("startRecordingAudio")) {
this.startRecordingAudio(args.getString(0), args.getString(1));
}
else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0));
}
else if (action.equals("startPlayingAudio")) {
this.startPlayingAudio(args.getString(0), args.getString(1));
}
else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1));
}
else if (action.equals("pausePlayingAudio")) {
this.pausePlayingAudio(args.getString(0));
}
else if (action.equals("stopPlayingAudio")) {
this.stopPlayingAudio(args.getString(0));
} else if (action.equals("setVolume")) {
try {
this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
} catch (NumberFormatException nfe) {
//no-op
}
} else if (action.equals("getCurrentPositionAudio")) {
float f = this.getCurrentPositionAudio(args.getString(0));
return new PluginResult(status, f);
}
else if (action.equals("getDurationAudio")) {
float f = this.getDurationAudio(args.getString(0), args.getString(1));
return new PluginResult(status, f);
}
else if (action.equals("release")) {
boolean b = this.release(args.getString(0));
return new PluginResult(status, b);
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/** /**
* Identifies if action to be executed returns a value and should be run synchronously. * Executes the request and returns PluginResult.
* *
* @param action The action to execute * @param action The action to execute.
* @return T=returns value * @param args JSONArry of arguments for the plugin.
*/ * @param callbackId The callback id used when calling back into JavaScript.
public boolean isSynch(String action) { * @return A PluginResult object with a status and message.
if (action.equals("getCurrentPositionAudio")) { */
return true; public PluginResult execute(String action, JSONArray args, String callbackId) {
} PluginResult.Status status = PluginResult.Status.OK;
else if (action.equals("getDurationAudio")) { String result = "";
return true;
}
return false;
}
/** try {
* Stop all audio players and recorders. if (action.equals("startRecordingAudio")) {
*/ this.startRecordingAudio(args.getString(0), args.getString(1));
public void onDestroy() { }
else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0));
}
else if (action.equals("startPlayingAudio")) {
this.startPlayingAudio(args.getString(0), args.getString(1));
}
else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1));
}
else if (action.equals("pausePlayingAudio")) {
this.pausePlayingAudio(args.getString(0));
}
else if (action.equals("stopPlayingAudio")) {
this.stopPlayingAudio(args.getString(0));
} else if (action.equals("setVolume")) {
try {
this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
} catch (NumberFormatException nfe) {
//no-op
}
} else if (action.equals("getCurrentPositionAudio")) {
float f = this.getCurrentPositionAudio(args.getString(0));
return new PluginResult(status, f);
}
else if (action.equals("getDurationAudio")) {
float f = this.getDurationAudio(args.getString(0), args.getString(1));
return new PluginResult(status, f);
}
else if (action.equals("release")) {
boolean b = this.release(args.getString(0));
return new PluginResult(status, b);
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("getCurrentPositionAudio")) {
return true;
}
else if (action.equals("getDurationAudio")) {
return true;
}
return false;
}
/**
* Stop all audio players and recorders.
*/
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.
* *
* @param id The message id * @param id The message id
* @param data The message data * @param data The message data
*/ */
public void onMessage(String id, Object data) { public void onMessage(String id, Object data) {
// If phone message // If phone message
if (id.equals("telephone")) { if (id.equals("telephone")) {
// If phone ringing, then pause playing // If phone ringing, then pause playing
if ("ringing".equals(data) || "offhook".equals(data)) { if ("ringing".equals(data) || "offhook".equals(data)) {
// Get all audio players and pause them // Get all audio players and pause them
for (AudioPlayer audio : this.players.values()) { for (AudioPlayer audio : this.players.values()) {
if (audio.getState() == AudioPlayer.MEDIA_RUNNING) { if (audio.getState() == AudioPlayer.MEDIA_RUNNING) {
@ -160,7 +158,7 @@ public class AudioHandler extends Plugin {
} }
} }
// If phone idle, then resume playing those players we paused // If phone idle, then resume playing those players we paused
else if ("idle".equals(data)) { else if ("idle".equals(data)) {
for (AudioPlayer audio : this.pausedForPhone) { for (AudioPlayer audio : this.pausedForPhone) {
@ -174,177 +172,177 @@ public class AudioHandler extends Plugin {
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/**
* Release the audio player instance to save memory.
*
* @param id The id of the audio player
*/
private boolean release(String id) {
if (!this.players.containsKey(id)) {
return false;
}
AudioPlayer audio = this.players.get(id);
this.players.remove(id);
audio.destroy();
return true;
}
/** /**
* Start recording and save the specified file. * Release the audio player instance to save memory.
* *
* @param id The id of the audio player * @param id The id of the audio player
* @param file The name of the file */
*/ private boolean release(String id) {
if (!this.players.containsKey(id)) {
return false;
}
AudioPlayer audio = this.players.get(id);
this.players.remove(id);
audio.destroy();
return true;
}
/**
* Start recording and save the specified file.
*
* @param id The id of the audio player
* @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));
} }
} }
/** /**
* Set the audio device to be used for playback. * Set the audio device to be used for playback.
* *
* @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.");
} }
} }
/** /**
* Get the audio device to be used for playback. * Get the audio device to be used for playback.
* *
* @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

@ -35,7 +35,7 @@ import java.io.IOException;
* This class implements the audio playback and recording capabilities used by Cordova. * This class implements the audio playback and recording capabilities used by Cordova.
* It is called by the AudioHandler Cordova class. * It is called by the AudioHandler Cordova class.
* Only one file can be played or recorded per class instance. * Only one file can be played or recorded per class instance.
* *
* Local audio files must reside in one of two places: * Local audio files must reside in one of two places:
* android_asset: file name must start with /android_asset/sound.mp3 * android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3 * sdcard: file name is just sound.mp3
@ -45,422 +45,422 @@ 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 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 String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object private AudioHandler handler; // The AudioHandler object
private String tempFile = null; // Temporary recording file name 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 MediaPlayer mPlayer = null; // Audio player object private String audioFile = null; // File name to play or record to
private boolean prepareOnly = false; private float duration = -1; // Duration of audio
/** private MediaRecorder recorder = null; // Audio recording object
* Constructor. private String tempFile = null; // Temporary recording file name
*
* @param handler The audio handler object private MediaPlayer mPlayer = null; // Audio player object
* @param id The id of this audio player private boolean prepareOnly = false;
*/
public AudioPlayer(AudioHandler handler, String id) { /**
this.handler = handler; * Constructor.
this.id = id; *
* @param handler The audio handler object
* @param id The id of this audio player
*/
public AudioPlayer(AudioHandler handler, String id) {
this.handler = handler;
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
if (this.mPlayer != null) {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
this.mPlayer.stop();
this.setState(MEDIA_STOPPED);
}
this.mPlayer.release();
this.mPlayer = null;
}
if (this.recorder != null) {
this.stopRecording();
this.recorder.release();
this.recorder = null;
}
}
/** // Stop any play or record
* Start recording the specified file. if (this.mPlayer != null) {
* if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
* @param file The name of the file this.mPlayer.stop();
*/ this.setState(MEDIA_STOPPED);
public void startRecording(String file) { }
if (this.mPlayer != null) { this.mPlayer.release();
Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode."); this.mPlayer = null;
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); }
} if (this.recorder != null) {
this.stopRecording();
// Make sure we're not already recording this.recorder.release();
else if (this.recorder == null) { this.recorder = null;
this.audioFile = file; }
this.recorder = new MediaRecorder(); }
this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
this.recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // THREE_GPP); /**
this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); //AMR_NB); * Start recording the specified file.
this.recorder.setOutputFile(this.tempFile); *
try { * @param file The name of the file
this.recorder.prepare(); */
this.recorder.start(); public void startRecording(String file) {
this.setState(MEDIA_RUNNING); if (this.mPlayer != null) {
return; Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
} catch (IllegalStateException e) { this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
e.printStackTrace(); }
} catch (IOException e) {
e.printStackTrace(); // Make sure we're not already recording
} else if (this.recorder == null) {
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); this.audioFile = file;
} this.recorder = new MediaRecorder();
else { this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Log.d(LOG_TAG, "AudioPlayer Error: Already recording."); this.recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // THREE_GPP);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});"); this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); //AMR_NB);
} this.recorder.setOutputFile(this.tempFile);
} try {
this.recorder.prepare();
/** this.recorder.start();
* Save temporary recorded file to specified name this.setState(MEDIA_RUNNING);
* return;
* @param file } catch (IllegalStateException e) {
*/ e.printStackTrace();
public void moveFile(String file) { } catch (IOException e) {
/* this is a hack to save the file as the specified name */ e.printStackTrace();
File f = new File(this.tempFile); }
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
}
else {
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+"});");
}
}
/**
* Save temporary recorded file to specified name
*
* @param file
*/
public void moveFile(String file) {
/* this is a hack to save the file as the specified name */
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));
} else { } else {
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()) {
FileInputStream fileInputStream = new FileInputStream(file); FileInputStream fileInputStream = new FileInputStream(file);
this.mPlayer.setDataSource(fileInputStream.getFD()); this.mPlayer.setDataSource(fileInputStream.getFD());
} }
else { else {
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 ((this.state == MEDIA_PAUSED) || (this.state == MEDIA_STARTING)) {
this.mPlayer.start();
this.setState(MEDIA_RUNNING);
}
else {
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+"});");
}
}
}
/** // If player has been paused, then resume playback
* Seek or jump to a new time in the track. if ((this.state == MEDIA_PAUSED) || (this.state == MEDIA_STARTING)) {
*/ this.mPlayer.start();
public void seekToPlaying(int milliseconds) { this.setState(MEDIA_RUNNING);
if (this.mPlayer != null) { }
this.mPlayer.seekTo(milliseconds); else {
Log.d(LOG_TAG, "Send a onStatus update for the new seek"); 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_POSITION+", "+milliseconds/1000.0f+");"); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
} }
} }
}
/**
* Pause playing. /**
*/ * Seek or jump to a new time in the track.
public void pausePlaying() { */
public void seekToPlaying(int milliseconds) {
// If playing, then pause if (this.mPlayer != null) {
if (this.state == MEDIA_RUNNING) { this.mPlayer.seekTo(milliseconds);
this.mPlayer.pause(); Log.d(LOG_TAG, "Send a onStatus update for the new seek");
this.setState(MEDIA_PAUSED); this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+milliseconds/1000.0f+");");
} }
else { }
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+"});"); /**
} * Pause playing.
} */
public void pausePlaying() {
// If playing, then pause
if (this.state == MEDIA_RUNNING) {
this.mPlayer.pause();
this.setState(MEDIA_PAUSED);
}
else {
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+"});");
}
}
/** /**
* 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);
} }
/** /**
* Get current position of playback. * Get current position of playback.
* *
* @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.
* *
* @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.
* -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
if (this.recorder != null) {
return(-2); // not allowed
}
// If audio file already loaded and started, then return duration
if (this.mPlayer != null) {
return this.duration;
}
// If no player yet, then create one
else {
this.prepareOnly = true;
this.startPlaying(file);
// This will only return value for local, since streaming
// file hasn't been read yet.
return this.duration;
}
}
/** // Can't get duration of recording
* Callback to be invoked when the media source is ready for playback. if (this.recorder != null) {
* return(-2); // not allowed
* @param mPlayer The MediaPlayer that is ready for playback }
*/
public void onPrepared(MediaPlayer mPlayer) {
// Listen for playback completion
this.mPlayer.setOnCompletionListener(this);
// If start playing after prepared // If audio file already loaded and started, then return duration
if (!this.prepareOnly) { if (this.mPlayer != null) {
return this.duration;
// Start playing }
this.mPlayer.start();
// Set player init flag // If no player yet, then create one
this.setState(MEDIA_RUNNING); else {
} this.prepareOnly = true;
this.startPlaying(file);
// Save off duration
this.duration = getDurationInSeconds();
this.prepareOnly = false;
// Send status notification to JavaScript // This will only return value for local, since streaming
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_DURATION+","+this.duration+");"); // file hasn't been read yet.
return this.duration;
} }
}
/** /**
* By default Android returns the length of audio in mills but we want seconds * Callback to be invoked when the media source is ready for playback.
* *
* @return length of clip in seconds * @param mPlayer The MediaPlayer that is ready for playback
*/ */
private float getDurationInSeconds() { public void onPrepared(MediaPlayer mPlayer) {
return (this.mPlayer.getDuration() / 1000.0f); // Listen for playback completion
} this.mPlayer.setOnCompletionListener(this);
/** // If start playing after prepared
* Callback to be invoked when there has been an error during an asynchronous operation if (!this.prepareOnly) {
* (other errors will throw exceptions at method call time).
*
* @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 arg2 an extra code, specific to the error.
*/
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")");
// TODO: Not sure if this needs to be sent? // Start playing
this.mPlayer.stop(); this.mPlayer.start();
this.mPlayer.release();
// Send error notification to JavaScript
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":"+arg1+"});");
return false;
}
/**
* Set the state and send it to JavaScript.
*
* @param state
*/
private void setState(int state) {
if (this.state != state) {
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");");
}
this.state = state;
}
/**
* Get the audio state.
*
* @return int
*/
public int getState() {
return this.state;
}
/** // Set player init flag
* Set the volume for audio player this.setState(MEDIA_RUNNING);
* }
* @param volume
*/ // Save off duration
this.duration = getDurationInSeconds();
this.prepareOnly = false;
// Send status notification to JavaScript
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
*
* @return length of clip in seconds
*/
private float getDurationInSeconds() {
return (this.mPlayer.getDuration() / 1000.0f);
}
/**
* Callback to be invoked when there has been an error during an asynchronous operation
* (other errors will throw exceptions at method call time).
*
* @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 arg2 an extra code, specific to the error.
*/
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")");
// TODO: Not sure if this needs to be sent?
this.mPlayer.stop();
this.mPlayer.release();
// Send error notification to JavaScript
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":"+arg1+"});");
return false;
}
/**
* Set the state and send it to JavaScript.
*
* @param state
*/
private void setState(int state) {
if (this.state != state) {
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");");
}
this.state = state;
}
/**
* Get the audio state.
*
* @return int
*/
public int getState() {
return this.state;
}
/**
* Set the volume for audio player
*
* @param volume
*/
public void setVolume(float volume) { public void setVolume(float volume) {
this.mPlayer.setVolume(volume, volume); this.mPlayer.setVolume(volume, volume);
} }

View File

@ -24,46 +24,46 @@ package org.apache.cordova;
public class AuthenticationToken { public class AuthenticationToken {
private String userName; private String userName;
private String password; private String password;
/** /**
* Gets the user name. * Gets the user name.
* *
* @return the user name * @return the user name
*/ */
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
/** /**
* Sets the user name. * Sets the user name.
* *
* @param userName * @param userName
* the new user name * the new user name
*/ */
public void setUserName(String userName) { public void setUserName(String userName) {
this.userName = userName; this.userName = userName;
} }
/** /**
* Gets the password. * Gets the password.
* *
* @return the password * @return the password
*/ */
public String getPassword() { public String getPassword() {
return password; return password;
} }
/** /**
* Sets the password. * Sets the password.
* *
* @param password * @param password
* the new password * the new password
*/ */
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
} }

View File

@ -32,23 +32,23 @@ import android.content.IntentFilter;
import android.util.Log; import android.util.Log;
public class BatteryListener extends Plugin { public class BatteryListener extends Plugin {
private static final String LOG_TAG = "BatteryManager"; private static final String LOG_TAG = "BatteryManager";
BroadcastReceiver receiver; BroadcastReceiver receiver;
private String batteryCallbackId = null; private String batteryCallbackId = null;
/** /**
* Constructor. * Constructor.
*/ */
public BatteryListener() { public BatteryListener() {
this.receiver = null; this.receiver = null;
} }
/** /**
* 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.
@ -56,12 +56,12 @@ public class BatteryListener extends Plugin {
*/ */
public PluginResult execute(String action, JSONArray args, String callbackId) { public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.INVALID_ACTION; PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
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
@ -70,29 +70,29 @@ public class BatteryListener extends Plugin {
if (this.receiver == null) { if (this.receiver == null) {
this.receiver = new BroadcastReceiver() { this.receiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
updateBatteryInfo(intent); updateBatteryInfo(intent);
} }
}; };
ctx.registerReceiver(this.receiver, intentFilter); ctx.registerReceiver(this.receiver, intentFilter);
} }
// Don't return any result now, since status results will be sent when events come in from broadcast receiver // Don't return any result now, since status results will be sent when events come in from broadcast receiver
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true); pluginResult.setKeepCallback(true);
return pluginResult; return pluginResult;
} }
else if (action.equals("stop")) { else if (action.equals("stop")) {
removeBatteryListener(); removeBatteryListener();
this.sendUpdate(new JSONObject(), false); // release status callback in JS side this.sendUpdate(new JSONObject(), false); // release status callback in JS side
this.batteryCallbackId = null; this.batteryCallbackId = null;
return new PluginResult(PluginResult.Status.OK); return new PluginResult(PluginResult.Status.OK);
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} }
/** /**
* Stop battery receiver. * Stop battery receiver.
*/ */
@ -116,7 +116,7 @@ public class BatteryListener extends Plugin {
/** /**
* Creates a JSONObject with the current battery information * Creates a JSONObject with the current battery information
* *
* @param batteryIntent the current battery information * @param batteryIntent the current battery information
* @return a JSONObject containing the battery status information * @return a JSONObject containing the battery status information
*/ */
@ -133,24 +133,24 @@ public class BatteryListener extends Plugin {
/** /**
* Updates the JavaScript side whenever the battery changes * Updates the JavaScript side whenever the battery changes
* *
* @param batteryIntent the current battery information * @param batteryIntent the current battery information
* @return * @return
*/ */
private void updateBatteryInfo(Intent batteryIntent) { private void updateBatteryInfo(Intent batteryIntent) {
sendUpdate(this.getBatteryInfo(batteryIntent), true); sendUpdate(this.getBatteryInfo(batteryIntent), true);
} }
/** /**
* Create a new plugin result and send it back to JavaScript * Create a new plugin result and send it back to JavaScript
* *
* @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,337 +25,334 @@ 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
* statements that are to be executed on the web page. * statements that are to be executed on the web page.
* *
* The process flow for XHR is: * The process flow for XHR is:
* 1. JavaScript makes an async XHR call. * 1. JavaScript makes an async XHR call.
* 2. The server holds the connection open until data is available. * 2. The server holds the connection open until data is available.
* 3. The server writes the data to the client and closes the connection. * 3. The server writes the data to the client and closes the connection.
* 4. The server immediately starts listening for the next XHR call. * 4. The server immediately starts listening for the next XHR call.
* 5. The client receives this XHR response, processes it. * 5. The client receives this XHR response, processes it.
* 6. The client sends a new async XHR request. * 6. The client sends a new async XHR request.
* *
* The CallbackServer class requires the following permission in Android manifest file * The CallbackServer class requires the following permission in Android manifest file
* <uses-permission android:name="android.permission.INTERNET" /> * <uses-permission android:name="android.permission.INTERNET" />
* *
* If the device has a proxy set, then XHR cannot be used, so polling must be used instead. * If the device has a proxy set, then XHR cannot be used, so polling must be used instead.
* This can be determined by the client by calling CallbackServer.usePolling(). * This can be determined by the client by calling CallbackServer.usePolling().
* *
* The process flow for polling is: * The process flow for polling is:
* 1. The client calls CallbackServer.getJavascript() to retrieve next statement. * 1. The client calls CallbackServer.getJavascript() to retrieve next statement.
* 2. If statement available, then client processes it. * 2. If statement available, then client processes it.
* 3. The client repeats #1 in loop. * 3. The client repeats #1 in loop.
*/ */
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.
*/ /**
private LinkedList<String> javascript; * The list of JavaScript statements to be sent to JavaScript.
*/
/** private LinkedList<String> javascript;
* The port to listen on.
*/ /**
private int port; * The port to listen on.
*/
/** private int port;
* The server thread.
*/ /**
private Thread serverThread; * The server thread.
*/
/** private Thread serverThread;
* Indicates the server is running.
*/ /**
private boolean active; * Indicates the server is running.
*/
/** private boolean active;
* Indicates that the JavaScript statements list is empty
*/ /**
private boolean empty; * Indicates that the JavaScript statements list is empty
*/
/** private boolean empty;
* Indicates that polling should be used instead of XHR.
*/ /**
private boolean usePolling = true; * Indicates that polling should be used instead of XHR.
*/
/** private boolean usePolling = true;
* Security token to prevent other apps from accessing this callback server via XHR
*/ /**
private String token; * Security token to prevent other apps from accessing this callback server via XHR
*/
/** private String token;
* Constructor.
*/ /**
public CallbackServer() { * Constructor.
//System.out.println("CallbackServer()"); */
this.active = false; public CallbackServer() {
this.empty = true; //System.out.println("CallbackServer()");
this.port = 0; this.active = false;
this.javascript = new LinkedList<String>(); this.empty = true;
} this.port = 0;
this.javascript = new LinkedList<String>();
/** }
* Init callback server and start XHR if running local app.
* /**
* If Cordova app is loaded from file://, then we can use XHR * Init callback server and start XHR if running local app.
* otherwise we have to use polling due to cross-domain security restrictions. *
* * If Cordova app is loaded from file://, then we can use XHR
* @param url The URL of the Cordova app being loaded * otherwise we have to use polling due to cross-domain security restrictions.
*/ *
public void init(String url) { * @param url The URL of the Cordova app being loaded
//System.out.println("CallbackServer.start("+url+")"); */
this.active = false; public void init(String url) {
this.empty = true; //System.out.println("CallbackServer.start("+url+")");
this.port = 0; this.active = false;
this.javascript = new LinkedList<String>(); this.empty = true;
this.port = 0;
this.javascript = new LinkedList<String>();
// Determine if XHR or polling is to be used
if ((url != null) && !url.startsWith("file://")) {
this.usePolling = true;
this.stopServer();
}
else if (android.net.Proxy.getDefaultHost() != null) {
this.usePolling = true;
this.stopServer();
}
else {
this.usePolling = false;
this.startServer();
}
}
// Determine if XHR or polling is to be used
if ((url != null) && !url.startsWith("file://")) {
this.usePolling = true;
this.stopServer();
}
else if (android.net.Proxy.getDefaultHost() != null) {
this.usePolling = true;
this.stopServer();
}
else {
this.usePolling = false;
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
*/
public boolean usePolling() {
return this.usePolling;
}
/**
* Get the port that this server is running on.
*
* @return
*/
public int getPort() {
return this.port;
}
/**
* Get the security token that this server requires when calling getJavascript().
*
* @return
*/
public String getToken() {
return this.token;
}
/**
* Start the server on a new thread.
*/
public void startServer() {
//System.out.println("CallbackServer.startServer()");
this.active = false;
// Start server on new thread
this.serverThread = new Thread(this);
this.serverThread.start();
}
/** /**
* Restart the server on a new thread. * Return if polling is being used instead of XHR.
*/ *
public void restartServer() { * @return
*/
// Stop server public boolean usePolling() {
this.stopServer(); return this.usePolling;
}
// Start server again
this.startServer();
}
/** /**
* Start running the server. * Get the port that this server is running on.
* This is called automatically when the server thread is started. *
*/ * @return
public void run() { */
public int getPort() {
// Start server return this.port;
try { }
this.active = true;
String request;
ServerSocket waitSocket = new ServerSocket(0);
this.port = waitSocket.getLocalPort();
//System.out.println("CallbackServer -- using port " +this.port);
this.token = java.util.UUID.randomUUID().toString();
//System.out.println("CallbackServer -- using token "+this.token);
while (this.active) { /**
//System.out.println("CallbackServer: Waiting for data on socket"); * Get the security token that this server requires when calling getJavascript().
Socket connection = waitSocket.accept(); *
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()),40); * @return
DataOutputStream output = new DataOutputStream(connection.getOutputStream()); */
request = xhrReader.readLine(); public String getToken() {
String response = ""; return this.token;
//System.out.println("CallbackServerRequest="+request); }
if (this.active && (request != null)) {
if (request.contains("GET")) {
// Get requested file
String[] requestParts = request.split(" ");
// Must have security token
if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) {
//System.out.println("CallbackServer -- Processing GET request");
// Wait until there is some data to send, or send empty data every 10 sec /**
// to prevent XHR timeout on the client * Start the server on a new thread.
synchronized (this) { */
while (this.empty) { public void startServer() {
try { //System.out.println("CallbackServer.startServer()");
this.wait(10000); // prevent timeout from happening this.active = false;
//System.out.println("CallbackServer>>> break <<<");
break;
}
catch (Exception e) { }
}
}
// If server is still running // Start server on new thread
if (this.active) { this.serverThread = new Thread(this);
this.serverThread.start();
}
// If no data, then send 404 back to client before it times out /**
if (this.empty) { * Restart the server on a new thread.
//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 public void restartServer() {
}
else {
//System.out.println("CallbackServer -- sending item");
response = "HTTP/1.1 200 OK\r\n\r\n";
String js = this.getJavascript();
if (js != null) {
response += encode(js, "UTF-8");
}
}
}
else {
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
}
//System.out.println("CallbackServer: response="+response);
//System.out.println("CallbackServer: closing output");
output.writeBytes(response);
output.flush();
}
output.close();
xhrReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
this.active = false;
//System.out.println("CallbackServer.startServer() - EXIT");
}
/**
* Stop server.
* This stops the thread that the server is running on.
*/
public void stopServer() {
//System.out.println("CallbackServer.stopServer()");
if (this.active) {
this.active = false;
// Break out of server wait // Stop server
synchronized (this) { this.stopServer();
this.notify();
} // Start server again
} this.startServer();
} }
/**
* Start running the server.
* This is called automatically when the server thread is started.
*/
public void run() {
// Start server
try {
this.active = true;
String request;
ServerSocket waitSocket = new ServerSocket(0);
this.port = waitSocket.getLocalPort();
//System.out.println("CallbackServer -- using port " +this.port);
this.token = java.util.UUID.randomUUID().toString();
//System.out.println("CallbackServer -- using token "+this.token);
while (this.active) {
//System.out.println("CallbackServer: Waiting for data on socket");
Socket connection = waitSocket.accept();
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()),40);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
request = xhrReader.readLine();
String response = "";
//System.out.println("CallbackServerRequest="+request);
if (this.active && (request != null)) {
if (request.contains("GET")) {
// Get requested file
String[] requestParts = request.split(" ");
// Must have security token
if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) {
//System.out.println("CallbackServer -- Processing GET request");
// Wait until there is some data to send, or send empty data every 10 sec
// to prevent XHR timeout on the client
synchronized (this) {
while (this.empty) {
try {
this.wait(10000); // prevent timeout from happening
//System.out.println("CallbackServer>>> break <<<");
break;
}
catch (Exception e) { }
}
}
// If server is still running
if (this.active) {
// If no data, then send 404 back to client before it times out
if (this.empty) {
//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
}
else {
//System.out.println("CallbackServer -- sending item");
response = "HTTP/1.1 200 OK\r\n\r\n";
String js = this.getJavascript();
if (js != null) {
response += encode(js, "UTF-8");
}
}
}
else {
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
}
//System.out.println("CallbackServer: response="+response);
//System.out.println("CallbackServer: closing output");
output.writeBytes(response);
output.flush();
}
output.close();
xhrReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
this.active = false;
//System.out.println("CallbackServer.startServer() - EXIT");
}
/**
* Stop server.
* This stops the thread that the server is running on.
*/
public void stopServer() {
//System.out.println("CallbackServer.stopServer()");
if (this.active) {
this.active = false;
// Break out of server wait
synchronized (this) {
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,24 +368,24 @@ 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
* common characters that don't require encoding to reduce the size of the string * common characters that don't require encoding to reduce the size of the string
* being passed to JavaScript. * being passed to JavaScript.
* *
* @param s to be encoded * @param s to be encoded
* @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();
} }
// check for UnsupportedEncodingException // check for UnsupportedEncodingException
"".getBytes(enc); "".getBytes(enc);
// Guess a bit bigger for encoded form // Guess a bit bigger for encoded form
StringBuilder buf = new StringBuilder(s.length() + 16); StringBuilder buf = new StringBuilder(s.length() + 16);
int start = -1; int start = -1;
@ -426,6 +423,6 @@ public class CallbackServer implements Runnable {
buf.append(digits.charAt(bytes[j] & 0xf)); buf.append(digits.charAt(bytes[j] & 0xf));
} }
} }
/* end */ /* end */
} }

View File

@ -44,40 +44,40 @@ import android.provider.MediaStore;
/** /**
* This class launches the camera view, allows the user to take a picture, closes the camera view, * This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before * and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed. * the camera view was shown is redisplayed.
*/ */
public class CameraLauncher extends Plugin { public class CameraLauncher extends Plugin {
private static final int DATA_URL = 0; // Return base64 encoded string private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android) private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android) private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL
private static final int ALLMEDIA = 2; // allow selection from all media types private static final int ALLMEDIA = 2; // allow selection from all media types
private static final int JPEG = 0; // Take a picture of type JPEG private static final int JPEG = 0; // Take a picture of type JPEG
private static final int PNG = 1; // Take a picture of type PNG private static final int PNG = 1; // Take a picture of type PNG
private static final String GET_PICTURE = "Get Picture"; private static final String GET_PICTURE = "Get Picture";
private static final String GET_VIDEO = "Get Video"; private static final String GET_VIDEO = "Get Video";
private static final String GET_All = "Get All"; private static final String GET_All = "Get All";
private static final String LOG_TAG = "CameraLauncher"; private static final String LOG_TAG = "CameraLauncher";
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private int targetWidth; // desired width of the image private int targetWidth; // desired width of the image
private int targetHeight; // desired height of the image private int targetHeight; // desired height of the image
private Uri imageUri; // Uri of captured image private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve private int mediaType; // What type of media to retrieve
public String callbackId; public String callbackId;
private int numPics; private int numPics;
/** /**
* Constructor. * Constructor.
*/ */
@ -86,7 +86,7 @@ public class CameraLauncher extends Plugin {
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
@ -94,9 +94,9 @@ public class CameraLauncher extends Plugin {
*/ */
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 = "";
this.callbackId = callbackId; this.callbackId = callbackId;
try { try {
if (action.equals("takePicture")) { if (action.equals("takePicture")) {
int srcType = CAMERA; int srcType = CAMERA;
@ -114,7 +114,7 @@ public class CameraLauncher extends Plugin {
this.targetHeight = args.getInt(4); this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5); this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6); this.mediaType = args.getInt(6);
if (srcType == CAMERA) { if (srcType == CAMERA) {
this.takePicture(destType, encodingType); this.takePicture(destType, encodingType);
} }
@ -131,32 +131,32 @@ public class CameraLauncher extends Plugin {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION); return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} }
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/** /**
* Take a picture with the camera. * Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned * When an image is captured or the camera view is cancelled, the result is returned
* in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult. * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
* *
* The image can either be returned as a base64 string or a URI that points to the file. * The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to: * To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result; * img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag * or to display URI in an img tag
* img.src=result; * img.src=result;
* *
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return. * @param returnType Set the type of image to return.
*/ */
public void takePicture(int returnType, int encodingType) { public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later // Save the number of images currently on disk for later
this.numPics = queryImgDB().getCount(); this.numPics = queryImgDB().getCount();
// Display camera // Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned // Specify file so that large image is captured and returned
// TODO: What if there isn't any external storage? // TODO: What if there isn't any external storage?
File photo = createCaptureFile(encodingType); File photo = createCaptureFile(encodingType);
@ -168,7 +168,7 @@ public class CameraLauncher extends Plugin {
/** /**
* Create a file in the applications temporary directory based upon the supplied encoding. * Create a file in the applications temporary directory based upon the supplied encoding.
* *
* @param encodingType of the image to be taken * @param encodingType of the image to be taken
* @return a File object pointing to the temporary picture * @return a File object pointing to the temporary picture
*/ */
@ -177,7 +177,7 @@ public class CameraLauncher extends Plugin {
if (encodingType == JPEG) { if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.jpg"); photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.jpg");
} else if (encodingType == PNG) { } else if (encodingType == PNG) {
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.png"); photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.png");
} else { } else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType); throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
} }
@ -186,29 +186,29 @@ public class CameraLauncher extends Plugin {
/** /**
* Get image from photo library. * Get image from photo library.
* *
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality) * @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from. * @param srcType The album to get image from.
* @param returnType Set the type of image to return. * @param returnType Set the type of image to return.
*/ */
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do! // TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int srcType, int returnType) { public void getImage(int srcType, int returnType) {
Intent intent = new Intent(); Intent intent = new Intent();
String title = GET_PICTURE; String title = GET_PICTURE;
if (this.mediaType == PICTURE) { if (this.mediaType == PICTURE) {
intent.setType("image/*"); intent.setType("image/*");
} }
else if (this.mediaType == VIDEO) { else if (this.mediaType == VIDEO) {
intent.setType("video/*"); intent.setType("video/*");
title = GET_VIDEO; title = GET_VIDEO;
} }
else if (this.mediaType == ALLMEDIA) { else if (this.mediaType == ALLMEDIA) {
// I wanted to make the type 'image/*, video/*' but this does not work on all versions // I wanted to make the type 'image/*, video/*' but this does not work on all versions
// of android so I had to go with the wildcard search. // of android so I had to go with the wildcard search.
intent.setType("*/*"); intent.setType("*/*");
title = GET_All; title = GET_All;
} }
intent.setAction(Intent.ACTION_GET_CONTENT); intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent, this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
@ -217,9 +217,9 @@ public class CameraLauncher extends Plugin {
/** /**
* Scales the bitmap according to the requested size. * Scales the bitmap according to the requested size.
* *
* @param bitmap The bitmap to scale. * @param bitmap The bitmap to scale.
* @return Bitmap A new Bitmap object of the same bitmap after scaling. * @return Bitmap A new Bitmap object of the same bitmap after scaling.
*/ */
public Bitmap scaleBitmap(Bitmap bitmap) { public Bitmap scaleBitmap(Bitmap bitmap) {
int newWidth = this.targetWidth; int newWidth = this.targetWidth;
@ -255,27 +255,27 @@ public class CameraLauncher extends Plugin {
newWidth = (newHeight * origWidth) / origHeight; newWidth = (newHeight * origWidth) / origHeight;
} }
} }
Bitmap retval = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); Bitmap retval = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
bitmap.recycle(); bitmap.recycle();
return retval; return retval;
} }
/** /**
* Called when the camera view exits. * Called when the camera view exits.
* *
* @param requestCode The request code originally supplied to startActivityForResult(), * @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from. * allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult(). * @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/ */
public void onActivityResult(int requestCode, int resultCode, Intent intent) { public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code // Get src and dest types from request code
int srcType = (requestCode/16) - 1; int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1; int destType = (requestCode % 16) - 1;
int rotate = 0; int rotate = 0;
// Create an ExifHelper to save the exif data that is lost during compression // Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper(); ExifHelper exif = new ExifHelper();
try { try {
@ -303,7 +303,7 @@ public class CameraLauncher extends Plugin {
} }
bitmap = scaleBitmap(bitmap); bitmap = scaleBitmap(bitmap);
// If sending base64 image back // If sending base64 image back
if (destType == DATA_URL) { if (destType == DATA_URL) {
this.processPicture(bitmap); this.processPicture(bitmap);
@ -324,7 +324,7 @@ public class CameraLauncher extends Plugin {
try { try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) { } catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage."); LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found."); this.failPicture("Error capturing image - no media storage found.");
return; return;
} }
@ -334,7 +334,7 @@ public class CameraLauncher extends Plugin {
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close(); os.close();
// Restore exif data to file // Restore exif data to file
if (this.encodingType == JPEG) { if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
@ -347,12 +347,12 @@ public class CameraLauncher extends Plugin {
bitmap.recycle(); bitmap.recycle();
bitmap = null; bitmap = null;
System.gc(); System.gc();
checkForDuplicateImage(FILE_URI); checkForDuplicateImage(FILE_URI);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
this.failPicture("Error capturing image."); this.failPicture("Error capturing image.");
} }
} }
// If cancelled // If cancelled
@ -365,17 +365,17 @@ public class CameraLauncher extends Plugin {
this.failPicture("Did not complete!"); this.failPicture("Did not complete!");
} }
} }
// If retrieving photo from library // If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData(); Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver(); android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI // If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data // and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) { if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} }
else { else {
// If sending base64 image back // If sending base64 image back
@ -383,8 +383,8 @@ public class CameraLauncher extends Plugin {
try { try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
String[] cols = { MediaStore.Images.Media.ORIENTATION }; String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = this.ctx.getContentResolver().query(intent.getData(), Cursor cursor = this.ctx.getContentResolver().query(intent.getData(),
cols, cols,
null, null, null); null, null, null);
if (cursor != null) { if (cursor != null) {
cursor.moveToPosition(0); cursor.moveToPosition(0);
@ -406,7 +406,7 @@ public class CameraLauncher extends Plugin {
this.failPicture("Error retrieving image."); this.failPicture("Error retrieving image.");
} }
} }
// If sending filename back // If sending filename back
else if (destType == FILE_URI) { else if (destType == FILE_URI) {
// Do we need to scale the returned file // Do we need to scale the returned file
@ -414,12 +414,12 @@ public class CameraLauncher extends Plugin {
try { try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap); bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/resize.jpg"; String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName); OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close(); os.close();
// Restore exif data to file // Restore exif data to file
if (this.encodingType == JPEG) { if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
@ -428,8 +428,8 @@ public class CameraLauncher extends Plugin {
bitmap.recycle(); bitmap.recycle();
bitmap = null; bitmap = null;
// The resized image is cached by the app in order to get around this and not have to delete you // The resized image is cached by the app in order to get around this and not have to delete you
// application cache I'm adding the current system time to the end of the file url. // application cache I'm adding the current system time to the end of the file url.
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, ("file://" + fileName + "?" + System.currentTimeMillis())), this.callbackId);
System.gc(); System.gc();
@ -439,23 +439,23 @@ public class CameraLauncher extends Plugin {
} }
} }
else { else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} }
} }
} }
} }
else if (resultCode == Activity.RESULT_CANCELED) { else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled."); this.failPicture("Selection cancelled.");
} }
else { else {
this.failPicture("Selection did not complete!"); this.failPicture("Selection did not complete!");
} }
} }
} }
/** /**
* Creates a cursor that can be used to determine how many images we have. * Creates a cursor that can be used to determine how many images we have.
* *
* @return a cursor * @return a cursor
*/ */
private Cursor queryImgDB() { private Cursor queryImgDB() {
@ -466,27 +466,27 @@ public class CameraLauncher extends Plugin {
null, null,
null); null);
} }
/** /**
* Used to find out if we are in a situation where the Camera Intent adds to images * Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store. If we are using a FILE_URI and the number of images in the DB * to the content store. If we are using a FILE_URI and the number of images in the DB
* increases by 2 we have a duplicate, when using a DATA_URL the number is 1. * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
* *
* @param type FILE_URI or DATA_URL * @param type FILE_URI or DATA_URL
*/ */
private void checkForDuplicateImage(int type) { private void checkForDuplicateImage(int type) {
int diff = 1; int diff = 1;
Cursor cursor = queryImgDB(); Cursor cursor = queryImgDB();
int currentNumOfImages = cursor.getCount(); int currentNumOfImages = cursor.getCount();
if (type == FILE_URI) { if (type == FILE_URI) {
diff = 2; diff = 2;
} }
// delete the duplicate file if the difference is 2 for file URI or 1 for Data URL // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
if ((currentNumOfImages - numPics) == diff) { if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast(); cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1; int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id); Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
this.ctx.getContentResolver().delete(uri, null, null); this.ctx.getContentResolver().delete(uri, null, null);
} }
@ -497,7 +497,7 @@ public class CameraLauncher extends Plugin {
* *
* @param bitmap * @param bitmap
*/ */
public void processPicture(Bitmap bitmap) { public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try { try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) { if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
@ -508,17 +508,17 @@ public class CameraLauncher extends Plugin {
js_out = null; js_out = null;
output = null; output = null;
code = null; code = null;
} }
} }
catch(Exception e) { catch(Exception e) {
this.failPicture("Error compressing image."); this.failPicture("Error compressing image.");
} }
jpeg_data = null; jpeg_data = null;
} }
/** /**
* Send error message to JavaScript. * Send error message to JavaScript.
* *
* @param err * @param err
*/ */
public void failPicture(String err) { public void failPicture(String err) {

View File

@ -45,23 +45,23 @@ public class Capture extends Plugin {
private static final String VIDEO_MP4 = "video/mp4"; private static final String VIDEO_MP4 = "video/mp4";
private static final String AUDIO_3GPP = "audio/3gpp"; private static final String AUDIO_3GPP = "audio/3gpp";
private static final String IMAGE_JPEG = "image/jpeg"; private static final String IMAGE_JPEG = "image/jpeg";
private static final int CAPTURE_AUDIO = 0; // Constant for capture audio private static final int CAPTURE_AUDIO = 0; // Constant for capture audio
private static final int CAPTURE_IMAGE = 1; // Constant for capture image private static final int CAPTURE_IMAGE = 1; // Constant for capture image
private static final int CAPTURE_VIDEO = 2; // Constant for capture video private static final int CAPTURE_VIDEO = 2; // Constant for capture video
private static final String LOG_TAG = "Capture"; private static final String LOG_TAG = "Capture";
private static final int CAPTURE_INTERNAL_ERR = 0; private static final int CAPTURE_INTERNAL_ERR = 0;
private static final int CAPTURE_APPLICATION_BUSY = 1; private static final int CAPTURE_APPLICATION_BUSY = 1;
private static final int CAPTURE_INVALID_ARGUMENT = 2; private static final int CAPTURE_INVALID_ARGUMENT = 2;
private static final int CAPTURE_NO_MEDIA_FILES = 3; private static final int CAPTURE_NO_MEDIA_FILES = 3;
private static final int CAPTURE_NOT_SUPPORTED = 20; private static final int CAPTURE_NOT_SUPPORTED = 20;
private String callbackId; // The ID of the callback to be invoked with our result private String callbackId; // The ID of the callback to be invoked with our result
private long limit; // the number of pics/vids/clips to take private long limit; // the number of pics/vids/clips to take
private double duration; // optional duration parameter for video recording private double duration; // optional duration parameter for video recording
private JSONArray results; // The array of results to be returned to the user private JSONArray results; // The array of results to be returned to the user
private Uri imageUri; // Uri of captured image private Uri imageUri; // Uri of captured image
@Override @Override
public PluginResult execute(String action, JSONArray args, String callbackId) { public PluginResult execute(String action, JSONArray args, String callbackId) {
@ -69,7 +69,7 @@ public class Capture extends Plugin {
this.limit = 1; this.limit = 1;
this.duration = 0.0f; this.duration = 0.0f;
this.results = new JSONArray(); this.results = new JSONArray();
JSONObject options = args.optJSONObject(0); JSONObject options = args.optJSONObject(0);
if (options != null) { if (options != null) {
limit = options.optLong("limit", 1); limit = options.optLong("limit", 1);
@ -91,9 +91,9 @@ public class Capture extends Plugin {
this.captureImage(); this.captureImage();
} }
else if (action.equals("captureVideo")) { else if (action.equals("captureVideo")) {
this.captureVideo(duration); this.captureVideo(duration);
} }
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true); r.setKeepCallback(true);
return r; return r;
@ -101,7 +101,7 @@ public class Capture extends Plugin {
/** /**
* Provides the media data file data depending on it's mime type * Provides the media data file data depending on it's mime type
* *
* @param filePath path to the file * @param filePath path to the file
* @param mimeType of the file * @param mimeType of the file
* @return a MediaFileData object * @return a MediaFileData object
@ -122,7 +122,7 @@ public class Capture extends Plugin {
mimeType = FileUtils.getMimeType(filePath); mimeType = FileUtils.getMimeType(filePath);
} }
Log.d(LOG_TAG, "Mime type = " + mimeType); Log.d(LOG_TAG, "Mime type = " + mimeType);
if (mimeType.equals(IMAGE_JPEG) || filePath.endsWith(".jpg")) { if (mimeType.equals(IMAGE_JPEG) || filePath.endsWith(".jpg")) {
obj = getImageData(filePath, obj); obj = getImageData(filePath, obj);
} }
@ -141,7 +141,7 @@ public class Capture extends Plugin {
/** /**
* Get the Image specific attributes * Get the Image specific attributes
* *
* @param filePath path to the file * @param filePath path to the file
* @param obj represents the Media File Data * @param obj represents the Media File Data
* @return a JSONObject that represents the Media File Data * @return a JSONObject that represents the Media File Data
@ -157,7 +157,7 @@ public class Capture extends Plugin {
/** /**
* Get the Image specific attributes * Get the Image specific attributes
* *
* @param filePath path to the file * @param filePath path to the file
* @param obj represents the Media File Data * @param obj represents the Media File Data
* @param video if true get video attributes as well * @param video if true get video attributes as well
@ -177,7 +177,7 @@ public class Capture extends Plugin {
} }
catch (IOException e) { catch (IOException e) {
Log.d(LOG_TAG, "Error: loading video file"); Log.d(LOG_TAG, "Error: loading video file");
} }
return obj; return obj;
} }
@ -211,18 +211,18 @@ public class Capture extends Plugin {
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE); Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
// Introduced in API 8 // Introduced in API 8
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration); //intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration);
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO); this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO);
} }
/** /**
* Called when the video view exits. * Called when the video view exits.
* *
* @param requestCode The request code originally supplied to startActivityForResult(), * @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from. * allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult(). * @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
* @throws JSONException * @throws JSONException
*/ */
public void onActivityResult(int requestCode, int resultCode, Intent intent) { public void onActivityResult(int requestCode, int resultCode, Intent intent) {
@ -252,7 +252,7 @@ public class Capture extends Plugin {
ExifHelper exif = new ExifHelper(); ExifHelper exif = new ExifHelper();
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Capture.jpg"); exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Capture.jpg");
exif.readExifData(); exif.readExifData();
// Read in bitmap of captured image // Read in bitmap of captured image
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri); Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
@ -268,7 +268,7 @@ public class Capture extends Plugin {
try { try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) { } catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage."); LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found.")); this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
return; return;
} }
@ -282,14 +282,14 @@ public class Capture extends Plugin {
bitmap.recycle(); bitmap.recycle();
bitmap = null; bitmap = null;
System.gc(); System.gc();
// Restore exif data to file // Restore exif data to file
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx)); exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData(); exif.writeExifData();
// Add image to results // Add image to results
results.put(createMediaFile(uri)); results.put(createMediaFile(uri));
if (results.length() >= limit) { if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image // Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId);
@ -320,7 +320,7 @@ public class Capture extends Plugin {
else if (resultCode == Activity.RESULT_CANCELED) { else if (resultCode == Activity.RESULT_CANCELED) {
// If we have partial results send them back to the user // If we have partial results send them back to the user
if (results.length() > 0) { if (results.length() > 0) {
this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId);
} }
// user canceled the action // user canceled the action
else { else {
@ -331,7 +331,7 @@ public class Capture extends Plugin {
else { else {
// If we have partial results send them back to the user // If we have partial results send them back to the user
if (results.length() > 0) { if (results.length() > 0) {
this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId); this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId);
} }
// something bad happened // something bad happened
else { else {
@ -342,43 +342,43 @@ public class Capture extends Plugin {
/** /**
* Creates a JSONObject that represents a File from the Uri * Creates a JSONObject that represents a File from the Uri
* *
* @param data the Uri of the audio/image/video * @param data the Uri of the audio/image/video
* @return a JSONObject that represents a File * @return a JSONObject that represents a File
* @throws IOException * @throws IOException
*/ */
private JSONObject createMediaFile(Uri data){ private JSONObject createMediaFile(Uri data){
File fp = new File(FileUtils.getRealPathFromURI(data, this.ctx)); File fp = new File(FileUtils.getRealPathFromURI(data, this.ctx));
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
// File properties // File properties
obj.put("name", fp.getName()); obj.put("name", fp.getName());
obj.put("fullPath", "file://" + fp.getAbsolutePath()); obj.put("fullPath", "file://" + fp.getAbsolutePath());
// Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
// are reported as video/3gpp. I'm doing this hacky check of the URI to see if it // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
// is stored in the audio or video content store. // is stored in the audio or video content store.
if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) { if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
if (data.toString().contains("/audio/")) { if (data.toString().contains("/audio/")) {
obj.put("type", AUDIO_3GPP); obj.put("type", AUDIO_3GPP);
} else { } else {
obj.put("type", VIDEO_3GPP); obj.put("type", VIDEO_3GPP);
} }
} else { } else {
obj.put("type", FileUtils.getMimeType(fp.getAbsolutePath())); obj.put("type", FileUtils.getMimeType(fp.getAbsolutePath()));
} }
obj.put("lastModifiedDate", fp.lastModified()); obj.put("lastModifiedDate", fp.lastModified());
obj.put("size", fp.length()); obj.put("size", fp.length());
} catch (JSONException e) { } catch (JSONException e) {
// this will never happen // this will never happen
e.printStackTrace(); e.printStackTrace();
} }
return obj; return obj;
} }
private JSONObject createErrorObject(int code, String message) { private JSONObject createErrorObject(int code, String message) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
@ -392,7 +392,7 @@ public class Capture extends Plugin {
/** /**
* Send error message to JavaScript. * Send error message to JavaScript.
* *
* @param err * @param err
*/ */
public void fail(JSONObject err) { public void fail(JSONObject err) {

View File

@ -43,18 +43,18 @@ public class CompassListener extends Plugin implements SensorEventListener {
public static int STARTING = 1; public static int STARTING = 1;
public static int RUNNING = 2; public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3; public static int ERROR_FAILED_TO_START = 3;
public long TIMEOUT = 30000; // Timeout in msec to shut off listener public long TIMEOUT = 30000; // Timeout in msec to shut off listener
int status; // status of listener int status; // status of listener
float heading; // most recent heading value float heading; // most recent heading value
long timeStamp; // time of most recent value long timeStamp; // time of most recent value
long lastAccessTime; // time the value was last retrieved long lastAccessTime; // time the value was last retrieved
int accuracy; // accuracy of the sensor int accuracy; // accuracy of the sensor
private SensorManager sensorManager;// Sensor manager private SensorManager sensorManager;// Sensor manager
Sensor mSensor; // Compass sensor returned by sensor manager Sensor mSensor; // Compass sensor returned by sensor manager
/** /**
* Constructor. * Constructor.
*/ */
@ -67,7 +67,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
/** /**
* 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) {
@ -77,7 +77,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
/** /**
* 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.
@ -85,8 +85,8 @@ public class CompassListener extends Plugin implements SensorEventListener {
*/ */
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("start")) { if (action.equals("start")) {
this.start(); this.start();
@ -116,7 +116,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
} }
} }
if (timeout == 0) { if (timeout == 0) {
return new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START); return new PluginResult(PluginResult.Status.IO_EXCEPTION, CompassListener.ERROR_FAILED_TO_START);
} }
} }
return new PluginResult(status, getCompassHeading()); return new PluginResult(status, getCompassHeading());
@ -140,7 +140,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
/** /**
* 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
*/ */
@ -159,7 +159,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
} }
return false; return false;
} }
/** /**
* Called when listener is to be shut down and object is being destroyed. * Called when listener is to be shut down and object is being destroyed.
*/ */
@ -173,11 +173,11 @@ public class CompassListener extends Plugin implements SensorEventListener {
/** /**
* Start listening for compass sensor. * Start listening for compass sensor.
* *
* @return status of listener * @return status of listener
*/ */
public int start() { public int start() {
// If already starting or running, then just return // If already starting or running, then just return
if ((this.status == CompassListener.RUNNING) || (this.status == CompassListener.STARTING)) { if ((this.status == CompassListener.RUNNING) || (this.status == CompassListener.STARTING)) {
return this.status; return this.status;
@ -198,10 +198,10 @@ public class CompassListener extends Plugin implements SensorEventListener {
else { else {
this.setStatus(CompassListener.ERROR_FAILED_TO_START); this.setStatus(CompassListener.ERROR_FAILED_TO_START);
} }
return this.status; return this.status;
} }
/** /**
* Stop listening to compass sensor. * Stop listening to compass sensor.
*/ */
@ -211,15 +211,15 @@ public class CompassListener extends Plugin implements SensorEventListener {
} }
this.setStatus(CompassListener.STOPPED); this.setStatus(CompassListener.STOPPED);
} }
public void onAccuracyChanged(Sensor sensor, int accuracy) { public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/** /**
* Sensor listener event. * Sensor listener event.
* *
* @param SensorEvent event * @param SensorEvent event
*/ */
public void onSensorChanged(SensorEvent event) { public void onSensorChanged(SensorEvent event) {
@ -237,38 +237,38 @@ public class CompassListener extends Plugin implements SensorEventListener {
this.stop(); this.stop();
} }
} }
/** /**
* Get status of compass sensor. * Get status of compass sensor.
* *
* @return status * @return status
*/ */
public int getStatus() { public int getStatus() {
return this.status; return this.status;
} }
/** /**
* Get the most recent compass heading. * Get the most recent compass heading.
* *
* @return heading * @return heading
*/ */
public float getHeading() { public float getHeading() {
this.lastAccessTime = System.currentTimeMillis(); this.lastAccessTime = System.currentTimeMillis();
return this.heading; return this.heading;
} }
/** /**
* Set the timeout to turn off compass sensor if getHeading() hasn't been called. * Set the timeout to turn off compass sensor if getHeading() hasn't been called.
* *
* @param timeout Timeout in msec. * @param timeout Timeout in msec.
*/ */
public void setTimeout(long timeout) { public void setTimeout(long timeout) {
this.TIMEOUT = timeout; this.TIMEOUT = timeout;
} }
/** /**
* Get the timeout to turn off compass sensor if getHeading() hasn't been called. * Get the timeout to turn off compass sensor if getHeading() hasn't been called.
* *
* @return timeout in msec * @return timeout in msec
*/ */
public long getTimeout() { public long getTimeout() {
@ -285,23 +285,23 @@ public class CompassListener extends Plugin implements SensorEventListener {
/** /**
* Create the CompassHeading JSON object to be returned to JavaScript * Create the CompassHeading JSON object to be returned to JavaScript
* *
* @return a compass heading * @return a compass heading
*/ */
private JSONObject getCompassHeading() { private JSONObject getCompassHeading() {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
obj.put("magneticHeading", this.getHeading()); obj.put("magneticHeading", this.getHeading());
obj.put("trueHeading", this.getHeading()); obj.put("trueHeading", this.getHeading());
// Since the magnetic and true heading are always the same our and accuracy // Since the magnetic and true heading are always the same our and accuracy
// is defined as the difference between true and magnetic always return zero // is defined as the difference between true and magnetic always return zero
obj.put("headingAccuracy", 0); obj.put("headingAccuracy", 0);
obj.put("timestamp", this.timeStamp); obj.put("timestamp", this.timeStamp);
} catch (JSONException e) { } catch (JSONException e) {
// Should never happen // Should never happen
} }
return obj; return obj;
} }

View File

@ -34,15 +34,15 @@ import org.json.JSONObject;
* Eclair or higher, we want to use {@link ContactAccessorSdk5}. * Eclair or higher, we want to use {@link ContactAccessorSdk5}.
*/ */
public abstract class ContactAccessor { public abstract class ContactAccessor {
protected final String LOG_TAG = "ContactsAccessor"; protected final String LOG_TAG = "ContactsAccessor";
protected Context mApp; protected Context mApp;
protected WebView mView; protected WebView mView;
/** /**
* Check to see if the data associated with the key is required to * Check to see if the data associated with the key is required to
* be populated in the Contact object. * be populated in the Contact object.
* @param key * @param key
* @param map created by running buildPopulationSet. * @param map created by running buildPopulationSet.
* @return true if the key data is required * @return true if the key data is required
*/ */
@ -50,7 +50,7 @@ public abstract class ContactAccessor {
Boolean retVal = map.get(key); Boolean retVal = map.get(key);
return (retVal == null) ? false : retVal.booleanValue(); return (retVal == null) ? false : retVal.booleanValue();
} }
/** /**
* Create a hash map of what data needs to be populated in the Contact object * Create a hash map of what data needs to be populated in the Contact object
* @param fields the list of fields to populate * @param fields the list of fields to populate
@ -58,7 +58,7 @@ public abstract class ContactAccessor {
*/ */
protected HashMap<String,Boolean> buildPopulationSet(JSONArray fields) { protected HashMap<String,Boolean> buildPopulationSet(JSONArray fields) {
HashMap<String,Boolean> map = new HashMap<String,Boolean>(); HashMap<String,Boolean> map = new HashMap<String,Boolean>();
String key; String key;
try { try {
if (fields.length() == 1 && fields.getString(0).equals("*")) { if (fields.length() == 1 && fields.getString(0).equals("*")) {
@ -75,7 +75,7 @@ public abstract class ContactAccessor {
map.put("urls", true); map.put("urls", true);
map.put("photos", true); map.put("photos", true);
map.put("categories", true); map.put("categories", true);
} }
else { else {
for (int i=0; i<fields.length(); i++) { for (int i=0; i<fields.length(); i++) {
key = fields.getString(i); key = fields.getString(i);
@ -127,12 +127,12 @@ public abstract class ContactAccessor {
} }
return map; return map;
} }
/** /**
* Convenience method to get a string from a JSON object. Saves a * Convenience method to get a string from a JSON object. Saves a
* lot of try/catch writing. * lot of try/catch writing.
* If the property is not found in the object null will be returned. * If the property is not found in the object null will be returned.
* *
* @param obj contact object to search * @param obj contact object to search
* @param property to be looked up * @param property to be looked up
* @return The value of the property * @return The value of the property
@ -150,7 +150,7 @@ public abstract class ContactAccessor {
} }
catch (JSONException e) { catch (JSONException e) {
Log.d(LOG_TAG, "Could not get = " + e.getMessage()); Log.d(LOG_TAG, "Could not get = " + e.getMessage());
} }
return value; return value;
} }
@ -167,7 +167,7 @@ public abstract class ContactAccessor {
/** /**
* Handles searching through SDK-specific contacts API. * Handles searching through SDK-specific contacts API.
* @throws JSONException * @throws JSONException
*/ */
public abstract JSONObject getContactById(String id) throws JSONException; public abstract JSONObject getContactById(String id) throws JSONException;
@ -175,9 +175,9 @@ public abstract class ContactAccessor {
* Handles removing a contact from the database. * Handles removing a contact from the database.
*/ */
public abstract boolean remove(String id); public abstract boolean remove(String id);
/** /**
* A class that represents the where clause to be used in the database query * A class that represents the where clause to be used in the database query
*/ */
class WhereOptions { class WhereOptions {
private String where; private String where;

File diff suppressed because it is too large Load Diff

View File

@ -46,7 +46,7 @@ public class ContactManager extends Plugin {
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args 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.
@ -57,7 +57,7 @@ public class ContactManager extends Plugin {
String result = ""; String result = "";
/** /**
* Check to see if we are on an Android 1.X device. If we are return an error as we * Check to see if we are on an Android 1.X device. If we are return an error as we
* do not support this as of Cordova 1.0. * do not support this as of Cordova 1.0.
*/ */
if (android.os.Build.VERSION.RELEASE.startsWith("1.")) { if (android.os.Build.VERSION.RELEASE.startsWith("1.")) {

View File

@ -40,15 +40,15 @@ import android.widget.EditText;
* This class is the WebChromeClient that implements callbacks for our web view. * This class is the WebChromeClient that implements callbacks for our web view.
*/ */
public class CordovaChromeClient extends WebChromeClient { public class CordovaChromeClient extends WebChromeClient {
private String TAG = "CordovaLog"; private String TAG = "CordovaLog";
private long MAX_QUOTA = 100 * 1024 * 1024; private long MAX_QUOTA = 100 * 1024 * 1024;
private DroidGap ctx; private DroidGap ctx;
/** /**
* Constructor. * Constructor.
* *
* @param ctx * @param ctx
*/ */
public CordovaChromeClient(Context ctx) { public CordovaChromeClient(Context ctx) {
@ -57,7 +57,7 @@ public class CordovaChromeClient extends WebChromeClient {
/** /**
* Tell the client to display a javascript alert dialog. * Tell the client to display a javascript alert dialog.
* *
* @param view * @param view
* @param url * @param url
* @param message * @param message
@ -97,11 +97,11 @@ public class CordovaChromeClient extends WebChromeClient {
dlg.create(); dlg.create();
dlg.show(); dlg.show();
return true; return true;
} }
/** /**
* Tell the client to display a confirm dialog to the user. * Tell the client to display a confirm dialog to the user.
* *
* @param view * @param view
* @param url * @param url
* @param message * @param message
@ -113,13 +113,13 @@ public class CordovaChromeClient extends WebChromeClient {
dlg.setMessage(message); dlg.setMessage(message);
dlg.setTitle("Confirm"); dlg.setTitle("Confirm");
dlg.setCancelable(true); dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok, dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
result.confirm(); result.confirm();
} }
}); });
dlg.setNegativeButton(android.R.string.cancel, dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
result.cancel(); result.cancel();
@ -149,13 +149,13 @@ public class CordovaChromeClient extends WebChromeClient {
} }
/** /**
* Tell the client to display a prompt dialog to the user. * Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will * If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method. * handle the prompt dialog and call the appropriate JsPromptResult method.
* *
* Since we are hacking prompts for our own purposes, we should not be using them for * Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead! * this purpose, perhaps we should hack console.log to do this instead!
* *
* @param view * @param view
* @param url * @param url
* @param message * @param message
@ -164,15 +164,15 @@ public class CordovaChromeClient extends WebChromeClient {
*/ */
@Override @Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially // Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe. // loaded in webview and not another loaded in an iframe.
boolean reqOk = false; boolean reqOk = false;
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || ctx.isUrlWhiteListed(url)) { if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || ctx.isUrlWhiteListed(url)) {
reqOk = true; reqOk = true;
} }
// Calling PluginManager.exec() to call a native service using // Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array; JSONArray array;
@ -188,13 +188,13 @@ public class CordovaChromeClient extends WebChromeClient {
e.printStackTrace(); e.printStackTrace();
} }
} }
// Polling for JavaScript messages // Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = ctx.callbackServer.getJavascript(); String r = ctx.callbackServer.getJavascript();
result.confirm(r); result.confirm(r);
} }
// Calling into CallbackServer // Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = ""; String r = "";
@ -212,7 +212,7 @@ public class CordovaChromeClient extends WebChromeClient {
} }
result.confirm(r); result.confirm(r);
} }
// Cordova JS has initialized, so show webview // Cordova JS has initialized, so show webview
// (This solves white flash seen when rendering HTML) // (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
@ -235,14 +235,14 @@ public class CordovaChromeClient extends WebChromeClient {
} }
dlg.setView(input); dlg.setView(input);
dlg.setCancelable(false); dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok, dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString(); String usertext = input.getText().toString();
res.confirm(usertext); res.confirm(usertext);
} }
}); });
dlg.setNegativeButton(android.R.string.cancel, dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
res.cancel(); res.cancel();
@ -253,7 +253,7 @@ public class CordovaChromeClient extends WebChromeClient {
} }
return true; return true;
} }
/** /**
* Handle database quota exceeded notification. * Handle database quota exceeded notification.
* *
@ -288,14 +288,14 @@ public class CordovaChromeClient extends WebChromeClient {
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
@Override @Override
public void onConsoleMessage(String message, int lineNumber, String sourceID) public void onConsoleMessage(String message, int lineNumber, String sourceID)
{ {
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID); super.onConsoleMessage(message, lineNumber, sourceID);
} }
@Override @Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{ {
if(consoleMessage.message() != null) if(consoleMessage.message() != null)
LOG.d(TAG, consoleMessage.message()); LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage); return super.onConsoleMessage(consoleMessage);
@ -303,8 +303,8 @@ public class CordovaChromeClient extends WebChromeClient {
@Override @Override
/** /**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
* *
* @param origin * @param origin
* @param callback * @param callback
*/ */

View File

@ -38,161 +38,161 @@ public class CordovaLocationListener implements LocationListener {
protected LocationManager locationManager; protected LocationManager locationManager;
private GeoBroker owner; private GeoBroker owner;
protected boolean running = false; protected boolean running = false;
public HashMap<String, String> watches = new HashMap<String, String>(); public HashMap<String, String> watches = new HashMap<String, String>();
private List<String> callbacks = new ArrayList<String>(); private List<String> callbacks = new ArrayList<String>();
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();
Iterator it = this.watches.entrySet().iterator(); Iterator it = this.watches.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next(); Map.Entry pairs = (Map.Entry)it.next();
this.owner.fail(code, message, (String)pairs.getValue()); this.owner.fail(code, message, (String)pairs.getValue());
} }
} }
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();
Iterator it = this.watches.entrySet().iterator(); Iterator it = this.watches.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next(); Map.Entry pairs = (Map.Entry)it.next();
this.owner.win(loc, (String)pairs.getValue()); this.owner.win(loc, (String)pairs.getValue());
} }
} }
/** /**
* Location Listener Methods * Location Listener Methods
*/ */
/**
* Called when the provider is disabled by the user.
*
* @param provider
*/
public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider '" + provider + "' disabled.");
this.fail(POSITION_UNAVAILABLE, "GPS provider disabled.");
}
/** /**
* Called when the provider is enabled by the user. * Called when the provider is disabled by the user.
* *
* @param provider * @param provider
*/ */
public void onProviderEnabled(String provider) { public void onProviderDisabled(String provider) {
Log.d(TAG, "Location provider "+ provider + " has been enabled"); Log.d(TAG, "Location provider '" + provider + "' disabled.");
} this.fail(POSITION_UNAVAILABLE, "GPS provider disabled.");
}
/** /**
* Called when the provider status changes. This method is called when a * Called when the provider is enabled by the user.
* provider is unable to fetch a location or if the provider has recently *
* become available after a period of unavailability. * @param provider
* */
* @param provider public void onProviderEnabled(String provider) {
* @param status Log.d(TAG, "Location provider "+ provider + " has been enabled");
* @param extras }
*/
public void onStatusChanged(String provider, int status, Bundle extras) { /**
Log.d(TAG, "The status of the provider " + provider + " has changed"); * Called when the provider status changes. This method is called when a
if (status == 0) { * provider is unable to fetch a location or if the provider has recently
Log.d(TAG, provider + " is OUT OF SERVICE"); * become available after a period of unavailability.
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Provider " + provider + " is out of service."); *
} * @param provider
else if (status == 1) { * @param status
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE"); * @param extras
} */
else { public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, provider + " is AVAILABLE"); Log.d(TAG, "The status of the provider " + provider + " has changed");
} if (status == 0) {
} Log.d(TAG, provider + " is OUT OF SERVICE");
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Provider " + provider + " is out of service.");
}
else if (status == 1) {
Log.d(TAG, provider + " is TEMPORARILY_UNAVAILABLE");
}
else {
Log.d(TAG, provider + " is AVAILABLE");
}
}
/**
* Called when the location has changed.
*
* @param location
*/
public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!");
this.win(location);
}
// PUBLIC
public int size() {
return this.watches.size() + this.callbacks.size();
}
public void addWatch(String timerId, String callbackId) {
this.watches.put(timerId, callbackId);
if (this.size() == 1) {
this.start();
}
}
public void addCallback(String callbackId) {
this.callbacks.add(callbackId);
if (this.size() == 1) {
this.start();
}
}
public void clearWatch(String timerId) {
if (this.watches.containsKey(timerId)) {
this.watches.remove(timerId);
}
if (this.size() == 0) {
this.stop();
}
}
/**
* Called when the location has changed.
*
* @param location
*/
public void onLocationChanged(Location location) {
Log.d(TAG, "The location has been updated!");
this.win(location);
}
// PUBLIC
public int size() {
return this.watches.size() + this.callbacks.size();
}
public void addWatch(String timerId, String callbackId) {
this.watches.put(timerId, callbackId);
if (this.size() == 1) {
this.start();
}
}
public void addCallback(String callbackId) {
this.callbacks.add(callbackId);
if (this.size() == 1) {
this.start();
}
}
public void clearWatch(String timerId) {
if (this.watches.containsKey(timerId)) {
this.watches.remove(timerId);
}
if (this.size() == 0) {
this.stop();
}
}
/** /**
* Destroy listener. * Destroy listener.
*/ */
public void destroy() { public void destroy() {
this.stop(); this.stop();
} }
// LOCAL
/**
* Start requesting location updates.
*
* @param interval
*/
protected void start() {
if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true;
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
} else {
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Network provider is not available.");
}
}
}
/** // LOCAL
* Stop receiving location updates.
*/ /**
private void stop() { * Start requesting location updates.
if (this.running) { *
this.locationManager.removeUpdates(this); * @param interval
this.running = false; */
} protected void start() {
} if (!this.running) {
if (this.locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.running = true;
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 10, this);
} else {
this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "Network provider is not available.");
}
}
}
/**
* Stop receiving location updates.
*/
private void stop() {
if (this.running) {
this.locationManager.removeUpdates(this);
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;
@ -38,35 +37,35 @@ import android.webkit.WebViewClient;
* This class is the WebViewClient that implements callbacks for our web view. * This class is the WebViewClient that implements callbacks for our web view.
*/ */
public class CordovaWebViewClient extends WebViewClient { public class CordovaWebViewClient extends WebViewClient {
private static final String TAG = "Cordova"; private static final String TAG = "Cordova";
DroidGap ctx; DroidGap ctx;
private boolean doClearHistory = false; private boolean doClearHistory = false;
/** /**
* Constructor. * Constructor.
* *
* @param ctx * @param ctx
*/ */
public CordovaWebViewClient(DroidGap ctx) { public CordovaWebViewClient(DroidGap ctx) {
this.ctx = ctx; this.ctx = ctx;
} }
/** /**
* Give the host application a chance to take over the control when a new url * Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView. * is about to be loaded in the current WebView.
* *
* @param view The WebView that is initiating the callback. * @param view The WebView that is initiating the callback.
* @param url The url to be loaded. * @param url The url to be loaded.
* @return true to override, false for default behavior * @return true to override, false for default behavior
*/ */
@Override @Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves // First give any plugins the chance to handle the url themselves
if ((this.ctx.pluginManager != null) && this.ctx.pluginManager.onOverrideUrlLoading(url)) { if ((this.ctx.pluginManager != null) && this.ctx.pluginManager.onOverrideUrlLoading(url)) {
} }
// If dialing phone (tel:5551212) // If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) { else if (url.startsWith(WebView.SCHEME_TEL)) {
try { try {
@ -154,11 +153,11 @@ public class CordovaWebViewClient extends WebViewClient {
} }
return true; return true;
} }
/** /**
* On received http auth request. * On received http auth request.
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
* *
* @param view * @param view
* the view * the view
* @param handler * @param handler
@ -171,27 +170,27 @@ public class CordovaWebViewClient extends WebViewClient {
@Override @Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) { String realm) {
// get the authentication token // get the authentication token
AuthenticationToken token = ctx.getAuthenticationToken(host,realm); AuthenticationToken token = ctx.getAuthenticationToken(host,realm);
if(token != null) { if(token != null) {
handler.proceed(token.getUserName(), token.getPassword()); handler.proceed(token.getUserName(), token.getPassword());
} }
} }
@Override @Override
public void onPageStarted(WebView view, String url, Bitmap favicon) { public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything. // Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager. // So we can reinit() native side CallbackServer & PluginManager.
view.clearHistory(); view.clearHistory();
this.doClearHistory = true; this.doClearHistory = true;
} }
/** /**
* Notify the host application that a page has finished loading. * Notify the host application that a page has finished loading.
* *
* @param view The webview initiating the callback. * @param view The webview initiating the callback.
* @param url The url of the page. * @param url The url of the page.
*/ */
@ -200,8 +199,8 @@ public class CordovaWebViewClient extends WebViewClient {
super.onPageFinished(view, url); super.onPageFinished(view, url);
/** /**
* Because of a timing issue we need to clear this history in onPageFinished as well as * Because of a timing issue we need to clear this history in onPageFinished as well as
* onPageStarted. However we only want to do this if the doClearHistory boolean is set to * onPageStarted. However we only want to do this if the doClearHistory boolean is set to
* true. You see when you load a url with a # in it which is common in jQuery applications * true. You see when you load a url with a # in it which is common in jQuery applications
* onPageStared is not called. Clearing the history at that point would break jQuery apps. * onPageStared is not called. Clearing the history at that point would break jQuery apps.
*/ */
@ -252,15 +251,15 @@ public class CordovaWebViewClient extends WebViewClient {
this.ctx.endActivity(); this.ctx.endActivity();
} }
} }
/** /**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants. * The errorCode parameter corresponds to one of the ERROR_* constants.
* *
* @param view The WebView that is initiating the callback. * @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value. * @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error. * @param description A String describing the error.
* @param failingUrl The url that failed to load. * @param failingUrl The url that failed to load.
*/ */
@Override @Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
@ -275,9 +274,9 @@ public class CordovaWebViewClient extends WebViewClient {
// Handle error // Handle error
this.ctx.onReceivedError(errorCode, description, failingUrl); this.ctx.onReceivedError(errorCode, description, failingUrl);
} }
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.ctx.getPackageName(); final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager(); final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo; ApplicationInfo appInfo;
@ -289,7 +288,7 @@ public class CordovaWebViewClient extends WebViewClient {
return; return;
} else { } else {
// debug = false // debug = false
super.onReceivedSslError(view, handler, error); super.onReceivedSslError(view, handler, error);
} }
} catch (NameNotFoundException e) { } catch (NameNotFoundException e) {
// When it doubt, lock it out! // When it doubt, lock it out!
@ -299,7 +298,7 @@ public class CordovaWebViewClient extends WebViewClient {
@Override @Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
/* /*
* If you do a document.location.href the url does not get pushed on the stack * If you do a document.location.href the url does not get pushed on the stack
* so we do a check here to see if the url should be pushed. * so we do a check here to see if the url should be pushed.
*/ */

View File

@ -41,7 +41,7 @@ public class Device extends Plugin {
public static String cordovaVersion = "1.8.0rc1"; // Cordova version public static String cordovaVersion = "1.8.0rc1"; // Cordova version
public static String platform = "Android"; // Device OS public static String platform = "Android"; // Device OS
public static String uuid; // Device UUID public static String uuid; // Device UUID
BroadcastReceiver telephonyReceiver = null; BroadcastReceiver telephonyReceiver = null;
/** /**
@ -49,11 +49,11 @@ public class Device extends Plugin {
*/ */
public Device() { public Device() {
} }
/** /**
* 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) {
@ -64,7 +64,7 @@ public class Device extends Plugin {
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param callbackId The callback id used when calling back into JavaScript.
@ -72,8 +72,8 @@ public class Device extends Plugin {
*/ */
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("getDeviceInfo")) { if (action.equals("getDeviceInfo")) {
JSONObject r = new JSONObject(); JSONObject r = new JSONObject();
@ -95,7 +95,7 @@ public class Device extends Plugin {
/** /**
* 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
*/ */
@ -105,7 +105,7 @@ public class Device extends Plugin {
} }
return false; return false;
} }
/** /**
* Unregister receiver. * Unregister receiver.
*/ */
@ -116,7 +116,7 @@ public class Device extends Plugin {
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// LOCAL METHODS // LOCAL METHODS
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
/** /**
* Listen for telephony events: RINGING, OFFHOOK and IDLE * Listen for telephony events: RINGING, OFFHOOK and IDLE
* Send these events to all plugins using * Send these events to all plugins using
@ -127,10 +127,10 @@ public class Device extends Plugin {
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
final CordovaInterface myctx = this.ctx; final CordovaInterface myctx = this.ctx;
this.telephonyReceiver = new BroadcastReceiver() { this.telephonyReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// If state has changed // If state has changed
if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) { if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) { if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) {
@ -151,69 +151,69 @@ public class Device extends Plugin {
} }
} }
}; };
// Register the receiver // Register the receiver
this.ctx.registerReceiver(this.telephonyReceiver, intentFilter); this.ctx.registerReceiver(this.telephonyReceiver, intentFilter);
} }
/** /**
* Get the OS name. * Get the OS name.
* *
* @return * @return
*/ */
public String getPlatform() { public String getPlatform() {
return Device.platform; return Device.platform;
} }
/** /**
* Get the device's Universally Unique Identifier (UUID). * Get the device's Universally Unique Identifier (UUID).
* *
* @return * @return
*/ */
public String getUuid() { public String getUuid() {
String uuid = Settings.Secure.getString(this.ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); String uuid = Settings.Secure.getString(this.ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid; return uuid;
} }
/** /**
* Get the Cordova version. * Get the Cordova version.
* *
* @return * @return
*/ */
public String getCordovaVersion() { public String getCordovaVersion() {
return Device.cordovaVersion; return Device.cordovaVersion;
} }
public String getModel() { public String getModel() {
String model = android.os.Build.MODEL; String model = android.os.Build.MODEL;
return model; return model;
} }
public String getProductName() { public String getProductName() {
String productname = android.os.Build.PRODUCT; String productname = android.os.Build.PRODUCT;
return productname; return productname;
} }
/** /**
* Get the OS version. * Get the OS version.
* *
* @return * @return
*/ */
public String getOSVersion() { public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE; String osversion = android.os.Build.VERSION.RELEASE;
return osversion; return osversion;
} }
public String getSDKVersion() { public String getSDKVersion() {
String sdkversion = android.os.Build.VERSION.SDK; String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion; return sdkversion;
} }
public String getTimeZoneID() { public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault(); TimeZone tz = TimeZone.getDefault();
return(tz.getID()); return(tz.getID());
} }
} }

View File

@ -25,127 +25,127 @@ import android.os.Environment;
import android.os.StatFs; import android.os.StatFs;
/** /**
* This class provides file directory utilities. * This class provides file directory utilities.
* All file operations are performed on the SD card. * All file operations are performed on the SD card.
* *
* It is used by the FileUtils class. * It is used by the FileUtils class.
*/ */
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.
* /**
* @param name The name of the file to check. * Determine if a file or directory exists.
* @return T=exists, F=not found *
*/ * @param name The name of the file to check.
protected static boolean testFileExists(String name) { * @return T=exists, F=not found
boolean status; */
protected static boolean testFileExists(String name) {
// If SD card exists boolean status;
if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory(); // If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) {
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.
*
* @return T=exists, F=not found
*/
protected static boolean testSaveLocationExists() {
String sDCardStatus = Environment.getExternalStorageState();
boolean status;
// If SD card is mounted
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
status = true;
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Create a new file object from two file paths.
*
* @param file1 Base file path
* @param file2 Remaining file path
* @return File object
*/
private static File constructFilePaths (String file1, String file2) {
File newPath;
if (file2.startsWith(file1)) {
newPath = new File(file2);
}
else {
newPath = new File(file1+"/"+file2);
}
return newPath;
}
/** /**
* Determine if we can use the SD Card to store the temporary file. If not then use * Determine if SD card exists.
*
* @return T=exists, F=not found
*/
protected static boolean testSaveLocationExists() {
String sDCardStatus = Environment.getExternalStorageState();
boolean status;
// If SD card is mounted
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
status = true;
}
// If no SD card
else {
status = false;
}
return status;
}
/**
* Create a new file object from two file paths.
*
* @param file1 Base file path
* @param file2 Remaining file path
* @return File object
*/
private static File constructFilePaths (String file1, String file2) {
File newPath;
if (file2.startsWith(file1)) {
newPath = new File(file2);
}
else {
newPath = new File(file1+"/"+file2);
}
return newPath;
}
/**
* Determine if we can use the SD Card to store the temporary file. If not then use
* the internal cache directory. * the internal cache directory.
* *
* @return the absolute path of where to store the file * @return the absolute path of where to store the file
*/ */
protected static String getTempDirectoryPath(Context ctx) { protected static String getTempDirectoryPath(Context ctx) {
File cache = null; File cache = null;
// SD Card Mounted // SD Card Mounted
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + cache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/" + ctx.getPackageName() + "/cache/"); "/Android/data/" + ctx.getPackageName() + "/cache/");
} }
// Use internal storage // Use internal storage
else { else {
cache = ctx.getCacheDir(); cache = ctx.getCacheDir();

File diff suppressed because it is too large Load Diff

View File

@ -41,31 +41,31 @@ public class ExifHelper {
private String make = null; private String make = null;
private String model = null; private String model = null;
private String orientation = null; private String orientation = null;
private String whiteBalance = null; private String whiteBalance = null;
private ExifInterface inFile = null; private ExifInterface inFile = null;
private ExifInterface outFile = null; private ExifInterface outFile = null;
/** /**
* The file before it is compressed * The file before it is compressed
* *
* @param filePath * @param filePath
* @throws IOException * @throws IOException
*/ */
public void createInFile(String filePath) throws IOException { public void createInFile(String filePath) throws IOException {
this.inFile = new ExifInterface(filePath); this.inFile = new ExifInterface(filePath);
} }
/** /**
* The file after it has been compressed * The file after it has been compressed
* *
* @param filePath * @param filePath
* @throws IOException * @throws IOException
*/ */
public void createOutFile(String filePath) throws IOException { public void createOutFile(String filePath) throws IOException {
this.outFile = new ExifInterface(filePath); this.outFile = new ExifInterface(filePath);
} }
/** /**
* Reads all the EXIF data from the input file. * Reads all the EXIF data from the input file.
*/ */
@ -88,12 +88,12 @@ public class ExifHelper {
this.make = inFile.getAttribute(ExifInterface.TAG_MAKE); this.make = inFile.getAttribute(ExifInterface.TAG_MAKE);
this.model = inFile.getAttribute(ExifInterface.TAG_MODEL); this.model = inFile.getAttribute(ExifInterface.TAG_MODEL);
this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION); this.orientation = inFile.getAttribute(ExifInterface.TAG_ORIENTATION);
this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE); this.whiteBalance = inFile.getAttribute(ExifInterface.TAG_WHITE_BALANCE);
} }
/** /**
* Writes the previously stored EXIF data to the output file. * Writes the previously stored EXIF data to the output file.
* *
* @throws IOException * @throws IOException
*/ */
public void writeExifData() throws IOException { public void writeExifData() throws IOException {
@ -101,7 +101,7 @@ public class ExifHelper {
if (this.outFile == null) { if (this.outFile == null) {
return; return;
} }
if (this.aperature != null) { if (this.aperature != null) {
this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperature); this.outFile.setAttribute(ExifInterface.TAG_APERTURE, this.aperature);
} }
@ -159,7 +159,7 @@ public class ExifHelper {
if (this.whiteBalance != null) { if (this.whiteBalance != null) {
this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance); this.outFile.setAttribute(ExifInterface.TAG_WHITE_BALANCE, this.whiteBalance);
} }
this.outFile.saveAttributes(); this.outFile.saveAttributes();
} }
} }

View File

@ -452,14 +452,14 @@ public class FileTransfer extends Plugin {
URL url = new URL(source); URL url = new URL(source);
connection = (HttpURLConnection) url.openConnection(); connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
//Add cookie support //Add cookie support
String cookie = CookieManager.getInstance().getCookie(source); String cookie = CookieManager.getInstance().getCookie(source);
if(cookie != null) if(cookie != null)
{ {
connection.setRequestProperty("cookie", cookie); connection.setRequestProperty("cookie", cookie);
} }
connection.connect(); connection.connect();
Log.d(LOG_TAG, "Download file: " + url); Log.d(LOG_TAG, "Download file: " + url);
@ -538,7 +538,7 @@ public class FileTransfer extends Plugin {
/** /**
* Get a File object from the passed in path * Get a File object from the passed in path
* *
* @param path file path * @param path file path
* @return file object * @return file object
*/ */

View File

@ -25,39 +25,39 @@ import org.json.JSONObject;
* Encapsulates the result and/or status of uploading a file to a remote server. * Encapsulates the result and/or status of uploading a file to a remote server.
*/ */
public class FileUploadResult { public class FileUploadResult {
private long bytesSent = 0; // bytes sent private long bytesSent = 0; // bytes sent
private int responseCode = -1; // HTTP response code private int responseCode = -1; // HTTP response code
private String response = null; // HTTP response private String response = null; // HTTP response
public long getBytesSent() { public long getBytesSent() {
return bytesSent; return bytesSent;
} }
public void setBytesSent(long bytes) { public void setBytesSent(long bytes) {
this.bytesSent = bytes; this.bytesSent = bytes;
} }
public int getResponseCode() { public int getResponseCode() {
return responseCode; return responseCode;
} }
public void setResponseCode(int responseCode) { public void setResponseCode(int responseCode) {
this.responseCode = responseCode; this.responseCode = responseCode;
} }
public String getResponse() { public String getResponse() {
return response; return response;
} }
public void setResponse(String response) { public void setResponse(String response) {
this.response = response; this.response = response;
} }
public JSONObject toJSONObject() throws JSONException { public JSONObject toJSONObject() throws JSONException {
return new JSONObject( return new JSONObject(
"{bytesSent:" + bytesSent + "{bytesSent:" + bytesSent +
",responseCode:" + responseCode + ",responseCode:" + responseCode +
",response:" + JSONObject.quote(response) + "}"); ",response:" + JSONObject.quote(response) + "}");
} }
} }

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;
@ -727,7 +726,7 @@ public class FileUtils extends Plugin {
filePath = stripFileProtocol(filePath); filePath = stripFileProtocol(filePath);
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + ctx.getPackageName() + "/cache") || if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + ctx.getPackageName() + "/cache") ||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) || filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
filePath.equals("/data/data/" + ctx.getPackageName())) { filePath.equals("/data/data/" + ctx.getPackageName())) {
return true; return true;
} }
@ -736,7 +735,7 @@ public class FileUtils extends Plugin {
/** /**
* This method removes the "file://" from the passed in filePath * This method removes the "file://" from the passed in filePath
* *
* @param filePath to be checked. * @param filePath to be checked.
* @return * @return
*/ */
@ -746,10 +745,10 @@ public class FileUtils extends Plugin {
} }
return filePath; return filePath;
} }
/** /**
* Create a File object from the passed in path * Create a File object from the passed in path
* *
* @param filePath * @param filePath
* @return * @return
*/ */
@ -840,7 +839,7 @@ public class FileUtils extends Plugin {
else { else {
throw new IOException("No filesystem of type requested"); throw new IOException("No filesystem of type requested");
} }
return fs; return fs;
} }
@ -974,7 +973,7 @@ public class FileUtils extends Plugin {
/**/ /**/
public long write(String filename, String data, int offset) throws FileNotFoundException, IOException { public long write(String filename, String data, int offset) throws FileNotFoundException, IOException {
filename = stripFileProtocol(filename); filename = stripFileProtocol(filename);
boolean append = false; boolean append = false;
if (offset > 0) { if (offset > 0) {
this.truncateFile(filename, offset); this.truncateFile(filename, offset);

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

@ -30,7 +30,7 @@ import android.location.LocationManager;
/* /*
* This class is the interface to the Geolocation. It's bound to the geo object. * This class is the interface to the Geolocation. It's bound to the geo object.
* *
* This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener * This class only starts and stops various GeoListeners, which consist of a GPS and a Network Listener
*/ */
@ -38,7 +38,7 @@ public class GeoBroker extends Plugin {
private GPSListener gpsListener; private GPSListener gpsListener;
private NetworkListener networkListener; private NetworkListener networkListener;
private LocationManager locationManager; private LocationManager locationManager;
/** /**
* Constructor. * Constructor.
*/ */
@ -47,74 +47,74 @@ public class GeoBroker extends Plugin {
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript. * @param 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) {
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);
result.setKeepCallback(true); result.setKeepCallback(true);
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
* @return T=returns value * @return T=returns value
*/ */
@ -122,65 +122,65 @@ public class GeoBroker extends Plugin {
// Starting listeners is easier to run on main thread, so don't run async. // Starting listeners is easier to run on main thread, so don't run async.
return true; return true;
} }
/** /**
* Called when the activity is to be shut down. * Called when the activity is to be shut down.
* 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.
* *
* @param code The error code * @param code The error code
* @param msg The error message * @param msg The error message
* @throws JSONException * @throws JSONException
*/ */
public void fail(int code, String msg, String callbackId) { public void fail(int code, String msg, 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;
/** /**
@ -29,15 +28,15 @@ import android.widget.LinearLayout;
public class LinearLayoutSoftKeyboardDetect extends LinearLayout { public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private static final String TAG = "SoftKeyboardDetect"; private static final String TAG = "SoftKeyboardDetect";
private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldHeight = 0; // Need to save the old height as not to send redundant events
private int oldWidth = 0; // Need to save old width for orientation change private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0; private int screenWidth = 0;
private int screenHeight = 0; private int screenHeight = 0;
private DroidGap app = null; private DroidGap app = null;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context); super(context);
screenWidth = width; screenWidth = width;
screenHeight = height; screenHeight = height;
app = (DroidGap) context; app = (DroidGap) context;
@ -45,18 +44,18 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
@Override @Override
/** /**
* Start listening to new measurement events. Fire events when the height * Start listening to new measurement events. Fire events when the height
* gets smaller fire a show keyboard event and when height gets bigger fire * gets smaller fire a show keyboard event and when height gets bigger fire
* a hide keyboard event. * a hide keyboard event.
* *
* Note: We are using app.postMessage so that this is more compatible with the API * Note: We are using app.postMessage so that this is more compatible with the API
* *
* @param widthMeasureSpec * @param widthMeasureSpec
* @param heightMeasureSpec * @param heightMeasureSpec
*/ */
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec);
LOG.v(TAG, "We are in our onMeasure method"); LOG.v(TAG, "We are in our onMeasure method");
// Get the current height of the visible part of the screen. // Get the current height of the visible part of the screen.
@ -66,7 +65,7 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
height = MeasureSpec.getSize(heightMeasureSpec); height = MeasureSpec.getSize(heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec); width = MeasureSpec.getSize(widthMeasureSpec);
LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Old Height = %d", oldHeight);
LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Height = %d", height);
LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Old Width = %d", oldWidth);
LOG.v(TAG, "Width = %d", width); LOG.v(TAG, "Width = %d", width);
@ -83,13 +82,13 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
screenWidth = tmp_var; screenWidth = tmp_var;
LOG.v(TAG, "Orientation Change"); LOG.v(TAG, "Orientation Change");
} }
// If the height as gotten bigger then we will assume the soft keyboard has // If the height as gotten bigger then we will assume the soft keyboard has
// gone away. // gone away.
else if (height > oldHeight) { else if (height > oldHeight) {
if(app != null) if(app != null)
app.sendJavascript("cordova.fireDocumentEvent('hidekeyboard');"); app.sendJavascript("cordova.fireDocumentEvent('hidekeyboard');");
} }
// If the height as gotten smaller then we will assume the soft keyboard has // If the height as gotten smaller then we will assume the soft keyboard has
// been displayed. // been displayed.
else if (height < oldHeight) { else if (height < oldHeight) {
if(app != null) if(app != null)

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

@ -33,7 +33,7 @@ import android.net.NetworkInfo;
import android.util.Log; import android.util.Log;
public class NetworkManager extends Plugin { public class NetworkManager extends Plugin {
public static int NOT_REACHABLE = 0; public static int NOT_REACHABLE = 0;
public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1;
public static int REACHABLE_VIA_WIFI_NETWORK = 2; public static int REACHABLE_VIA_WIFI_NETWORK = 2;
@ -66,14 +66,14 @@ public class NetworkManager extends Plugin {
public static final String TYPE_3G = "3g"; public static final String TYPE_3G = "3g";
public static final String TYPE_4G = "4g"; public static final String TYPE_4G = "4g";
public static final String TYPE_NONE = "none"; public static final String TYPE_NONE = "none";
private static final String LOG_TAG = "NetworkManager"; private static final String LOG_TAG = "NetworkManager";
private String connectionCallbackId; private String connectionCallbackId;
ConnectivityManager sockMan; ConnectivityManager sockMan;
BroadcastReceiver receiver; BroadcastReceiver receiver;
/** /**
* Constructor. * Constructor.
*/ */
@ -84,14 +84,14 @@ public class NetworkManager extends Plugin {
/** /**
* 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.sockMan = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); this.sockMan = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
this.connectionCallbackId = null; this.connectionCallbackId = null;
// We need to listen to connectivity events to update navigator.connection // We need to listen to connectivity events to update navigator.connection
IntentFilter intentFilter = new IntentFilter() ; IntentFilter intentFilter = new IntentFilter() ;
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
@ -99,17 +99,17 @@ public class NetworkManager extends Plugin {
this.receiver = new BroadcastReceiver() { this.receiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO)); updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
} }
}; };
ctx.registerReceiver(this.receiver, intentFilter); ctx.registerReceiver(this.receiver, intentFilter);
} }
} }
/** /**
* 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.
@ -118,7 +118,7 @@ public class NetworkManager extends Plugin {
public PluginResult execute(String action, JSONArray args, String callbackId) { public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.INVALID_ACTION; PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
String result = "Unsupported Operation: " + action; String result = "Unsupported Operation: " + action;
if (action.equals("getConnectionInfo")) { if (action.equals("getConnectionInfo")) {
this.connectionCallbackId = callbackId; this.connectionCallbackId = callbackId;
NetworkInfo info = sockMan.getActiveNetworkInfo(); NetworkInfo info = sockMan.getActiveNetworkInfo();
@ -126,20 +126,20 @@ public class NetworkManager extends Plugin {
pluginResult.setKeepCallback(true); pluginResult.setKeepCallback(true);
return pluginResult; return pluginResult;
} }
return new PluginResult(status, result); return new PluginResult(status, result);
} }
/** /**
* 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 true; return true;
} }
/** /**
* Stop network receiver. * Stop network receiver.
*/ */
@ -160,18 +160,18 @@ public class NetworkManager extends Plugin {
/** /**
* Updates the JavaScript side whenever the connection changes * Updates the JavaScript side whenever the connection changes
* *
* @param info the current active network info * @param info the current active network info
* @return * @return
*/ */
private void updateConnectionInfo(NetworkInfo info) { private void updateConnectionInfo(NetworkInfo info) {
// send update to javascript "navigator.network.connection" // send update to javascript "navigator.network.connection"
sendUpdate(this.getConnectionInfo(info)); sendUpdate(this.getConnectionInfo(info));
} }
/** /**
* Get the latest network connection information * Get the latest network connection information
* *
* @param info the current active network info * @param info the current active network info
* @return a JSONObject that represents the network info * @return a JSONObject that represents the network info
*/ */
@ -188,24 +188,24 @@ public class NetworkManager extends Plugin {
} }
return type; return type;
} }
/** /**
* Create a new plugin result and send it back to JavaScript * Create a new plugin result and send it back to JavaScript
* *
* @param connection the network info to set as navigator.connection * @param connection the network info to set as navigator.connection
*/ */
private void sendUpdate(String type) { private void sendUpdate(String type) {
PluginResult result = new PluginResult(PluginResult.Status.OK, type); PluginResult result = new PluginResult(PluginResult.Status.OK, type);
result.setKeepCallback(true); result.setKeepCallback(true);
this.success(result, this.connectionCallbackId); this.success(result, this.connectionCallbackId);
// Send to all plugins // Send to all plugins
this.ctx.postMessage("networkconnection", type); this.ctx.postMessage("networkconnection", type);
} }
/** /**
* Determine the type of connection * Determine the type of connection
* *
* @param info the network info so we can determine connection type. * @param info the network info so we can determine connection type.
* @return the type of mobile network we are on * @return the type of mobile network we are on
*/ */
@ -218,12 +218,12 @@ public class NetworkManager extends Plugin {
} }
else if (type.toLowerCase().equals(MOBILE)) { else if (type.toLowerCase().equals(MOBILE)) {
type = info.getSubtypeName(); type = info.getSubtypeName();
if (type.toLowerCase().equals(GSM) || if (type.toLowerCase().equals(GSM) ||
type.toLowerCase().equals(GPRS) || type.toLowerCase().equals(GPRS) ||
type.toLowerCase().equals(EDGE)) { type.toLowerCase().equals(EDGE)) {
return TYPE_2G; return TYPE_2G;
} }
else if (type.toLowerCase().startsWith(CDMA) || else if (type.toLowerCase().startsWith(CDMA) ||
type.toLowerCase().equals(UMTS) || type.toLowerCase().equals(UMTS) ||
type.toLowerCase().equals(ONEXRTT) || type.toLowerCase().equals(ONEXRTT) ||
type.toLowerCase().equals(EHRPD) || type.toLowerCase().equals(EHRPD) ||
@ -232,13 +232,13 @@ public class NetworkManager extends Plugin {
type.toLowerCase().equals(HSPA)) { type.toLowerCase().equals(HSPA)) {
return TYPE_3G; return TYPE_3G;
} }
else if (type.toLowerCase().equals(LTE) || else if (type.toLowerCase().equals(LTE) ||
type.toLowerCase().equals(UMB) || type.toLowerCase().equals(UMB) ||
type.toLowerCase().equals(HSPA_PLUS)) { type.toLowerCase().equals(HSPA_PLUS)) {
return TYPE_4G; return TYPE_4G;
} }
} }
} }
else { else {
return TYPE_NONE; return TYPE_NONE;
} }

View File

@ -36,11 +36,11 @@ import android.os.Vibrator;
* This class provides access to notifications on the device. * This class provides access to notifications on the device.
*/ */
public class Notification extends Plugin { public class Notification extends Plugin {
public int confirmResult = -1; public int confirmResult = -1;
public ProgressDialog spinnerDialog = null; public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null; public ProgressDialog progressDialog = null;
/** /**
* Constructor. * Constructor.
*/ */
@ -49,7 +49,7 @@ public class Notification extends Plugin {
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* *
* @param action The action to execute. * @param action The action to execute.
* @param args JSONArry of arguments for the plugin. * @param args 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.
@ -57,8 +57,8 @@ public class Notification extends Plugin {
*/ */
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("beep")) { if (action.equals("beep")) {
this.beep(args.getLong(0)); this.beep(args.getLong(0));
@ -101,7 +101,7 @@ public class Notification extends Plugin {
/** /**
* 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
*/ */
@ -138,13 +138,13 @@ public class Notification extends Plugin {
/** /**
* Beep plays the default notification ringtone. * Beep plays the default notification ringtone.
* *
* @param count Number of times to play notification * @param count Number of times to play notification
*/ */
public void beep(long count) { public void beep(long count) {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(this.ctx.getContext(), ringtone); Ringtone notification = RingtoneManager.getRingtone(this.ctx.getContext(), ringtone);
// If phone is not set to silent mode // If phone is not set to silent mode
if (notification != null) { if (notification != null) {
for (long i = 0; i < count; ++i) { for (long i = 0; i < count; ++i) {
@ -160,10 +160,10 @@ public class Notification extends Plugin {
} }
} }
} }
/** /**
* Vibrates the device for the specified amount of time. * Vibrates the device for the specified amount of time.
* *
* @param time Time to vibrate in ms. * @param time Time to vibrate in ms.
*/ */
public void vibrate(long time){ public void vibrate(long time){
@ -174,22 +174,22 @@ public class Notification extends Plugin {
Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE); Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(time); vibrator.vibrate(time);
} }
/** /**
* Builds and shows a native Android alert with given Strings * Builds and shows a native Android alert with given Strings
* @param message The message the alert should display * @param message The message the alert should display
* @param title The title of the alert * @param title The title of the alert
* @param buttonLabel The label of the button * @param buttonLabel The label of the button
* @param callbackId The callback id * @param callbackId The callback id
*/ */
public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) { public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) {
final CordovaInterface ctx = this.ctx; final CordovaInterface ctx = this.ctx;
final Notification notification = this; final Notification notification = this;
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
public void run() { public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext()); AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message); dlg.setMessage(message);
dlg.setTitle(title); dlg.setTitle(title);
@ -212,7 +212,7 @@ public class Notification extends Plugin {
* Builds and shows a native Android confirm dialog with given title, message, buttons. * Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored. * This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId. * The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
* *
* @param message The message the dialog should display * @param message The message the dialog should display
* @param title The title of the dialog * @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons) * @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
@ -244,7 +244,7 @@ public class Notification extends Plugin {
// Second button // Second button
if (fButtons.length > 1) { if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1], dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() { new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); dialog.dismiss();
@ -274,7 +274,7 @@ public class Notification extends Plugin {
/** /**
* Show the spinner. * Show the spinner.
* *
* @param title Title of the dialog * @param title Title of the dialog
* @param message The message of the dialog * @param message The message of the dialog
*/ */
@ -287,8 +287,8 @@ public class Notification extends Plugin {
final CordovaInterface ctx = this.ctx; final CordovaInterface ctx = this.ctx;
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
public void run() { public void run() {
notification.spinnerDialog = ProgressDialog.show(ctx.getContext(), title , message, true, true, notification.spinnerDialog = ProgressDialog.show(ctx.getContext(), title , message, true, true,
new DialogInterface.OnCancelListener() { new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null; notification.spinnerDialog = null;
} }
@ -297,7 +297,7 @@ public class Notification extends Plugin {
}; };
this.ctx.runOnUiThread(runnable); this.ctx.runOnUiThread(runnable);
} }
/** /**
* Stop spinner. * Stop spinner.
*/ */
@ -310,7 +310,7 @@ public class Notification extends Plugin {
/** /**
* Show the progress dialog. * Show the progress dialog.
* *
* @param title Title of the dialog * @param title Title of the dialog
* @param message The message of the dialog * @param message The message of the dialog
*/ */
@ -331,7 +331,7 @@ public class Notification extends Plugin {
notification.progressDialog.setMax(100); notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0); notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener( notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() { new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
notification.progressDialog = null; notification.progressDialog = null;
} }
@ -341,18 +341,18 @@ public class Notification extends Plugin {
}; };
this.ctx.runOnUiThread(runnable); this.ctx.runOnUiThread(runnable);
} }
/** /**
* Set value of progress bar. * Set value of progress bar.
* *
* @param value 0-100 * @param value 0-100
*/ */
public synchronized void progressValue(int value) { public synchronized void progressValue(int value) {
if (this.progressDialog != null) { if (this.progressDialog != null) {
this.progressDialog.setProgress(value); this.progressDialog.setProgress(value);
} }
} }
/** /**
* Stop progress dialog. * Stop progress dialog.
*/ */

View File

@ -18,18 +18,15 @@
*/ */
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

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

View File

@ -33,80 +33,80 @@ import android.hardware.SensorManager;
import android.content.Context; import android.content.Context;
public class TempListener extends Plugin implements SensorEventListener { public class TempListener extends Plugin implements SensorEventListener {
Sensor mSensor;
private SensorManager sensorManager;
/**
* Constructor.
*/
public TempListener() {
}
/** Sensor mSensor;
* Sets the context of the Command. This can then be used to do things like private SensorManager sensorManager;
* get file paths associated with the Activity.
* /**
* @param ctx The context of the main Activity. * Constructor.
*/ */
public void setContext(CordovaInterface ctx) { public TempListener() {
super.setContext(ctx); }
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface 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.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
if (action.equals("start")) {
this.start();
}
else if (action.equals("stop")) {
this.stop();
}
return new PluginResult(status, result);
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
if (action.equals("start")) {
this.start();
}
else if (action.equals("stop")) {
this.stop();
}
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() {
this.sensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) { public void stop() {
// We want to know what temp this is. this.sensorManager.unregisterListener(this);
float temp = event.values[0]; }
this.sendJavascript("gotTemp(" + temp + ");");
} public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
// We want to know what temp this is.
float temp = event.values[0];
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;
@ -43,62 +40,62 @@ public interface CordovaInterface {
/** /**
* @deprecated * @deprecated
* Add services to res/xml/plugins.xml instead. * Add services to res/xml/plugins.xml instead.
* *
* Add a class that implements a service. * Add a class that implements a service.
* *
* @param serviceType * @param serviceType
* @param className * @param className
*/ */
@Deprecated @Deprecated
abstract public void addService(String serviceType, String className); abstract public void addService(String serviceType, String className);
/** /**
* Send JavaScript statement back to JavaScript. * Send JavaScript statement back to JavaScript.
* *
* @param message * @param message
*/ */
abstract public void sendJavascript(String statement); abstract public void sendJavascript(String statement);
/** /**
* Launch an activity for which you would like a result when it finished. When this activity exits, * Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called. * your onActivityResult() method will be called.
* *
* @param command The command object * @param command The command object
* @param intent The intent to start * @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity * @param requestCode The request code that is passed to callback to identify the activity
*/ */
abstract public void startActivityForResult(IPlugin command, Intent intent, int requestCode); abstract public void startActivityForResult(IPlugin command, Intent intent, int requestCode);
/** /**
* Launch an activity for which you would not like a result when it finished. * Launch an activity for which you would not like a result when it finished.
* *
* @param intent The intent to start * @param intent The intent to start
*/ */
abstract public void startActivity(Intent intent); abstract public void startActivity(Intent intent);
/** /**
* Set the plugin to be called when a sub-activity exits. * Set the plugin to be called when a sub-activity exits.
* *
* @param plugin The plugin on which onActivityResult is to be called * @param plugin The plugin on which onActivityResult is to be called
*/ */
abstract public void setActivityResultCallback(IPlugin plugin); abstract public void setActivityResultCallback(IPlugin plugin);
/** /**
* Load the specified URL in the Cordova webview. * Load the specified URL in the Cordova webview.
* *
* @param url The URL to load. * @param url The URL to load.
*/ */
abstract public void loadUrl(String url); abstract public void loadUrl(String url);
/** /**
* Send a message to all plugins. * Send a message to all plugins.
* *
* @param id The message id * @param id The message id
* @param data The message data * @param data The message data
*/ */
abstract public void postMessage(String id, Object data); abstract public void postMessage(String id, Object data);
public abstract Resources getResources(); public abstract Resources getResources();
public abstract String getPackageName(); public abstract String getPackageName();
@ -106,7 +103,7 @@ public interface CordovaInterface {
public abstract Object getSystemService(String service); public abstract Object getSystemService(String service);
public abstract Context getContext(); public abstract Context getContext();
public abstract Context getBaseContext(); public abstract Context getBaseContext();
public abstract Intent registerReceiver(BroadcastReceiver receiver, public abstract Intent registerReceiver(BroadcastReceiver receiver,
@ -118,7 +115,7 @@ public interface CordovaInterface {
public abstract Cursor managedQuery(Uri uri, String[] projection, String selection, public abstract Cursor managedQuery(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder); String[] selectionArgs, String sortOrder);
public abstract void runOnUiThread(Runnable runnable); public abstract void runOnUiThread(Runnable runnable);
public abstract AssetManager getAssets(); public abstract AssetManager getAssets();
@ -143,5 +140,5 @@ public interface CordovaInterface {
public abstract Context getApplicationContext(); public abstract Context getApplicationContext();
public abstract boolean isUrlWhiteListed(String source); public abstract boolean isUrlWhiteListed(String source);
} }

View File

@ -28,68 +28,68 @@ import android.webkit.WebView;
* The execute method is called by the PluginManager. * The execute method is called by the PluginManager.
*/ */
public interface IPlugin { public interface IPlugin {
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
PluginResult execute(String action, JSONArray args, String callbackId);
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action);
/**
* Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
void setContext(CordovaInterface ctx);
/**
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
* @param webView The Cordova WebView
*/
void setView(WebView webView);
/** /**
* Called when the system is about to start resuming a previous activity. * Executes the request and returns PluginResult.
* *
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
PluginResult execute(String action, JSONArray args, String callbackId);
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action);
/**
* Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
void setContext(CordovaInterface ctx);
/**
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
* @param webView The Cordova WebView
*/
void setView(WebView webView);
/**
* Called when the system is about to start resuming a previous activity.
*
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
void onPause(boolean multitasking); void onPause(boolean multitasking);
/** /**
* Called when the activity will start interacting with the user. * Called when the activity will start interacting with the user.
* *
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
void onResume(boolean multitasking); void onResume(boolean multitasking);
/** /**
* Called when the activity receives a new intent. * Called when the activity receives a new intent.
*/ */
void onNewIntent(Intent intent); void onNewIntent(Intent intent);
/** /**
* The final call you receive before your activity is destroyed. * The final call you receive before your activity is destroyed.
*/ */
void onDestroy(); void onDestroy();
/** /**
* Called when a message is sent to plugin. * Called when a message is sent to plugin.
* *
* @param id The message id * @param id The message id
* @param data The message data * @param data The message data
*/ */
@ -97,9 +97,9 @@ public interface IPlugin {
/** /**
* Called when an activity you launched exits, giving you the requestCode you started it with, * Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it. * the resultCode it returned, and any additional data from it.
* *
* @param requestCode The request code originally supplied to startActivityForResult(), * @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from. * allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult(). * @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
@ -108,7 +108,7 @@ public interface IPlugin {
/** /**
* By specifying a <url-filter> in plugins.xml you can map a URL (using startsWith atm) to this method. * By specifying a <url-filter> in plugins.xml you can map a URL (using startsWith atm) to this method.
* *
* @param url The URL that is trying to be loaded in the Cordova webview. * @param url The URL that is trying to be loaded in the Cordova webview.
* @return Return true to prevent the URL from loading. Default is false. * @return Return true to prevent the URL from loading. Default is false.
*/ */

View File

@ -22,12 +22,12 @@ import android.util.Log;
/** /**
* Log to Android logging system. * Log to Android logging system.
* *
* Log message can be a string or a printf formatted string with arguments. * Log message can be a string or a printf formatted string with arguments.
* See http://developer.android.com/reference/java/util/Formatter.html * See http://developer.android.com/reference/java/util/Formatter.html
*/ */
public class LOG { public class LOG {
public static final int VERBOSE = Log.VERBOSE; public static final int VERBOSE = Log.VERBOSE;
public static final int DEBUG = Log.DEBUG; public static final int DEBUG = Log.DEBUG;
public static final int INFO = Log.INFO; public static final int INFO = Log.INFO;
@ -36,20 +36,20 @@ public class LOG {
// Current log level // Current log level
public static int LOGLEVEL = Log.ERROR; public static int LOGLEVEL = Log.ERROR;
/** /**
* Set the current log level. * Set the current log level.
* *
* @param logLevel * @param logLevel
*/ */
public static void setLogLevel(int logLevel) { public static void setLogLevel(int logLevel) {
LOGLEVEL = logLevel; LOGLEVEL = logLevel;
Log.i("CordovaLog", "Changing log level to " + logLevel); Log.i("CordovaLog", "Changing log level to " + logLevel);
} }
/** /**
* Set the current log level. * Set the current log level.
* *
* @param logLevel * @param logLevel
*/ */
public static void setLogLevel(String logLevel) { public static void setLogLevel(String logLevel) {
@ -63,7 +63,7 @@ public class LOG {
/** /**
* Determine if log level will be logged * Determine if log level will be logged
* *
* @param logLevel * @param logLevel
* @return * @return
*/ */
@ -73,7 +73,7 @@ public class LOG {
/** /**
* Verbose log message. * Verbose log message.
* *
* @param tag * @param tag
* @param s * @param s
*/ */
@ -83,17 +83,17 @@ public class LOG {
/** /**
* Debug log message. * Debug log message.
* *
* @param tag * @param tag
* @param s * @param s
*/ */
public static void d(String tag, String s) { public static void d(String tag, String s) {
if (LOG.DEBUG >= LOGLEVEL) Log.d(tag, s); if (LOG.DEBUG >= LOGLEVEL) Log.d(tag, s);
} }
/** /**
* Info log message. * Info log message.
* *
* @param tag * @param tag
* @param s * @param s
*/ */
@ -103,7 +103,7 @@ public class LOG {
/** /**
* Warning log message. * Warning log message.
* *
* @param tag * @param tag
* @param s * @param s
*/ */
@ -113,7 +113,7 @@ public class LOG {
/** /**
* Error log message. * Error log message.
* *
* @param tag * @param tag
* @param s * @param s
*/ */
@ -123,7 +123,7 @@ public class LOG {
/** /**
* Verbose log message. * Verbose log message.
* *
* @param tag * @param tag
* @param s * @param s
* @param e * @param e
@ -134,7 +134,7 @@ public class LOG {
/** /**
* Debug log message. * Debug log message.
* *
* @param tag * @param tag
* @param s * @param s
* @param e * @param e
@ -142,10 +142,10 @@ public class LOG {
public static void d(String tag, String s, Throwable e) { public static void d(String tag, String s, Throwable e) {
if (LOG.DEBUG >= LOGLEVEL) Log.d(tag, s, e); if (LOG.DEBUG >= LOGLEVEL) Log.d(tag, s, e);
} }
/** /**
* Info log message. * Info log message.
* *
* @param tag * @param tag
* @param s * @param s
* @param e * @param e
@ -156,7 +156,7 @@ public class LOG {
/** /**
* Warning log message. * Warning log message.
* *
* @param tag * @param tag
* @param s * @param s
* @param e * @param e
@ -167,7 +167,7 @@ public class LOG {
/** /**
* Error log message. * Error log message.
* *
* @param tag * @param tag
* @param s * @param s
* @param e * @param e
@ -178,7 +178,7 @@ public class LOG {
/** /**
* Verbose log message with printf formatting. * Verbose log message with printf formatting.
* *
* @param tag * @param tag
* @param s * @param s
* @param args * @param args
@ -189,7 +189,7 @@ public class LOG {
/** /**
* Debug log message with printf formatting. * Debug log message with printf formatting.
* *
* @param tag * @param tag
* @param s * @param s
* @param args * @param args
@ -200,7 +200,7 @@ public class LOG {
/** /**
* Info log message with printf formatting. * Info log message with printf formatting.
* *
* @param tag * @param tag
* @param s * @param s
* @param args * @param args
@ -208,10 +208,10 @@ public class LOG {
public static void i(String tag, String s, Object... args) { public static void i(String tag, String s, Object... args) {
if (LOG.INFO >= LOGLEVEL) Log.i(tag, String.format(s, args)); if (LOG.INFO >= LOGLEVEL) Log.i(tag, String.format(s, args));
} }
/** /**
* Warning log message with printf formatting. * Warning log message with printf formatting.
* *
* @param tag * @param tag
* @param s * @param s
* @param args * @param args
@ -219,10 +219,10 @@ public class LOG {
public static void w(String tag, String s, Object... args) { public static void w(String tag, String s, Object... args) {
if (LOG.WARN >= LOGLEVEL) Log.w(tag, String.format(s, args)); if (LOG.WARN >= LOGLEVEL) Log.w(tag, String.format(s, args));
} }
/** /**
* Error log message with printf formatting. * Error log message with printf formatting.
* *
* @param tag * @param tag
* @param s * @param s
* @param args * @param args

View File

@ -31,81 +31,81 @@ 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.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public abstract PluginResult execute(String action, JSONArray args, String callbackId);
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
return false;
}
/**
* Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface ctx) {
this.ctx = ctx;
}
/**
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
* @param webView The Cordova WebView
*/
public void setView(WebView webView) {
this.webView = webView;
}
/** /**
* Called when the system is about to start resuming a previous activity. * Executes the request and returns PluginResult.
* *
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public abstract PluginResult execute(String action, JSONArray args, String callbackId);
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
return false;
}
/**
* Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface ctx) {
this.ctx = ctx;
}
/**
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
* @param webView The Cordova WebView
*/
public void setView(WebView webView) {
this.webView = webView;
}
/**
* Called when the system is about to start resuming a previous activity.
*
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
public void onPause(boolean multitasking) { public void onPause(boolean multitasking) {
} }
/** /**
* Called when the activity will start interacting with the user. * Called when the activity will start interacting with the user.
* *
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
public void onResume(boolean multitasking) { public void onResume(boolean multitasking) {
} }
/** /**
* Called when the activity receives a new intent. * Called when the activity receives a new intent.
*/ */
public void onNewIntent(Intent intent) { public void onNewIntent(Intent intent) {
} }
/** /**
* The final call you receive before your activity is destroyed. * The final call you receive before your activity is destroyed.
*/ */
public void onDestroy() { public void onDestroy() {
} }
/** /**
* Called when a message is sent to plugin. * Called when a message is sent to plugin.
* *
* @param id The message id * @param id The message id
* @param data The message data * @param data The message data
*/ */
@ -114,9 +114,9 @@ public abstract class Plugin implements IPlugin {
/** /**
* Called when an activity you launched exits, giving you the requestCode you started it with, * Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it. * the resultCode it returned, and any additional data from it.
* *
* @param requestCode The request code originally supplied to startActivityForResult(), * @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from. * allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult(). * @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
@ -126,85 +126,85 @@ public abstract class Plugin implements IPlugin {
/** /**
* By specifying a <url-filter> in plugins.xml you can map a URL (using startsWith atm) to this method. * By specifying a <url-filter> in plugins.xml you can map a URL (using startsWith atm) to this method.
* *
* @param url The URL that is trying to be loaded in the Cordova webview. * @param url The URL that is trying to be loaded in the Cordova webview.
* @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;
} }
/** /**
* Send generic JavaScript statement back to JavaScript. * Send generic JavaScript statement back to JavaScript.
* success(...) and error(...) should be used instead where possible. * success(...) and error(...) should be used instead where possible.
* *
* @param statement * @param statement
*/ */
public void sendJavascript(String statement) { public void sendJavascript(String statement) {
this.ctx.sendJavascript(statement); this.ctx.sendJavascript(statement);
} }
/** /**
* Call the JavaScript success callback for this plugin. * Call the JavaScript success callback for this plugin.
* *
* This can be used if the execute code for the plugin is asynchronous meaning * This can be used if the execute code for the plugin is asynchronous meaning
* that execute should return null and the callback from the async operation can * that execute should return null and the callback from the async operation can
* 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));
} }
/** /**
* Helper for success callbacks that just returns the Status.OK by default * Helper for success callbacks that just returns the Status.OK by default
* *
* @param message The message to add to the success result. * @param message The message to add to the success result.
* @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));
} }
/** /**
* Helper for success callbacks that just returns the Status.OK by default * Helper for success callbacks that just returns the Status.OK by default
* *
* @param message The message to add to the success result. * @param message The message to add to the success result.
* @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));
} }
/** /**
* Helper for error callbacks that just returns the Status.ERROR by default * Helper for error callbacks that just returns the Status.ERROR by default
* *
* @param message The message to add to the error result. * @param message The message to add to the error result.
* @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));
} }
/** /**
* Helper for error callbacks that just returns the Status.ERROR by default * Helper for error callbacks that just returns the Status.ERROR by default
* *
* @param message The message to add to the error result. * @param message The message to add to the error result.
* @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

@ -43,13 +43,13 @@ public class PluginEntry {
public IPlugin plugin = null; public IPlugin plugin = null;
/** /**
* Flag that indicates the plugin object should be created when PluginManager is initialized. * Flag that indicates the plugin object should be created when PluginManager is initialized.
*/ */
public boolean onload = false; public boolean onload = false;
/** /**
* Constructor * Constructor
* *
* @param service The name of the service * @param service The name of the service
* @param pluginClass The plugin class name * @param pluginClass The plugin class name
* @param onload Create plugin object when HTML page is loaded * @param onload Create plugin object when HTML page is loaded
@ -63,7 +63,7 @@ public class PluginEntry {
/** /**
* Create plugin object. * Create plugin object.
* If plugin is already created, then just return it. * If plugin is already created, then just return it.
* *
* @return The plugin object * @return The plugin object
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -88,7 +88,7 @@ public class PluginEntry {
/** /**
* Get the class. * Get the class.
* *
* @param clazz * @param clazz
* @return * @return
* @throws ClassNotFoundException * @throws ClassNotFoundException
@ -105,7 +105,7 @@ public class PluginEntry {
/** /**
* Get the interfaces that a class implements and see if it implements the * Get the interfaces that a class implements and see if it implements the
* org.apache.cordova.api.Plugin interface. * org.apache.cordova.api.Plugin interface.
* *
* @param c The class to check the interfaces of. * @param c The class to check the interfaces of.
* @return Boolean indicating if the class implements org.apache.cordova.api.Plugin * @return Boolean indicating if the class implements org.apache.cordova.api.Plugin
*/ */

View File

@ -33,7 +33,7 @@ import android.webkit.WebView;
/** /**
* PluginManager is exposed to JavaScript in the Cordova WebView. * PluginManager is exposed to JavaScript in the Cordova WebView.
* *
* Calling native plugin code can be done by calling PluginManager.exec(...) * Calling native plugin code can be done by calling PluginManager.exec(...)
* from JavaScript. * from JavaScript.
*/ */
@ -55,7 +55,7 @@ public class PluginManager {
/** /**
* Constructor. * Constructor.
* *
* @param app * @param app
* @param ctx * @param ctx
*/ */
@ -148,23 +148,23 @@ public class PluginManager {
/** /**
* Receives a request for execution and fulfills it by finding the appropriate * Receives a request for execution and fulfills it by finding the appropriate
* Java class and calling it's execute method. * Java class and calling it's execute method.
* *
* PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded * PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded
* string is returned that will indicate if any errors have occurred when trying to find * string is returned that will indicate if any errors have occurred when trying to find
* or execute the class denoted by the clazz argument. * or execute the class denoted by the clazz argument.
* *
* @param service String containing the service to run * @param service String containing the service to run
* @param action String containt the action that the class is supposed to perform. This is * @param action String containt the action that the class is supposed to perform. This is
* passed to the plugin execute method and it is up to the plugin developer * passed to the plugin execute method and it is up to the plugin developer
* how to deal with it. * how to deal with it.
* @param callbackId String containing the id of the callback that is execute in JavaScript if * @param callbackId String containing the id of the callback that is execute in JavaScript if
* this is an async plugin call. * this is an async plugin call.
* @param args An Array literal string containing any arguments needed in the * @param args An Array literal string containing any arguments needed in the
* plugin execute method. * plugin execute method.
* @param async Boolean indicating whether the calling JavaScript code is expecting an * @param async Boolean indicating whether the calling JavaScript code is expecting an
* immediate return value. If true, either Cordova.callbackSuccess(...) or * immediate return value. If true, either Cordova.callbackSuccess(...) or
* Cordova.callbackError(...) is called once the plugin code has executed. * Cordova.callbackError(...) is called once the plugin code has executed.
* *
* @return JSON encoded string with a response message and status. * @return JSON encoded string with a response message and status.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -232,10 +232,10 @@ public class PluginManager {
} }
/** /**
* Get the plugin object that implements the service. * Get the plugin object that implements the service.
* If the plugin object does not already exist, then create it. * If the plugin object does not already exist, then create it.
* If the service doesn't exist, then return null. * If the service doesn't exist, then return null.
* *
* @param service The name of the service. * @param service The name of the service.
* @return IPlugin or null * @return IPlugin or null
*/ */
@ -252,9 +252,9 @@ public class PluginManager {
} }
/** /**
* Add a plugin class that implements a service to the service entry table. * Add a plugin class that implements a service to the service entry table.
* This does not create the plugin object instance. * This does not create the plugin object instance.
* *
* @param service The service name * @param service The service name
* @param className The plugin class name * @param className The plugin class name
*/ */
@ -264,9 +264,9 @@ public class PluginManager {
} }
/** /**
* Add a plugin class that implements a service to the service entry table. * Add a plugin class that implements a service to the service entry table.
* This does not create the plugin object instance. * This does not create the plugin object instance.
* *
* @param entry The plugin entry * @param entry The plugin entry
*/ */
public void addService(PluginEntry entry) { public void addService(PluginEntry entry) {
@ -275,7 +275,7 @@ public class PluginManager {
/** /**
* Called when the system is about to start resuming a previous activity. * Called when the system is about to start resuming a previous activity.
* *
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
public void onPause(boolean multitasking) { public void onPause(boolean multitasking) {
@ -288,7 +288,7 @@ public class PluginManager {
/** /**
* Called when the activity will start interacting with the user. * Called when the activity will start interacting with the user.
* *
* @param multitasking Flag indicating if multitasking is turned on for app * @param multitasking Flag indicating if multitasking is turned on for app
*/ */
public void onResume(boolean multitasking) { public void onResume(boolean multitasking) {
@ -312,7 +312,7 @@ public class PluginManager {
/** /**
* Send a message to all plugins. * Send a message to all plugins.
* *
* @param id The message id * @param id The message id
* @param data The message data * @param data The message data
*/ */
@ -337,7 +337,7 @@ public class PluginManager {
/** /**
* Called when the URL of the webview changes. * Called when the URL of the webview changes.
* *
* @param url The URL that is being changed to. * @param url The URL that is being changed to.
* @return Return false to allow the URL to load, return true to prevent the URL from loading. * @return Return false to allow the URL to load, return true to prevent the URL from loading.
*/ */

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) {
this.status = status.ordinal();
this.message = "'" + PluginResult.StatusMessages[this.status] + "'";
}
public PluginResult(Status status, String message) {
this.status = status.ordinal();
this.message = JSONObject.quote(message);
}
public PluginResult(Status status, JSONArray message) { public PluginResult(Status status) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = message.toString(); this.message = "'" + PluginResult.StatusMessages[this.status] + "'";
} }
public PluginResult(Status status, JSONObject message) { public PluginResult(Status status, String message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = message.toString(); this.message = JSONObject.quote(message);
} }
public PluginResult(Status status, int i) { public PluginResult(Status status, JSONArray message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+i; this.message = message.toString();
} }
public PluginResult(Status status, float f) { public PluginResult(Status status, JSONObject message) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+f; this.message = message.toString();
} }
public PluginResult(Status status, boolean b) { public PluginResult(Status status, int i) {
this.status = status.ordinal(); this.status = status.ordinal();
this.message = ""+b; this.message = ""+i;
} }
public void setKeepCallback(boolean b) {
this.keepCallback = b;
}
public int getStatus() {
return status;
}
public String getMessage() { public PluginResult(Status status, float f) {
return message; this.status = status.ordinal();
} this.message = ""+f;
}
public boolean getKeepCallback() {
return this.keepCallback; public PluginResult(Status status, boolean b) {
} this.status = status.ordinal();
this.message = ""+b;
public String getJSONString() { }
return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}";
} public void setKeepCallback(boolean b) {
this.keepCallback = b;
public String toSuccessCallbackString(String callbackId) { }
return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
} public int getStatus() {
return status;
public String toErrorCallbackString(String callbackId) { }
return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
} public String getMessage() {
return message;
public static String[] StatusMessages = new String[] { }
"No result",
"OK", public boolean getKeepCallback() {
"Class not found", return this.keepCallback;
"Illegal access", }
"Instantiation error",
"Malformed url", public String getJSONString() {
"IO error", return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}";
"Invalid action", }
"JSON error",
"Error" public String toSuccessCallbackString(String callbackId) {
}; return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
}
public enum Status {
NO_RESULT, public String toErrorCallbackString(String callbackId) {
OK, return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
CLASS_NOT_FOUND_EXCEPTION, }
ILLEGAL_ACCESS_EXCEPTION,
INSTANTIATION_EXCEPTION, public static String[] StatusMessages = new String[] {
MALFORMED_URL_EXCEPTION, "No result",
IO_EXCEPTION, "OK",
INVALID_ACTION, "Class not found",
JSON_EXCEPTION, "Illegal access",
ERROR "Instantiation error",
} "Malformed url",
"IO error",
"Invalid action",
"JSON error",
"Error"
};
public enum Status {
NO_RESULT,
OK,
CLASS_NOT_FOUND_EXCEPTION,
ILLEGAL_ACCESS_EXCEPTION,
INSTANTIATION_EXCEPTION,
MALFORMED_URL_EXCEPTION,
IO_EXCEPTION,
INVALID_ACTION,
JSON_EXCEPTION,
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);
} }
} }