mirror of
https://github.com/apache/cordova-android.git
synced 2025-03-13 14:41:03 +08:00
Updates.
This commit is contained in:
parent
f3e70c79eb
commit
c8fafa6bbd
@ -18,6 +18,7 @@
|
|||||||
*/
|
*/
|
||||||
package com.phonegap.api;
|
package com.phonegap.api;
|
||||||
|
|
||||||
|
import org.apache.cordova.CordovaWebView;
|
||||||
import org.apache.cordova.api.CordovaInterface;
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
|
|
||||||
import android.webkit.WebView;
|
import android.webkit.WebView;
|
||||||
@ -31,6 +32,6 @@ import android.webkit.WebView;
|
|||||||
public class PluginManager extends org.apache.cordova.api.PluginManager {
|
public class PluginManager extends org.apache.cordova.api.PluginManager {
|
||||||
|
|
||||||
public PluginManager(WebView app, CordovaInterface ctx) throws Exception {
|
public PluginManager(WebView app, CordovaInterface ctx) throws Exception {
|
||||||
super(app, ctx);
|
super((CordovaWebView) app, ctx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -27,7 +27,6 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
|
||||||
import android.hardware.Sensor;
|
import android.hardware.Sensor;
|
||||||
import android.hardware.SensorEvent;
|
import android.hardware.SensorEvent;
|
||||||
import android.hardware.SensorEventListener;
|
import android.hardware.SensorEventListener;
|
||||||
@ -47,7 +46,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
|
|||||||
|
|
||||||
public float TIMEOUT = 30000; // Timeout in msec to shut off listener
|
public float TIMEOUT = 30000; // Timeout in msec to shut off listener
|
||||||
|
|
||||||
float x,y,z; // most recent acceleration values
|
float x, y, z; // most recent acceleration values
|
||||||
long timestamp; // time of most recent value
|
long timestamp; // time of most recent value
|
||||||
int status; // status of listener
|
int status; // status of listener
|
||||||
long lastAccessTime; // time the value was last retrieved
|
long lastAccessTime; // time the value was last retrieved
|
||||||
@ -73,8 +72,9 @@ public class AccelListener extends Plugin implements SensorEventListener {
|
|||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
|
super.setContext(ctx);
|
||||||
|
this.sensorManager = (SensorManager) ctx.getActivity().getSystemService(Context.SENSOR_SERVICE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -26,7 +26,7 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
import android.webkit.WebView;
|
//import android.webkit.WebView;
|
||||||
import android.app.Activity;
|
import android.app.Activity;
|
||||||
import android.view.View;
|
import android.view.View;
|
||||||
|
|
||||||
@ -53,13 +53,18 @@ public class App extends Plugin {
|
|||||||
if (action.equals("clearCache")) {
|
if (action.equals("clearCache")) {
|
||||||
this.clearCache();
|
this.clearCache();
|
||||||
}
|
}
|
||||||
else if (action.equals("show")) {
|
else if (action.equals("show")) { // TODO @bc - Not in master branch. When should this be called?
|
||||||
final CordovaWebView wv = this.webView;
|
ctx.getActivity().runOnUiThread(new Runnable() {
|
||||||
((Activity)this.ctx).runOnUiThread(new Runnable() {
|
|
||||||
public void run() {
|
public void run() {
|
||||||
wv.setVisibility(View.VISIBLE);
|
webView.postMessage("spinner", "stop");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
// final CordovaWebView wv = this.webView;
|
||||||
|
// ((Activity) this.ctx).runOnUiThread(new Runnable() {
|
||||||
|
// public void run() {
|
||||||
|
// wv.setVisibility(View.VISIBLE);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
}
|
}
|
||||||
else if (action.equals("loadUrl")) {
|
else if (action.equals("loadUrl")) {
|
||||||
this.loadUrl(args.getString(0), args.optJSONObject(1));
|
this.loadUrl(args.getString(0), args.optJSONObject(1));
|
||||||
@ -97,7 +102,7 @@ public class App extends Plugin {
|
|||||||
* Clear the resource cache.
|
* Clear the resource cache.
|
||||||
*/
|
*/
|
||||||
public void clearCache() {
|
public void clearCache() {
|
||||||
webView.clearCache(true);
|
this.webView.clearCache(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -108,7 +113,7 @@ public class App extends Plugin {
|
|||||||
* @throws JSONException
|
* @throws JSONException
|
||||||
*/
|
*/
|
||||||
public void loadUrl(String url, JSONObject props) throws JSONException {
|
public void loadUrl(String url, JSONObject props) throws JSONException {
|
||||||
LOG.d("App", "App.loadUrl("+url+","+props+")");
|
LOG.d("App", "App.loadUrl(" + url + "," + props + ")");
|
||||||
int wait = 0;
|
int wait = 0;
|
||||||
boolean openExternal = false;
|
boolean openExternal = false;
|
||||||
boolean clearHistory = false;
|
boolean clearHistory = false;
|
||||||
@ -117,7 +122,7 @@ public class App extends Plugin {
|
|||||||
HashMap<String, Object> params = new HashMap<String, Object>();
|
HashMap<String, Object> params = new HashMap<String, Object>();
|
||||||
if (props != null) {
|
if (props != null) {
|
||||||
JSONArray keys = props.names();
|
JSONArray keys = props.names();
|
||||||
for (int i=0; i<keys.length(); i++) {
|
for (int i = 0; i < keys.length(); i++) {
|
||||||
String key = keys.getString(i);
|
String key = keys.getString(i);
|
||||||
if (key.equals("wait")) {
|
if (key.equals("wait")) {
|
||||||
wait = props.getInt(key);
|
wait = props.getInt(key);
|
||||||
@ -134,13 +139,13 @@ public class App extends Plugin {
|
|||||||
|
|
||||||
}
|
}
|
||||||
else if (value.getClass().equals(String.class)) {
|
else if (value.getClass().equals(String.class)) {
|
||||||
params.put(key, (String)value);
|
params.put(key, (String) value);
|
||||||
}
|
}
|
||||||
else if (value.getClass().equals(Boolean.class)) {
|
else if (value.getClass().equals(Boolean.class)) {
|
||||||
params.put(key, (Boolean)value);
|
params.put(key, (Boolean) value);
|
||||||
}
|
}
|
||||||
else if (value.getClass().equals(Integer.class)) {
|
else if (value.getClass().equals(Integer.class)) {
|
||||||
params.put(key, (Integer)value);
|
params.put(key, (Integer) value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -150,28 +155,28 @@ public class App extends Plugin {
|
|||||||
|
|
||||||
if (wait > 0) {
|
if (wait > 0) {
|
||||||
try {
|
try {
|
||||||
synchronized(this) {
|
synchronized (this) {
|
||||||
this.wait(wait);
|
this.wait(wait);
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
webView.showWebPage(url, openExternal, clearHistory, params);
|
this.webView.showWebPage(url, openExternal, clearHistory, params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cancel loadUrl before it has been loaded (Only works on a CordovaInterface class)
|
* Cancel loadUrl before it has been loaded (Only works on a CordovaInterface class)
|
||||||
*/
|
*/
|
||||||
public void cancelLoadUrl() {
|
public void cancelLoadUrl() {
|
||||||
((DroidGap)this.ctx).cancelLoadUrl();
|
this.ctx.cancelLoadUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear page history for the app.
|
* Clear page history for the app.
|
||||||
*/
|
*/
|
||||||
public void clearHistory() {
|
public void clearHistory() {
|
||||||
webView.clearHistory();
|
this.webView.clearHistory();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -179,7 +184,7 @@ public class App extends Plugin {
|
|||||||
* This is the same as pressing the backbutton on Android device.
|
* This is the same as pressing the backbutton on Android device.
|
||||||
*/
|
*/
|
||||||
public void backHistory() {
|
public void backHistory() {
|
||||||
webView.backHistory();
|
this.webView.backHistory();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -189,8 +194,8 @@ public class App extends Plugin {
|
|||||||
* @param override T=override, F=cancel override
|
* @param override T=override, F=cancel override
|
||||||
*/
|
*/
|
||||||
public void overrideBackbutton(boolean override) {
|
public void overrideBackbutton(boolean override) {
|
||||||
LOG.i("DroidGap", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!");
|
LOG.i("App", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!");
|
||||||
((DroidGap)this.ctx).bound = override;
|
this.ctx.bindBackButton(override);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -199,14 +204,14 @@ public class App extends Plugin {
|
|||||||
* @return boolean
|
* @return boolean
|
||||||
*/
|
*/
|
||||||
public boolean isBackbuttonOverridden() {
|
public boolean isBackbuttonOverridden() {
|
||||||
return ((DroidGap)this.ctx).bound;
|
return this.ctx.isBackButtonBound();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exit the Android application.
|
* Exit the Android application.
|
||||||
*/
|
*/
|
||||||
public void exitApp() {
|
public void exitApp() {
|
||||||
((DroidGap)this.ctx).endActivity();
|
this.ctx.getActivity().finish();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,8 @@ 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;
|
|
||||||
|
//import java.util.Map.Entry;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class called by CordovaActivity to play and record audio.
|
* This class called by CordovaActivity to play and record audio.
|
||||||
@ -45,14 +46,14 @@ import java.util.Map.Entry;
|
|||||||
public class AudioHandler extends Plugin {
|
public class AudioHandler extends Plugin {
|
||||||
|
|
||||||
public static String TAG = "AudioHandler";
|
public static String TAG = "AudioHandler";
|
||||||
HashMap<String,AudioPlayer> players; // Audio player object
|
HashMap<String, AudioPlayer> players; // Audio player object
|
||||||
ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in
|
ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor.
|
* Constructor.
|
||||||
*/
|
*/
|
||||||
public AudioHandler() {
|
public AudioHandler() {
|
||||||
this.players = new HashMap<String,AudioPlayer>();
|
this.players = new HashMap<String, AudioPlayer>();
|
||||||
this.pausedForPhone = new ArrayList<AudioPlayer>();
|
this.pausedForPhone = new ArrayList<AudioPlayer>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -283,7 +284,7 @@ public class AudioHandler extends Plugin {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
@ -300,14 +301,14 @@ public class AudioHandler extends Plugin {
|
|||||||
// 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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -316,8 +317,9 @@ public class AudioHandler extends Plugin {
|
|||||||
*
|
*
|
||||||
* @param output 1=earpiece, 2=speaker
|
* @param output 1=earpiece, 2=speaker
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
public void setAudioOutputDevice(int output) {
|
public void setAudioOutputDevice(int output) {
|
||||||
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
|
AudioManager audiMgr = (AudioManager) this.ctx.getActivity().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);
|
||||||
}
|
}
|
||||||
@ -334,8 +336,9 @@ public class AudioHandler extends Plugin {
|
|||||||
*
|
*
|
||||||
* @return 1=earpiece, 2=speaker
|
* @return 1=earpiece, 2=speaker
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
public int getAudioOutputDevice() {
|
public int getAudioOutputDevice() {
|
||||||
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
|
AudioManager audiMgr = (AudioManager) this.ctx.getActivity().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;
|
||||||
}
|
}
|
||||||
|
@ -60,9 +60,9 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
// Media error codes
|
// Media error codes
|
||||||
private static int MEDIA_ERR_NONE_ACTIVE = 0;
|
private static int MEDIA_ERR_NONE_ACTIVE = 0;
|
||||||
private static int MEDIA_ERR_ABORTED = 1;
|
private static int MEDIA_ERR_ABORTED = 1;
|
||||||
private static int MEDIA_ERR_NETWORK = 2;
|
// private static int MEDIA_ERR_NETWORK = 2;
|
||||||
private static int MEDIA_ERR_DECODE = 3;
|
// private static int MEDIA_ERR_DECODE = 3;
|
||||||
private static int MEDIA_ERR_NONE_SUPPORTED = 4;
|
// private static int MEDIA_ERR_NONE_SUPPORTED = 4;
|
||||||
|
|
||||||
private AudioHandler handler; // The AudioHandler object
|
private AudioHandler handler; // The AudioHandler object
|
||||||
private String id; // The id of this player (used to identify Media object in JavaScript)
|
private String id; // The id of this player (used to identify Media object in JavaScript)
|
||||||
@ -117,7 +117,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
public void startRecording(String file) {
|
public void startRecording(String file) {
|
||||||
if (this.mPlayer != null) {
|
if (this.mPlayer != null) {
|
||||||
Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
|
Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure we're not already recording
|
// Make sure we're not already recording
|
||||||
@ -138,11 +138,11 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Log.d(LOG_TAG, "AudioPlayer Error: Already recording.");
|
Log.d(LOG_TAG, "AudioPlayer Error: Already recording.");
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -163,14 +163,13 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
*/
|
*/
|
||||||
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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -184,7 +183,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
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
|
||||||
@ -213,7 +212,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
else {
|
else {
|
||||||
if (file.startsWith("/android_asset/")) {
|
if (file.startsWith("/android_asset/")) {
|
||||||
String f = file.substring(15);
|
String f = file.substring(15);
|
||||||
android.content.res.AssetFileDescriptor fd = this.handler.ctx.getAssets().openFd(f);
|
android.content.res.AssetFileDescriptor fd = this.handler.ctx.getActivity().getAssets().openFd(f);
|
||||||
this.mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
|
this.mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@ -233,10 +232,9 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
// 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 + "});");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,8 +247,8 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
this.setState(MEDIA_RUNNING);
|
this.setState(MEDIA_RUNNING);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: "+this.state);
|
Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -262,7 +260,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
if (this.mPlayer != null) {
|
if (this.mPlayer != null) {
|
||||||
this.mPlayer.seekTo(milliseconds);
|
this.mPlayer.seekTo(milliseconds);
|
||||||
Log.d(LOG_TAG, "Send a onStatus update for the new seek");
|
Log.d(LOG_TAG, "Send a onStatus update for the new seek");
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+milliseconds/1000.0f+");");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + milliseconds / 1000.0f + ");");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -277,8 +275,8 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
this.setState(MEDIA_PAUSED);
|
this.setState(MEDIA_PAUSED);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: "+this.state);
|
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state);
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -291,8 +289,8 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
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 + "});");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -313,7 +311,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
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 {
|
||||||
@ -349,7 +347,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
|
|
||||||
// Can't get duration of recording
|
// Can't get duration of recording
|
||||||
if (this.recorder != null) {
|
if (this.recorder != null) {
|
||||||
return(-2); // not allowed
|
return (-2); // not allowed
|
||||||
}
|
}
|
||||||
|
|
||||||
// If audio file already loaded and started, then return duration
|
// If audio file already loaded and started, then return duration
|
||||||
@ -392,7 +390,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
this.prepareOnly = false;
|
this.prepareOnly = false;
|
||||||
|
|
||||||
// Send status notification to JavaScript
|
// Send status notification to JavaScript
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_DURATION+","+this.duration+");");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_DURATION + "," + this.duration + ");");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -414,14 +412,14 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
* @param arg2 an extra code, specific to the error.
|
* @param arg2 an extra code, specific to the error.
|
||||||
*/
|
*/
|
||||||
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
|
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
|
||||||
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")");
|
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");
|
||||||
|
|
||||||
// TODO: Not sure if this needs to be sent?
|
// TODO: Not sure if this needs to be sent?
|
||||||
this.mPlayer.stop();
|
this.mPlayer.stop();
|
||||||
this.mPlayer.release();
|
this.mPlayer.release();
|
||||||
|
|
||||||
// Send error notification to JavaScript
|
// Send error notification to JavaScript
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":"+arg1+"});");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":" + arg1 + "});");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -432,7 +430,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
|
|||||||
*/
|
*/
|
||||||
private void setState(int state) {
|
private void setState(int state) {
|
||||||
if (this.state != state) {
|
if (this.state != state) {
|
||||||
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");");
|
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + state + ");");
|
||||||
}
|
}
|
||||||
|
|
||||||
this.state = state;
|
this.state = state;
|
||||||
|
@ -24,7 +24,6 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
|
||||||
import android.content.BroadcastReceiver;
|
import android.content.BroadcastReceiver;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
@ -65,7 +64,7 @@ public class BatteryListener extends Plugin {
|
|||||||
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
|
||||||
IntentFilter intentFilter = new IntentFilter() ;
|
IntentFilter intentFilter = new IntentFilter();
|
||||||
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
|
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
|
||||||
if (this.receiver == null) {
|
if (this.receiver == null) {
|
||||||
this.receiver = new BroadcastReceiver() {
|
this.receiver = new BroadcastReceiver() {
|
||||||
@ -74,7 +73,7 @@ public class BatteryListener extends Plugin {
|
|||||||
updateBatteryInfo(intent);
|
updateBatteryInfo(intent);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
ctx.registerReceiver(this.receiver, intentFilter);
|
ctx.getActivity().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
|
||||||
@ -106,7 +105,7 @@ public class BatteryListener extends Plugin {
|
|||||||
private void removeBatteryListener() {
|
private void removeBatteryListener() {
|
||||||
if (this.receiver != null) {
|
if (this.receiver != null) {
|
||||||
try {
|
try {
|
||||||
this.ctx.unregisterReceiver(this.receiver);
|
this.ctx.getActivity().unregisterReceiver(this.receiver);
|
||||||
this.receiver = null;
|
this.receiver = null;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
|
Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);
|
||||||
|
@ -26,7 +26,7 @@ import java.io.IOException;
|
|||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
|
||||||
import org.apache.commons.codec.binary.Base64;
|
import org.apache.commons.codec.binary.Base64;
|
||||||
import org.apache.cordova.api.CordovaInterface;
|
//import org.apache.cordova.api.CordovaInterface;
|
||||||
import org.apache.cordova.api.LOG;
|
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;
|
||||||
@ -35,7 +35,7 @@ import org.json.JSONException;
|
|||||||
|
|
||||||
import android.app.Activity;
|
import android.app.Activity;
|
||||||
import android.content.ContentValues;
|
import android.content.ContentValues;
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.database.Cursor;
|
import android.database.Cursor;
|
||||||
import android.graphics.Bitmap;
|
import android.graphics.Bitmap;
|
||||||
@ -81,7 +81,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
private int numPics;
|
private int numPics;
|
||||||
|
|
||||||
//This should never be null!
|
//This should never be null!
|
||||||
private CordovaInterface cordova;
|
//private CordovaInterface cordova;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor.
|
* Constructor.
|
||||||
@ -89,13 +89,13 @@ public class CameraLauncher extends Plugin {
|
|||||||
public CameraLauncher() {
|
public CameraLauncher() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContext(Context mCtx) {
|
// public void setContext(CordovaInterface mCtx) {
|
||||||
super.setContext(mCtx);
|
// super.setContext(mCtx);
|
||||||
if(CordovaInterface.class.isInstance(mCtx))
|
// if (CordovaInterface.class.isInstance(mCtx))
|
||||||
cordova = (CordovaInterface) mCtx;
|
// cordova = (CordovaInterface) mCtx;
|
||||||
else
|
// else
|
||||||
LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes the request and returns PluginResult.
|
* Executes the request and returns PluginResult.
|
||||||
@ -176,10 +176,11 @@ public class CameraLauncher extends Plugin {
|
|||||||
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
|
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
|
||||||
this.imageUri = Uri.fromFile(photo);
|
this.imageUri = Uri.fromFile(photo);
|
||||||
|
|
||||||
if(cordova != null)
|
if (this.ctx != null) {
|
||||||
cordova.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
|
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
|
||||||
else
|
}
|
||||||
LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
// else
|
||||||
|
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -191,9 +192,9 @@ public class CameraLauncher extends Plugin {
|
|||||||
private File createCaptureFile(int encodingType) {
|
private File createCaptureFile(int encodingType) {
|
||||||
File photo = null;
|
File photo = null;
|
||||||
if (encodingType == JPEG) {
|
if (encodingType == JPEG) {
|
||||||
photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.jpg");
|
photo = new File(DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()), "Pic.jpg");
|
||||||
} else if (encodingType == PNG) {
|
} else if (encodingType == PNG) {
|
||||||
photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Pic.png");
|
photo = new File(DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()), "Pic.png");
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
|
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
|
||||||
}
|
}
|
||||||
@ -227,8 +228,10 @@ public class CameraLauncher extends Plugin {
|
|||||||
|
|
||||||
intent.setAction(Intent.ACTION_GET_CONTENT);
|
intent.setAction(Intent.ACTION_GET_CONTENT);
|
||||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||||
cordova.startActivityForResult((Plugin) this, Intent.createChooser(intent,
|
if (this.ctx != null) {
|
||||||
new String(title)), (srcType+1)*16 + returnType + 1);
|
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
|
||||||
|
new String(title)), (srcType + 1) * 16 + returnType + 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -262,8 +265,8 @@ public class CameraLauncher extends Plugin {
|
|||||||
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
|
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
|
||||||
// would result in whitespace in the new image.
|
// would result in whitespace in the new image.
|
||||||
else {
|
else {
|
||||||
double newRatio = newWidth / (double)newHeight;
|
double newRatio = newWidth / (double) newHeight;
|
||||||
double origRatio = origWidth / (double)origHeight;
|
double origRatio = origWidth / (double) origHeight;
|
||||||
|
|
||||||
if (origRatio > newRatio) {
|
if (origRatio > newRatio) {
|
||||||
newHeight = (newWidth * origHeight) / origWidth;
|
newHeight = (newWidth * origHeight) / origWidth;
|
||||||
@ -286,7 +289,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
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;
|
||||||
|
|
||||||
@ -294,7 +297,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
ExifHelper exif = new ExifHelper();
|
ExifHelper exif = new ExifHelper();
|
||||||
try {
|
try {
|
||||||
if (this.encodingType == JPEG) {
|
if (this.encodingType == JPEG) {
|
||||||
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Pic.jpg");
|
exif.createInFile(DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()) + "/Pic.jpg");
|
||||||
exif.readExifData();
|
exif.readExifData();
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
@ -309,10 +312,10 @@ public class CameraLauncher extends Plugin {
|
|||||||
// Read in bitmap of captured image
|
// Read in bitmap of captured image
|
||||||
Bitmap bitmap;
|
Bitmap bitmap;
|
||||||
try {
|
try {
|
||||||
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
|
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getActivity().getContentResolver(), imageUri);
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
Uri uri = intent.getData();
|
Uri uri = intent.getData();
|
||||||
android.content.ContentResolver resolver = this.ctx.getContentResolver();
|
android.content.ContentResolver resolver = this.ctx.getActivity().getContentResolver();
|
||||||
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
|
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -325,18 +328,18 @@ public class CameraLauncher extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If sending filename back
|
// If sending filename back
|
||||||
else if (destType == FILE_URI){
|
else if (destType == FILE_URI) {
|
||||||
// Create entry in media store for image
|
// Create entry in media store for image
|
||||||
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
||||||
ContentValues values = new ContentValues();
|
ContentValues values = new ContentValues();
|
||||||
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
|
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
|
||||||
Uri uri = null;
|
Uri uri = null;
|
||||||
try {
|
try {
|
||||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
uri = this.ctx.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
LOG.d(LOG_TAG, "Can't write to external media storage.");
|
LOG.d(LOG_TAG, "Can't write to external media storage.");
|
||||||
try {
|
try {
|
||||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
|
uri = this.ctx.getActivity().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.");
|
||||||
@ -345,13 +348,13 @@ public class CameraLauncher extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add compressed version of captured image to returned media store Uri
|
// Add compressed version of captured image to returned media store Uri
|
||||||
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
|
OutputStream os = this.ctx.getActivity().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, ((Activity) this.ctx)));
|
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
|
||||||
exif.writeExifData();
|
exif.writeExifData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -384,7 +387,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
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.getActivity().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
|
||||||
@ -397,7 +400,7 @@ 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.getActivity().getContentResolver().query(intent.getData(),
|
||||||
cols,
|
cols,
|
||||||
null, null, null);
|
null, null, null);
|
||||||
if (cursor != null) {
|
if (cursor != null) {
|
||||||
@ -408,7 +411,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
if (rotate != 0) {
|
if (rotate != 0) {
|
||||||
Matrix matrix = new Matrix();
|
Matrix matrix = new Matrix();
|
||||||
matrix.setRotate(rotate);
|
matrix.setRotate(rotate);
|
||||||
bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
|
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
|
||||||
}
|
}
|
||||||
bitmap = scaleBitmap(bitmap);
|
bitmap = scaleBitmap(bitmap);
|
||||||
this.processPicture(bitmap);
|
this.processPicture(bitmap);
|
||||||
@ -429,14 +432,14 @@ public class CameraLauncher extends Plugin {
|
|||||||
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) + "/resize.jpg";
|
String fileName = DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()) + "/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, ((Activity) ctx)));
|
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
|
||||||
exif.writeExifData();
|
exif.writeExifData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -473,7 +476,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
* @return a cursor
|
* @return a cursor
|
||||||
*/
|
*/
|
||||||
private Cursor queryImgDB() {
|
private Cursor queryImgDB() {
|
||||||
return this.ctx.getContentResolver().query(
|
return this.ctx.getActivity().getContentResolver().query(
|
||||||
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||||
new String[] { MediaStore.Images.Media._ID },
|
new String[] { MediaStore.Images.Media._ID },
|
||||||
null,
|
null,
|
||||||
@ -502,7 +505,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
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.getActivity().getContentResolver().delete(uri, null, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -523,8 +526,7 @@ public class CameraLauncher extends Plugin {
|
|||||||
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;
|
||||||
|
@ -32,7 +32,7 @@ import org.json.JSONObject;
|
|||||||
|
|
||||||
import android.app.Activity;
|
import android.app.Activity;
|
||||||
import android.content.ContentValues;
|
import android.content.ContentValues;
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.graphics.Bitmap;
|
import android.graphics.Bitmap;
|
||||||
import android.graphics.BitmapFactory;
|
import android.graphics.BitmapFactory;
|
||||||
@ -40,7 +40,6 @@ import android.media.MediaPlayer;
|
|||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
|
||||||
public class Capture extends Plugin {
|
public class Capture extends Plugin {
|
||||||
|
|
||||||
private static final String VIDEO_3GPP = "video/3gpp";
|
private static final String VIDEO_3GPP = "video/3gpp";
|
||||||
@ -54,25 +53,26 @@ public class Capture extends Plugin {
|
|||||||
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
|
||||||
private CordovaInterface cordova;
|
|
||||||
|
|
||||||
public void setContext(Context mCtx)
|
//private CordovaInterface cordova;
|
||||||
{
|
|
||||||
if(CordovaInterface.class.isInstance(mCtx))
|
// public void setContext(Context mCtx)
|
||||||
cordova = (CordovaInterface) mCtx;
|
// {
|
||||||
else
|
// if (CordovaInterface.class.isInstance(mCtx))
|
||||||
LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
// cordova = (CordovaInterface) mCtx;
|
||||||
}
|
// else
|
||||||
|
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
|
||||||
|
// }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PluginResult execute(String action, JSONArray args, String callbackId) {
|
public PluginResult execute(String action, JSONArray args, String callbackId) {
|
||||||
@ -143,8 +143,7 @@ public class Capture extends Plugin {
|
|||||||
else if (mimeType.equals(VIDEO_3GPP) || mimeType.equals(VIDEO_MP4)) {
|
else if (mimeType.equals(VIDEO_3GPP) || mimeType.equals(VIDEO_MP4)) {
|
||||||
obj = getAudioVideoData(filePath, obj, true);
|
obj = getAudioVideoData(filePath, obj, true);
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Error: setting media file data object");
|
Log.d(LOG_TAG, "Error: setting media file data object");
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
@ -179,13 +178,12 @@ public class Capture extends Plugin {
|
|||||||
try {
|
try {
|
||||||
player.setDataSource(filePath);
|
player.setDataSource(filePath);
|
||||||
player.prepare();
|
player.prepare();
|
||||||
obj.put("duration", player.getDuration()/1000);
|
obj.put("duration", player.getDuration() / 1000);
|
||||||
if (video) {
|
if (video) {
|
||||||
obj.put("height", player.getVideoHeight());
|
obj.put("height", player.getVideoHeight());
|
||||||
obj.put("width", player.getVideoWidth());
|
obj.put("width", player.getVideoWidth());
|
||||||
}
|
}
|
||||||
}
|
} 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;
|
||||||
@ -197,7 +195,7 @@ public class Capture extends Plugin {
|
|||||||
private void captureAudio() {
|
private void captureAudio() {
|
||||||
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
|
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
|
||||||
|
|
||||||
cordova.startActivityForResult((Plugin) this, intent, CAPTURE_AUDIO);
|
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_AUDIO);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -207,11 +205,11 @@ public class Capture extends Plugin {
|
|||||||
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
|
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
|
||||||
|
|
||||||
// Specify file so that large image is captured and returned
|
// Specify file so that large image is captured and returned
|
||||||
File photo = new File(DirectoryManager.getTempDirectoryPath(ctx), "Capture.jpg");
|
File photo = new File(DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()), "Capture.jpg");
|
||||||
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
|
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
|
||||||
this.imageUri = Uri.fromFile(photo);
|
this.imageUri = Uri.fromFile(photo);
|
||||||
|
|
||||||
cordova.startActivityForResult((Plugin) this, intent, CAPTURE_IMAGE);
|
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_IMAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -222,7 +220,7 @@ public class Capture extends Plugin {
|
|||||||
// Introduced in API 8
|
// Introduced in API 8
|
||||||
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration);
|
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration);
|
||||||
|
|
||||||
cordova.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO);
|
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -260,11 +258,11 @@ public class Capture extends Plugin {
|
|||||||
try {
|
try {
|
||||||
// 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();
|
||||||
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Capture.jpg");
|
exif.createInFile(DirectoryManager.getTempDirectoryPath(this.ctx.getActivity()) + "/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.getActivity().getContentResolver(), imageUri);
|
||||||
|
|
||||||
// Create entry in media store for image
|
// Create entry in media store for image
|
||||||
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
||||||
@ -272,11 +270,11 @@ public class Capture extends Plugin {
|
|||||||
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
|
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
|
||||||
Uri uri = null;
|
Uri uri = null;
|
||||||
try {
|
try {
|
||||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
uri = this.ctx.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
||||||
} catch (UnsupportedOperationException e) {
|
} catch (UnsupportedOperationException e) {
|
||||||
LOG.d(LOG_TAG, "Can't write to external media storage.");
|
LOG.d(LOG_TAG, "Can't write to external media storage.");
|
||||||
try {
|
try {
|
||||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
|
uri = this.ctx.getActivity().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."));
|
||||||
@ -285,7 +283,7 @@ public class Capture extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add compressed version of captured image to returned media store Uri
|
// Add compressed version of captured image to returned media store Uri
|
||||||
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
|
OutputStream os = this.ctx.getActivity().getContentResolver().openOutputStream(uri);
|
||||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
|
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
|
||||||
os.close();
|
os.close();
|
||||||
|
|
||||||
@ -294,7 +292,7 @@ public class Capture extends Plugin {
|
|||||||
System.gc();
|
System.gc();
|
||||||
|
|
||||||
// Restore exif data to file
|
// Restore exif data to file
|
||||||
exif.createOutFile(FileUtils.getRealPathFromURI(uri, ((Activity) this.ctx)));
|
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
|
||||||
exif.writeExifData();
|
exif.writeExifData();
|
||||||
|
|
||||||
// Add image to results
|
// Add image to results
|
||||||
@ -357,8 +355,8 @@ public class Capture extends Plugin {
|
|||||||
* @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, ((Activity) this.ctx)));
|
File fp = new File(FileUtils.getRealPathFromURI(data, this.ctx));
|
||||||
JSONObject obj = new JSONObject();
|
JSONObject obj = new JSONObject();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -27,7 +27,6 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
|
||||||
import android.hardware.Sensor;
|
import android.hardware.Sensor;
|
||||||
import android.hardware.SensorEvent;
|
import android.hardware.SensorEvent;
|
||||||
import android.hardware.SensorEventListener;
|
import android.hardware.SensorEventListener;
|
||||||
@ -70,9 +69,9 @@ public class CompassListener extends Plugin implements SensorEventListener {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
super.setContext(ctx);
|
super.setContext(ctx);
|
||||||
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
|
this.sensorManager = (SensorManager) ctx.getActivity().getSystemService(Context.SENSOR_SERVICE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -184,6 +183,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get compass sensor from sensor manager
|
// Get compass sensor from sensor manager
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
|
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
|
||||||
|
|
||||||
// If found, then register as listener
|
// If found, then register as listener
|
||||||
@ -212,7 +212,6 @@ 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
|
||||||
}
|
}
|
||||||
|
@ -18,11 +18,12 @@ package org.apache.cordova;
|
|||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
|
||||||
import android.app.Activity;
|
//import android.app.Activity;
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
import android.webkit.WebView;
|
import android.webkit.WebView;
|
||||||
|
|
||||||
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
import org.json.JSONArray;
|
import org.json.JSONArray;
|
||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
@ -37,7 +38,7 @@ import org.json.JSONObject;
|
|||||||
public abstract class ContactAccessor {
|
public abstract class ContactAccessor {
|
||||||
|
|
||||||
protected final String LOG_TAG = "ContactsAccessor";
|
protected final String LOG_TAG = "ContactsAccessor";
|
||||||
protected Context mApp;
|
protected CordovaInterface mApp;
|
||||||
protected WebView mView;
|
protected WebView mView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -47,7 +48,7 @@ public abstract class ContactAccessor {
|
|||||||
* @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
|
||||||
*/
|
*/
|
||||||
protected boolean isRequired(String key, HashMap<String,Boolean> map) {
|
protected boolean isRequired(String key, HashMap<String, Boolean> map) {
|
||||||
Boolean retVal = map.get(key);
|
Boolean retVal = map.get(key);
|
||||||
return (retVal == null) ? false : retVal.booleanValue();
|
return (retVal == null) ? false : retVal.booleanValue();
|
||||||
}
|
}
|
||||||
@ -57,8 +58,8 @@ public abstract class ContactAccessor {
|
|||||||
* @param fields the list of fields to populate
|
* @param fields the list of fields to populate
|
||||||
* @return the hash map of required data
|
* @return the hash map of required data
|
||||||
*/
|
*/
|
||||||
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 {
|
||||||
@ -78,7 +79,7 @@ public abstract class ContactAccessor {
|
|||||||
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);
|
||||||
if (key.startsWith("displayName")) {
|
if (key.startsWith("displayName")) {
|
||||||
map.put("displayName", true);
|
map.put("displayName", true);
|
||||||
@ -122,8 +123,7 @@ public abstract class ContactAccessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.e(LOG_TAG, e.getMessage(), e);
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
@ -148,8 +148,7 @@ public abstract class ContactAccessor {
|
|||||||
value = null;
|
value = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} 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;
|
||||||
@ -183,15 +182,19 @@ public abstract class ContactAccessor {
|
|||||||
class WhereOptions {
|
class WhereOptions {
|
||||||
private String where;
|
private String where;
|
||||||
private String[] whereArgs;
|
private String[] whereArgs;
|
||||||
|
|
||||||
public void setWhere(String where) {
|
public void setWhere(String where) {
|
||||||
this.where = where;
|
this.where = where;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getWhere() {
|
public String getWhere() {
|
||||||
return where;
|
return where;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setWhereArgs(String[] whereArgs) {
|
public void setWhereArgs(String[] whereArgs) {
|
||||||
this.whereArgs = whereArgs;
|
this.whereArgs = whereArgs;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String[] getWhereArgs() {
|
public String[] getWhereArgs() {
|
||||||
return whereArgs;
|
return whereArgs;
|
||||||
}
|
}
|
||||||
|
@ -32,18 +32,19 @@ import java.util.Iterator;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
import org.json.JSONArray;
|
import org.json.JSONArray;
|
||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
import android.accounts.Account;
|
import android.accounts.Account;
|
||||||
import android.accounts.AccountManager;
|
import android.accounts.AccountManager;
|
||||||
import android.app.Activity;
|
//import android.app.Activity;
|
||||||
import android.content.ContentProviderOperation;
|
import android.content.ContentProviderOperation;
|
||||||
import android.content.ContentProviderResult;
|
import android.content.ContentProviderResult;
|
||||||
import android.content.ContentUris;
|
import android.content.ContentUris;
|
||||||
import android.content.ContentValues;
|
import android.content.ContentValues;
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.OperationApplicationException;
|
import android.content.OperationApplicationException;
|
||||||
import android.database.Cursor;
|
import android.database.Cursor;
|
||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
@ -122,7 +123,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
/**
|
/**
|
||||||
* Create an contact accessor.
|
* Create an contact accessor.
|
||||||
*/
|
*/
|
||||||
public ContactAccessorSdk5(WebView view, Context context) {
|
public ContactAccessorSdk5(WebView view, CordovaInterface context) {
|
||||||
mApp = context;
|
mApp = context;
|
||||||
mView = view;
|
mView = view;
|
||||||
}
|
}
|
||||||
@ -143,7 +144,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
|
|
||||||
if (options != null) {
|
if (options != null) {
|
||||||
searchTerm = options.optString("filter");
|
searchTerm = options.optString("filter");
|
||||||
if (searchTerm.length()==0) {
|
if (searchTerm.length() == 0) {
|
||||||
searchTerm = "%";
|
searchTerm = "%";
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@ -167,13 +168,13 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
//Log.d(LOG_TAG, "Fields = " + fields.toString());
|
//Log.d(LOG_TAG, "Fields = " + fields.toString());
|
||||||
|
|
||||||
// Loop through the fields the user provided to see what data should be returned.
|
// Loop through the fields the user provided to see what data should be returned.
|
||||||
HashMap<String,Boolean> populate = buildPopulationSet(fields);
|
HashMap<String, Boolean> populate = buildPopulationSet(fields);
|
||||||
|
|
||||||
// Build the ugly where clause and where arguments for one big query.
|
// Build the ugly where clause and where arguments for one big query.
|
||||||
WhereOptions whereOptions = buildWhereClause(fields, searchTerm);
|
WhereOptions whereOptions = buildWhereClause(fields, searchTerm);
|
||||||
|
|
||||||
// Get all the id's where the search term matches the fields passed in.
|
// Get all the id's where the search term matches the fields passed in.
|
||||||
Cursor idCursor = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
Cursor idCursor = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
||||||
new String[] { ContactsContract.Data.CONTACT_ID },
|
new String[] { ContactsContract.Data.CONTACT_ID },
|
||||||
whereOptions.getWhere(),
|
whereOptions.getWhere(),
|
||||||
whereOptions.getWhereArgs(),
|
whereOptions.getWhereArgs(),
|
||||||
@ -191,7 +192,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
WhereOptions idOptions = buildIdClause(contactIds, searchTerm);
|
WhereOptions idOptions = buildIdClause(contactIds, searchTerm);
|
||||||
|
|
||||||
// Do the id query
|
// Do the id query
|
||||||
Cursor c = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
||||||
null,
|
null,
|
||||||
idOptions.getWhere(),
|
idOptions.getWhere(),
|
||||||
idOptions.getWhereArgs(),
|
idOptions.getWhereArgs(),
|
||||||
@ -210,7 +211,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
public JSONObject getContactById(String id) throws JSONException {
|
public JSONObject getContactById(String id) throws JSONException {
|
||||||
// Do the id query
|
// Do the id query
|
||||||
Cursor c = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
|
||||||
null,
|
null,
|
||||||
ContactsContract.Data.CONTACT_ID + " = ? ",
|
ContactsContract.Data.CONTACT_ID + " = ? ",
|
||||||
new String[] { id },
|
new String[] { id },
|
||||||
@ -219,7 +220,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
JSONArray fields = new JSONArray();
|
JSONArray fields = new JSONArray();
|
||||||
fields.put("*");
|
fields.put("*");
|
||||||
|
|
||||||
HashMap<String,Boolean> populate = buildPopulationSet(fields);
|
HashMap<String, Boolean> populate = buildPopulationSet(fields);
|
||||||
|
|
||||||
JSONArray contacts = populateContactArray(1, populate, c);
|
JSONArray contacts = populateContactArray(1, populate, c);
|
||||||
|
|
||||||
@ -258,7 +259,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
JSONArray photos = new JSONArray();
|
JSONArray photos = new JSONArray();
|
||||||
|
|
||||||
if (c.getCount() > 0) {
|
if (c.getCount() > 0) {
|
||||||
while (c.moveToNext() && (contacts.length() <= (limit-1))) {
|
while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
|
||||||
try {
|
try {
|
||||||
contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
|
contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
|
||||||
rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
|
rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
|
||||||
@ -305,54 +306,53 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
contact.put("displayName", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
|
contact.put("displayName", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
|
||||||
}
|
}
|
||||||
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
|
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("name",populate)) {
|
&& isRequired("name", populate)) {
|
||||||
contact.put("name", nameQuery(c));
|
contact.put("name", nameQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("phoneNumbers",populate)) {
|
&& isRequired("phoneNumbers", populate)) {
|
||||||
phones.put(phoneQuery(c));
|
phones.put(phoneQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("emails",populate)) {
|
&& isRequired("emails", populate)) {
|
||||||
emails.put(emailQuery(c));
|
emails.put(emailQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("addresses",populate)) {
|
&& isRequired("addresses", populate)) {
|
||||||
addresses.put(addressQuery(c));
|
addresses.put(addressQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("organizations",populate)) {
|
&& isRequired("organizations", populate)) {
|
||||||
organizations.put(organizationQuery(c));
|
organizations.put(organizationQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("ims",populate)) {
|
&& isRequired("ims", populate)) {
|
||||||
ims.put(imQuery(c));
|
ims.put(imQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("note",populate)) {
|
&& isRequired("note", populate)) {
|
||||||
contact.put("note",c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
|
contact.put("note", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("nickname",populate)) {
|
&& isRequired("nickname", populate)) {
|
||||||
contact.put("nickname",c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
|
contact.put("nickname", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("urls",populate)) {
|
&& isRequired("urls", populate)) {
|
||||||
websites.put(websiteQuery(c));
|
websites.put(websiteQuery(c));
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
|
||||||
if (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
|
if (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
|
||||||
&& isRequired("birthday",populate)) {
|
&& isRequired("birthday", populate)) {
|
||||||
contact.put("birthday", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
|
contact.put("birthday", c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
|
else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
|
||||||
&& isRequired("photos",populate)) {
|
&& isRequired("photos", populate)) {
|
||||||
photos.put(photoQuery(c, contactId));
|
photos.put(photoQuery(c, contactId));
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
Log.e(LOG_TAG, e.getMessage(),e);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the old contact ID
|
// Set the old contact ID
|
||||||
@ -382,7 +382,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
// and return a shorter where clause to be searched.
|
// and return a shorter where clause to be searched.
|
||||||
if (searchTerm.equals("%")) {
|
if (searchTerm.equals("%")) {
|
||||||
options.setWhere("(" + ContactsContract.Data.CONTACT_ID + " LIKE ? )");
|
options.setWhere("(" + ContactsContract.Data.CONTACT_ID + " LIKE ? )");
|
||||||
options.setWhereArgs(new String[] {searchTerm});
|
options.setWhereArgs(new String[] { searchTerm });
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -442,9 +442,8 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
if (photos.length() > 0) {
|
if (photos.length() > 0) {
|
||||||
contact.put("photos", photos);
|
contact.put("photos", photos);
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
Log.e(LOG_TAG,e.getMessage(),e);
|
|
||||||
}
|
}
|
||||||
return contact;
|
return contact;
|
||||||
}
|
}
|
||||||
@ -469,7 +468,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
// Get all contacts with all properties
|
// Get all contacts with all properties
|
||||||
if ("%".equals(searchTerm)) {
|
if ("%".equals(searchTerm)) {
|
||||||
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
|
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
|
||||||
options.setWhereArgs(new String[] {searchTerm});
|
options.setWhereArgs(new String[] { searchTerm });
|
||||||
return options;
|
return options;
|
||||||
} else {
|
} else {
|
||||||
// Get all contacts that match the filter but return all properties
|
// Get all contacts that match the filter but return all properties
|
||||||
@ -519,19 +518,19 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
if ("%".equals(searchTerm)) {
|
if ("%".equals(searchTerm)) {
|
||||||
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
|
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
|
||||||
options.setWhereArgs(new String[] {searchTerm});
|
options.setWhereArgs(new String[] { searchTerm });
|
||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
String key;
|
String key;
|
||||||
try {
|
try {
|
||||||
//Log.d(LOG_TAG, "How many fields do we have = " + fields.length());
|
//Log.d(LOG_TAG, "How many fields do we have = " + fields.length());
|
||||||
for (int i=0; i<fields.length(); i++) {
|
for (int i = 0; i < fields.length(); i++) {
|
||||||
key = fields.getString(i);
|
key = fields.getString(i);
|
||||||
|
|
||||||
if (key.equals("id")) {
|
if (key.equals("id")) {
|
||||||
where.add("(" + dbMap.get(key) + " = ? )");
|
where.add("(" + dbMap.get(key) + " = ? )");
|
||||||
whereArgs.add(searchTerm.substring(1, searchTerm.length()-1));
|
whereArgs.add(searchTerm.substring(1, searchTerm.length() - 1));
|
||||||
}
|
}
|
||||||
else if (key.startsWith("displayName")) {
|
else if (key.startsWith("displayName")) {
|
||||||
where.add("(" + dbMap.get(key) + " LIKE ? )");
|
where.add("(" + dbMap.get(key) + " LIKE ? )");
|
||||||
@ -579,7 +578,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
whereArgs.add(searchTerm);
|
whereArgs.add(searchTerm);
|
||||||
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
|
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
|
||||||
}
|
}
|
||||||
// else if (key.startsWith("birthday")) {
|
// else if (key.startsWith("birthday")) {
|
||||||
// where.add("(" + dbMap.get(key) + " LIKE ? AND "
|
// where.add("(" + dbMap.get(key) + " LIKE ? AND "
|
||||||
// + ContactsContract.Data.MIMETYPE + " = ? )");
|
// + ContactsContract.Data.MIMETYPE + " = ? )");
|
||||||
// }
|
// }
|
||||||
@ -596,16 +595,15 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
|
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.e(LOG_TAG, e.getMessage(), e);
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creating the where string
|
// Creating the where string
|
||||||
StringBuffer selection = new StringBuffer();
|
StringBuffer selection = new StringBuffer();
|
||||||
for (int i=0; i<where.size(); i++) {
|
for (int i = 0; i < where.size(); i++) {
|
||||||
selection.append(where.get(i));
|
selection.append(where.get(i));
|
||||||
if (i != (where.size()-1)) {
|
if (i != (where.size() - 1)) {
|
||||||
selection.append(" OR ");
|
selection.append(" OR ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -613,7 +611,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
|
|
||||||
// Creating the where args array
|
// Creating the where args array
|
||||||
String[] selectionArgs = new String[whereArgs.size()];
|
String[] selectionArgs = new String[whereArgs.size()];
|
||||||
for (int i=0; i<whereArgs.size(); i++) {
|
for (int i = 0; i < whereArgs.size(); i++) {
|
||||||
selectionArgs[i] = whereArgs.get(i);
|
selectionArgs[i] = whereArgs.get(i);
|
||||||
}
|
}
|
||||||
options.setWhereArgs(selectionArgs);
|
options.setWhereArgs(selectionArgs);
|
||||||
@ -700,11 +698,21 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
|
|
||||||
// Create the formatted name
|
// Create the formatted name
|
||||||
StringBuffer formatted = new StringBuffer("");
|
StringBuffer formatted = new StringBuffer("");
|
||||||
if (honorificPrefix != null) { formatted.append(honorificPrefix + " "); }
|
if (honorificPrefix != null) {
|
||||||
if (givenName != null) { formatted.append(givenName + " "); }
|
formatted.append(honorificPrefix + " ");
|
||||||
if (middleName != null) { formatted.append(middleName + " "); }
|
}
|
||||||
if (familyName != null) { formatted.append(familyName + " "); }
|
if (givenName != null) {
|
||||||
if (honorificSuffix != null) { formatted.append(honorificSuffix + " "); }
|
formatted.append(givenName + " ");
|
||||||
|
}
|
||||||
|
if (middleName != null) {
|
||||||
|
formatted.append(middleName + " ");
|
||||||
|
}
|
||||||
|
if (familyName != null) {
|
||||||
|
formatted.append(familyName + " ");
|
||||||
|
}
|
||||||
|
if (honorificSuffix != null) {
|
||||||
|
formatted.append(honorificSuffix + " ");
|
||||||
|
}
|
||||||
|
|
||||||
contactName.put("familyName", familyName);
|
contactName.put("familyName", familyName);
|
||||||
contactName.put("givenName", givenName);
|
contactName.put("givenName", givenName);
|
||||||
@ -732,8 +740,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
phoneNumber.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
|
phoneNumber.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
|
||||||
} catch (JSONException e) {
|
} catch (JSONException e) {
|
||||||
Log.e(LOG_TAG, e.getMessage(), e);
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
}
|
} catch (Exception excp) {
|
||||||
catch (Exception excp) {
|
|
||||||
Log.e(LOG_TAG, excp.getMessage(), excp);
|
Log.e(LOG_TAG, excp.getMessage(), excp);
|
||||||
}
|
}
|
||||||
return phoneNumber;
|
return phoneNumber;
|
||||||
@ -821,7 +828,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
* @returns the id if the contact is successfully saved, null otherwise.
|
* @returns the id if the contact is successfully saved, null otherwise.
|
||||||
*/
|
*/
|
||||||
public String save(JSONObject contact) {
|
public String save(JSONObject contact) {
|
||||||
AccountManager mgr = AccountManager.get(mApp);
|
AccountManager mgr = AccountManager.get(mApp.getActivity());
|
||||||
Account[] accounts = mgr.getAccounts();
|
Account[] accounts = mgr.getAccounts();
|
||||||
String accountName = null;
|
String accountName = null;
|
||||||
String accountType = null;
|
String accountType = null;
|
||||||
@ -831,25 +838,25 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
accountType = accounts[0].type;
|
accountType = accounts[0].type;
|
||||||
}
|
}
|
||||||
else if (accounts.length > 1) {
|
else if (accounts.length > 1) {
|
||||||
for(Account a : accounts) {
|
for (Account a : accounts) {
|
||||||
if(a.type.contains("eas")&& a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/ {
|
if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/{
|
||||||
accountName = a.name;
|
accountName = a.name;
|
||||||
accountType = a.type;
|
accountType = a.type;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(accountName == null){
|
if (accountName == null) {
|
||||||
for(Account a : accounts){
|
for (Account a : accounts) {
|
||||||
if(a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/ {
|
if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/{
|
||||||
accountName = a.name;
|
accountName = a.name;
|
||||||
accountType = a.type;
|
accountType = a.type;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(accountName == null){
|
if (accountName == null) {
|
||||||
for(Account a : accounts){
|
for (Account a : accounts) {
|
||||||
if(a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/ {
|
if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/{
|
||||||
accountName = a.name;
|
accountName = a.name;
|
||||||
accountType = a.type;
|
accountType = a.type;
|
||||||
break;
|
break;
|
||||||
@ -879,7 +886,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
|
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
|
||||||
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
|
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
|
||||||
// But not needed to update existing values.
|
// But not needed to update existing values.
|
||||||
int rawId = (new Integer(getJsonString(contact,"rawId"))).intValue();
|
int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();
|
||||||
|
|
||||||
// Create a list of attributes to add to the contact database
|
// Create a list of attributes to add to the contact database
|
||||||
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
|
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
|
||||||
@ -899,7 +906,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE});
|
new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
|
||||||
|
|
||||||
if (displayName != null) {
|
if (displayName != null) {
|
||||||
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
|
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
|
||||||
@ -937,8 +944,8 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
phones = contact.getJSONArray("phoneNumbers");
|
phones = contact.getJSONArray("phoneNumbers");
|
||||||
if (phones != null) {
|
if (phones != null) {
|
||||||
for (int i=0; i<phones.length(); i++) {
|
for (int i = 0; i < phones.length(); i++) {
|
||||||
JSONObject phone = (JSONObject)phones.get(i);
|
JSONObject phone = (JSONObject) phones.get(i);
|
||||||
String phoneId = getJsonString(phone, "id");
|
String phoneId = getJsonString(phone, "id");
|
||||||
// This is a new phone so do a DB insert
|
// This is a new phone so do a DB insert
|
||||||
if (phoneId == null) {
|
if (phoneId == null) {
|
||||||
@ -956,15 +963,14 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE})
|
new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
|
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
|
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get phone numbers");
|
Log.d(LOG_TAG, "Could not get phone numbers");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -973,11 +979,11 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
emails = contact.getJSONArray("emails");
|
emails = contact.getJSONArray("emails");
|
||||||
if (emails != null) {
|
if (emails != null) {
|
||||||
for (int i=0; i<emails.length(); i++) {
|
for (int i = 0; i < emails.length(); i++) {
|
||||||
JSONObject email = (JSONObject)emails.get(i);
|
JSONObject email = (JSONObject) emails.get(i);
|
||||||
String emailId = getJsonString(email, "id");
|
String emailId = getJsonString(email, "id");
|
||||||
// This is a new email so do a DB insert
|
// This is a new email so do a DB insert
|
||||||
if (emailId==null) {
|
if (emailId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
|
||||||
@ -992,15 +998,14 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE})
|
new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
|
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")))
|
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get emails");
|
Log.d(LOG_TAG, "Could not get emails");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1009,11 +1014,11 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
addresses = contact.getJSONArray("addresses");
|
addresses = contact.getJSONArray("addresses");
|
||||||
if (addresses != null) {
|
if (addresses != null) {
|
||||||
for (int i=0; i<addresses.length(); i++) {
|
for (int i = 0; i < addresses.length(); i++) {
|
||||||
JSONObject address = (JSONObject)addresses.get(i);
|
JSONObject address = (JSONObject) addresses.get(i);
|
||||||
String addressId = getJsonString(address, "id");
|
String addressId = getJsonString(address, "id");
|
||||||
// This is a new address so do a DB insert
|
// This is a new address so do a DB insert
|
||||||
if (addressId==null) {
|
if (addressId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
|
||||||
@ -1033,7 +1038,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE})
|
new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
|
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
|
||||||
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
|
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
|
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
|
||||||
@ -1045,8 +1050,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get addresses");
|
Log.d(LOG_TAG, "Could not get addresses");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1055,11 +1059,11 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
organizations = contact.getJSONArray("organizations");
|
organizations = contact.getJSONArray("organizations");
|
||||||
if (organizations != null) {
|
if (organizations != null) {
|
||||||
for (int i=0; i<organizations.length(); i++) {
|
for (int i = 0; i < organizations.length(); i++) {
|
||||||
JSONObject org = (JSONObject)organizations.get(i);
|
JSONObject org = (JSONObject) organizations.get(i);
|
||||||
String orgId = getJsonString(org, "id");
|
String orgId = getJsonString(org, "id");
|
||||||
// This is a new organization so do a DB insert
|
// This is a new organization so do a DB insert
|
||||||
if (orgId==null) {
|
if (orgId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
|
||||||
@ -1076,7 +1080,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE})
|
new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
|
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
|
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
|
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
|
||||||
@ -1085,8 +1089,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get organizations");
|
Log.d(LOG_TAG, "Could not get organizations");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1095,11 +1098,11 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
ims = contact.getJSONArray("ims");
|
ims = contact.getJSONArray("ims");
|
||||||
if (ims != null) {
|
if (ims != null) {
|
||||||
for (int i=0; i<ims.length(); i++) {
|
for (int i = 0; i < ims.length(); i++) {
|
||||||
JSONObject im = (JSONObject)ims.get(i);
|
JSONObject im = (JSONObject) ims.get(i);
|
||||||
String imId = getJsonString(im, "id");
|
String imId = getJsonString(im, "id");
|
||||||
// This is a new IM so do a DB insert
|
// This is a new IM so do a DB insert
|
||||||
if (imId==null) {
|
if (imId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
|
||||||
@ -1114,15 +1117,14 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE})
|
new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
|
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
|
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get emails");
|
Log.d(LOG_TAG, "Could not get emails");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1131,7 +1133,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{id,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE})
|
new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
|
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
@ -1141,7 +1143,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{id,ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE})
|
new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
|
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
@ -1151,11 +1153,11 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
websites = contact.getJSONArray("websites");
|
websites = contact.getJSONArray("websites");
|
||||||
if (websites != null) {
|
if (websites != null) {
|
||||||
for (int i=0; i<websites.length(); i++) {
|
for (int i = 0; i < websites.length(); i++) {
|
||||||
JSONObject website = (JSONObject)websites.get(i);
|
JSONObject website = (JSONObject) websites.get(i);
|
||||||
String websiteId = getJsonString(website, "id");
|
String websiteId = getJsonString(website, "id");
|
||||||
// This is a new website so do a DB insert
|
// This is a new website so do a DB insert
|
||||||
if (websiteId==null) {
|
if (websiteId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
|
||||||
@ -1170,15 +1172,14 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE})
|
new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
|
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
|
||||||
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
|
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get websites");
|
Log.d(LOG_TAG, "Could not get websites");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1189,7 +1190,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=? AND " +
|
ContactsContract.Data.MIMETYPE + "=? AND " +
|
||||||
ContactsContract.CommonDataKinds.Event.TYPE + "=?",
|
ContactsContract.CommonDataKinds.Event.TYPE + "=?",
|
||||||
new String[]{id,ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String(""+ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)})
|
new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
|
||||||
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
|
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
|
||||||
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
|
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
|
||||||
.build());
|
.build());
|
||||||
@ -1200,12 +1201,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
photos = contact.getJSONArray("photos");
|
photos = contact.getJSONArray("photos");
|
||||||
if (photos != null) {
|
if (photos != null) {
|
||||||
for (int i=0; i<photos.length(); i++) {
|
for (int i = 0; i < photos.length(); i++) {
|
||||||
JSONObject photo = (JSONObject)photos.get(i);
|
JSONObject photo = (JSONObject) photos.get(i);
|
||||||
String photoId = getJsonString(photo, "id");
|
String photoId = getJsonString(photo, "id");
|
||||||
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
|
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
|
||||||
// This is a new photo so do a DB insert
|
// This is a new photo so do a DB insert
|
||||||
if (photoId==null) {
|
if (photoId == null) {
|
||||||
ContentValues contentValues = new ContentValues();
|
ContentValues contentValues = new ContentValues();
|
||||||
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
|
||||||
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
|
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
|
||||||
@ -1220,15 +1221,14 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||||
.withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " +
|
.withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " +
|
||||||
ContactsContract.Data.MIMETYPE + "=?",
|
ContactsContract.Data.MIMETYPE + "=?",
|
||||||
new String[]{photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE})
|
new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
|
||||||
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
|
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
|
||||||
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
|
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get photos");
|
Log.d(LOG_TAG, "Could not get photos");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1236,7 +1236,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
|
|
||||||
//Modify contact
|
//Modify contact
|
||||||
try {
|
try {
|
||||||
mApp.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
|
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
|
||||||
} catch (RemoteException e) {
|
} catch (RemoteException e) {
|
||||||
Log.e(LOG_TAG, e.getMessage(), e);
|
Log.e(LOG_TAG, e.getMessage(), e);
|
||||||
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
|
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
|
||||||
@ -1403,6 +1403,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
}
|
}
|
||||||
return buffer.toByteArray();
|
return buffer.toByteArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an input stream based on file path or uri content://, http://, file://
|
* Get an input stream based on file path or uri content://, http://, file://
|
||||||
*
|
*
|
||||||
@ -1413,7 +1414,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
private InputStream getPathFromUri(String path) throws IOException {
|
private InputStream getPathFromUri(String path) throws IOException {
|
||||||
if (path.startsWith("content:")) {
|
if (path.startsWith("content:")) {
|
||||||
Uri uri = Uri.parse(path);
|
Uri uri = Uri.parse(path);
|
||||||
return mApp.getContentResolver().openInputStream(uri);
|
return mApp.getActivity().getContentResolver().openInputStream(uri);
|
||||||
}
|
}
|
||||||
if (path.startsWith("http:") || path.startsWith("file:")) {
|
if (path.startsWith("http:") || path.startsWith("file:")) {
|
||||||
URL url = new URL(path);
|
URL url = new URL(path);
|
||||||
@ -1456,8 +1457,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix"))
|
.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix"))
|
||||||
.build());
|
.build());
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get name object");
|
Log.d(LOG_TAG, "Could not get name object");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1466,13 +1466,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
phones = contact.getJSONArray("phoneNumbers");
|
phones = contact.getJSONArray("phoneNumbers");
|
||||||
if (phones != null) {
|
if (phones != null) {
|
||||||
for (int i=0; i<phones.length(); i++) {
|
for (int i = 0; i < phones.length(); i++) {
|
||||||
JSONObject phone = (JSONObject)phones.get(i);
|
JSONObject phone = (JSONObject) phones.get(i);
|
||||||
insertPhone(ops, phone);
|
insertPhone(ops, phone);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get phone numbers");
|
Log.d(LOG_TAG, "Could not get phone numbers");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1481,13 +1480,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
emails = contact.getJSONArray("emails");
|
emails = contact.getJSONArray("emails");
|
||||||
if (emails != null) {
|
if (emails != null) {
|
||||||
for (int i=0; i<emails.length(); i++) {
|
for (int i = 0; i < emails.length(); i++) {
|
||||||
JSONObject email = (JSONObject)emails.get(i);
|
JSONObject email = (JSONObject) emails.get(i);
|
||||||
insertEmail(ops, email);
|
insertEmail(ops, email);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get emails");
|
Log.d(LOG_TAG, "Could not get emails");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1496,13 +1494,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
addresses = contact.getJSONArray("addresses");
|
addresses = contact.getJSONArray("addresses");
|
||||||
if (addresses != null) {
|
if (addresses != null) {
|
||||||
for (int i=0; i<addresses.length(); i++) {
|
for (int i = 0; i < addresses.length(); i++) {
|
||||||
JSONObject address = (JSONObject)addresses.get(i);
|
JSONObject address = (JSONObject) addresses.get(i);
|
||||||
insertAddress(ops, address);
|
insertAddress(ops, address);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get addresses");
|
Log.d(LOG_TAG, "Could not get addresses");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1511,13 +1508,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
organizations = contact.getJSONArray("organizations");
|
organizations = contact.getJSONArray("organizations");
|
||||||
if (organizations != null) {
|
if (organizations != null) {
|
||||||
for (int i=0; i<organizations.length(); i++) {
|
for (int i = 0; i < organizations.length(); i++) {
|
||||||
JSONObject org = (JSONObject)organizations.get(i);
|
JSONObject org = (JSONObject) organizations.get(i);
|
||||||
insertOrganization(ops, org);
|
insertOrganization(ops, org);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get organizations");
|
Log.d(LOG_TAG, "Could not get organizations");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1526,13 +1522,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
ims = contact.getJSONArray("ims");
|
ims = contact.getJSONArray("ims");
|
||||||
if (ims != null) {
|
if (ims != null) {
|
||||||
for (int i=0; i<ims.length(); i++) {
|
for (int i = 0; i < ims.length(); i++) {
|
||||||
JSONObject im = (JSONObject)ims.get(i);
|
JSONObject im = (JSONObject) ims.get(i);
|
||||||
insertIm(ops, im);
|
insertIm(ops, im);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get emails");
|
Log.d(LOG_TAG, "Could not get emails");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1561,13 +1556,12 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
websites = contact.getJSONArray("websites");
|
websites = contact.getJSONArray("websites");
|
||||||
if (websites != null) {
|
if (websites != null) {
|
||||||
for (int i=0; i<websites.length(); i++) {
|
for (int i = 0; i < websites.length(); i++) {
|
||||||
JSONObject website = (JSONObject)websites.get(i);
|
JSONObject website = (JSONObject) websites.get(i);
|
||||||
insertWebsite(ops, website);
|
insertWebsite(ops, website);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get websites");
|
Log.d(LOG_TAG, "Could not get websites");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1587,20 +1581,19 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
try {
|
try {
|
||||||
photos = contact.getJSONArray("photos");
|
photos = contact.getJSONArray("photos");
|
||||||
if (photos != null) {
|
if (photos != null) {
|
||||||
for (int i=0; i<photos.length(); i++) {
|
for (int i = 0; i < photos.length(); i++) {
|
||||||
JSONObject photo = (JSONObject)photos.get(i);
|
JSONObject photo = (JSONObject) photos.get(i);
|
||||||
insertPhoto(ops, photo);
|
insertPhoto(ops, photo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Could not get photos");
|
Log.d(LOG_TAG, "Could not get photos");
|
||||||
}
|
}
|
||||||
|
|
||||||
String newId = null;
|
String newId = null;
|
||||||
//Add contact
|
//Add contact
|
||||||
try {
|
try {
|
||||||
ContentProviderResult[] cpResults = mApp.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
|
ContentProviderResult[] cpResults = mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
|
||||||
if (cpResults.length >= 0) {
|
if (cpResults.length >= 0) {
|
||||||
newId = cpResults[0].uri.getLastPathSegment();
|
newId = cpResults[0].uri.getLastPathSegment();
|
||||||
}
|
}
|
||||||
@ -1619,15 +1612,15 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
public boolean remove(String id) {
|
public boolean remove(String id) {
|
||||||
int result = 0;
|
int result = 0;
|
||||||
Cursor cursor = mApp.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
|
Cursor cursor = mApp.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
|
||||||
null,
|
null,
|
||||||
ContactsContract.Contacts._ID + " = ?",
|
ContactsContract.Contacts._ID + " = ?",
|
||||||
new String[] {id}, null);
|
new String[] { id }, null);
|
||||||
if(cursor.getCount() == 1) {
|
if (cursor.getCount() == 1) {
|
||||||
cursor.moveToFirst();
|
cursor.moveToFirst();
|
||||||
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
|
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
|
||||||
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
|
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
|
||||||
result = mApp.getContentResolver().delete(uri, null, null);
|
result = mApp.getActivity().getContentResolver().delete(uri, null, null);
|
||||||
} else {
|
} else {
|
||||||
Log.d(LOG_TAG, "Could not find contact with ID");
|
Log.d(LOG_TAG, "Could not find contact with ID");
|
||||||
}
|
}
|
||||||
@ -1635,7 +1628,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
return (result > 0) ? true : false;
|
return (result > 0) ? true : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**************************************************************************
|
/**************************************************************************
|
||||||
*
|
*
|
||||||
* All methods below this comment are used to convert from JavaScript
|
* All methods below this comment are used to convert from JavaScript
|
||||||
* text types to Android integer types and vice versa.
|
* text types to Android integer types and vice versa.
|
||||||
@ -1800,7 +1793,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
private int getContactType(String string) {
|
private int getContactType(String string) {
|
||||||
int type = ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
|
int type = ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
|
||||||
if (string!=null) {
|
if (string != null) {
|
||||||
if ("home".equals(string.toLowerCase())) {
|
if ("home".equals(string.toLowerCase())) {
|
||||||
return ContactsContract.CommonDataKinds.Email.TYPE_HOME;
|
return ContactsContract.CommonDataKinds.Email.TYPE_HOME;
|
||||||
}
|
}
|
||||||
@ -1855,7 +1848,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
private int getOrgType(String string) {
|
private int getOrgType(String string) {
|
||||||
int type = ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
|
int type = ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
|
||||||
if (string!=null) {
|
if (string != null) {
|
||||||
if ("work".equals(string.toLowerCase())) {
|
if ("work".equals(string.toLowerCase())) {
|
||||||
return ContactsContract.CommonDataKinds.Organization.TYPE_WORK;
|
return ContactsContract.CommonDataKinds.Organization.TYPE_WORK;
|
||||||
}
|
}
|
||||||
@ -1898,7 +1891,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
|
|||||||
*/
|
*/
|
||||||
private int getAddressType(String string) {
|
private int getAddressType(String string) {
|
||||||
int type = ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
|
int type = ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
|
||||||
if (string!=null) {
|
if (string != null) {
|
||||||
if ("work".equals(string.toLowerCase())) {
|
if ("work".equals(string.toLowerCase())) {
|
||||||
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK;
|
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK;
|
||||||
}
|
}
|
||||||
|
@ -17,17 +17,18 @@
|
|||||||
under the License.
|
under the License.
|
||||||
*/
|
*/
|
||||||
package org.apache.cordova;
|
package org.apache.cordova;
|
||||||
|
|
||||||
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
import org.apache.cordova.api.LOG;
|
import org.apache.cordova.api.LOG;
|
||||||
import org.json.JSONArray;
|
import org.json.JSONArray;
|
||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
|
|
||||||
|
//import android.app.Activity;
|
||||||
import android.app.Activity;
|
|
||||||
import android.app.AlertDialog;
|
import android.app.AlertDialog;
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.DialogInterface;
|
import android.content.DialogInterface;
|
||||||
import android.view.KeyEvent;
|
import android.view.KeyEvent;
|
||||||
import android.view.View;
|
//import android.view.View;
|
||||||
import android.webkit.ConsoleMessage;
|
import android.webkit.ConsoleMessage;
|
||||||
import android.webkit.JsPromptResult;
|
import android.webkit.JsPromptResult;
|
||||||
import android.webkit.JsResult;
|
import android.webkit.JsResult;
|
||||||
@ -42,10 +43,9 @@ import android.widget.EditText;
|
|||||||
*/
|
*/
|
||||||
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 Activity ctx;
|
private CordovaInterface ctx;
|
||||||
private CordovaWebView appView;
|
private CordovaWebView appView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -53,20 +53,28 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
*
|
*
|
||||||
* @param ctx
|
* @param ctx
|
||||||
*/
|
*/
|
||||||
public CordovaChromeClient(Context ctx) {
|
public CordovaChromeClient(CordovaInterface ctx) {
|
||||||
this.ctx = (Activity) ctx;
|
this.ctx = ctx;
|
||||||
//appView = this.ctx.appView;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public CordovaChromeClient(Context ctx, CordovaWebView app)
|
/**
|
||||||
{
|
* Constructor.
|
||||||
this.ctx = (Activity) ctx;
|
*
|
||||||
appView = app;
|
* @param ctx
|
||||||
|
* @param app
|
||||||
|
*/
|
||||||
|
public CordovaChromeClient(CordovaInterface ctx, CordovaWebView app) {
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.appView = app;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setWebView(CordovaWebView view)
|
/**
|
||||||
{
|
* Constructor.
|
||||||
appView = view;
|
*
|
||||||
|
* @param view
|
||||||
|
*/
|
||||||
|
public void setWebView(CordovaWebView view) {
|
||||||
|
this.appView = view;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -79,7 +87,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
|
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
|
||||||
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
|
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx.getActivity());
|
||||||
dlg.setMessage(message);
|
dlg.setMessage(message);
|
||||||
dlg.setTitle("Alert");
|
dlg.setTitle("Alert");
|
||||||
//Don't let alerts break the back button
|
//Don't let alerts break the back button
|
||||||
@ -99,7 +107,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
|
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
|
||||||
//DO NOTHING
|
//DO NOTHING
|
||||||
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
|
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
|
||||||
if(keyCode == KeyEvent.KEYCODE_BACK)
|
if (keyCode == KeyEvent.KEYCODE_BACK)
|
||||||
{
|
{
|
||||||
result.confirm();
|
result.confirm();
|
||||||
return false;
|
return false;
|
||||||
@ -123,7 +131,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
|
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
|
||||||
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
|
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx.getActivity());
|
||||||
dlg.setMessage(message);
|
dlg.setMessage(message);
|
||||||
dlg.setTitle("Confirm");
|
dlg.setTitle("Confirm");
|
||||||
dlg.setCancelable(true);
|
dlg.setCancelable(true);
|
||||||
@ -148,7 +156,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
|
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
|
||||||
//DO NOTHING
|
//DO NOTHING
|
||||||
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
|
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
|
||||||
if(keyCode == KeyEvent.KEYCODE_BACK)
|
if (keyCode == KeyEvent.KEYCODE_BACK)
|
||||||
{
|
{
|
||||||
result.cancel();
|
result.cancel();
|
||||||
return false;
|
return false;
|
||||||
@ -182,7 +190,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
// 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(appView.baseUrl) == 0 || appView.isUrlWhiteListed(url)) {
|
if (url.startsWith("file://") || url.indexOf(this.appView.baseUrl) == 0 || this.appView.isUrlWhiteListed(url)) {
|
||||||
reqOk = true;
|
reqOk = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -196,7 +204,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
String action = array.getString(1);
|
String action = array.getString(1);
|
||||||
String callbackId = array.getString(2);
|
String callbackId = array.getString(2);
|
||||||
boolean async = array.getBoolean(3);
|
boolean async = array.getBoolean(3);
|
||||||
String r = appView.pluginManager.exec(service, action, callbackId, message, async);
|
String r = this.appView.pluginManager.exec(service, action, callbackId, message, async);
|
||||||
result.confirm(r);
|
result.confirm(r);
|
||||||
} catch (JSONException e) {
|
} catch (JSONException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
@ -205,24 +213,29 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
|
|
||||||
// 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 = appView.callbackServer.getJavascript();
|
String r = this.appView.callbackServer.getJavascript();
|
||||||
result.confirm(r);
|
result.confirm(r);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do NO-OP so older code doesn't display dialog
|
||||||
|
else if (defaultValue.equals("gap_init:")) {
|
||||||
|
result.confirm("OK");
|
||||||
|
}
|
||||||
|
|
||||||
// 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 = "";
|
||||||
if (message.equals("usePolling")) {
|
if (message.equals("usePolling")) {
|
||||||
r = ""+ appView.callbackServer.usePolling();
|
r = "" + this.appView.callbackServer.usePolling();
|
||||||
}
|
}
|
||||||
else if (message.equals("restartServer")) {
|
else if (message.equals("restartServer")) {
|
||||||
appView.callbackServer.restartServer();
|
this.appView.callbackServer.restartServer();
|
||||||
}
|
}
|
||||||
else if (message.equals("getPort")) {
|
else if (message.equals("getPort")) {
|
||||||
r = Integer.toString(appView.callbackServer.getPort());
|
r = Integer.toString(this.appView.callbackServer.getPort());
|
||||||
}
|
}
|
||||||
else if (message.equals("getToken")) {
|
else if (message.equals("getToken")) {
|
||||||
r = appView.callbackServer.getToken();
|
r = this.appView.callbackServer.getToken();
|
||||||
}
|
}
|
||||||
result.confirm(r);
|
result.confirm(r);
|
||||||
}
|
}
|
||||||
@ -230,9 +243,9 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
// Show dialog
|
// Show dialog
|
||||||
else {
|
else {
|
||||||
final JsPromptResult res = result;
|
final JsPromptResult res = result;
|
||||||
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
|
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx.getActivity());
|
||||||
dlg.setMessage(message);
|
dlg.setMessage(message);
|
||||||
final EditText input = new EditText(this.ctx);
|
final EditText input = new EditText(this.ctx.getActivity());
|
||||||
if (defaultValue != null) {
|
if (defaultValue != null) {
|
||||||
input.setText(defaultValue);
|
input.setText(defaultValue);
|
||||||
}
|
}
|
||||||
@ -273,7 +286,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
{
|
{
|
||||||
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
|
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
|
||||||
|
|
||||||
if( estimatedSize < MAX_QUOTA)
|
if (estimatedSize < MAX_QUOTA)
|
||||||
{
|
{
|
||||||
//increase for 1Mb
|
//increase for 1Mb
|
||||||
long newQuota = estimatedSize;
|
long newQuota = estimatedSize;
|
||||||
@ -289,6 +302,7 @@ 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
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
@Override
|
@Override
|
||||||
public void onConsoleMessage(String message, int lineNumber, String sourceID)
|
public void onConsoleMessage(String message, int lineNumber, String sourceID)
|
||||||
{
|
{
|
||||||
@ -299,7 +313,7 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
@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);
|
||||||
}
|
}
|
||||||
@ -315,6 +329,4 @@ public class CordovaChromeClient extends WebChromeClient {
|
|||||||
super.onGeolocationPermissionsShowPrompt(origin, callback);
|
super.onGeolocationPermissionsShowPrompt(origin, callback);
|
||||||
callback.invoke(origin, true, false);
|
callback.invoke(origin, true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
1
framework/src/org/apache/cordova/CordovaException.java
Normal file → Executable file
1
framework/src/org/apache/cordova/CordovaException.java
Normal file → Executable file
@ -20,5 +20,4 @@
|
|||||||
package org.apache.cordova;
|
package org.apache.cordova;
|
||||||
|
|
||||||
public class CordovaException extends Exception {
|
public class CordovaException extends Exception {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -28,6 +28,7 @@ import java.util.Stack;
|
|||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
import org.apache.cordova.api.LOG;
|
import org.apache.cordova.api.LOG;
|
||||||
import org.apache.cordova.api.PluginManager;
|
import org.apache.cordova.api.PluginManager;
|
||||||
import org.xmlpull.v1.XmlPullParserException;
|
import org.xmlpull.v1.XmlPullParserException;
|
||||||
@ -36,28 +37,27 @@ import android.content.Context;
|
|||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.res.XmlResourceParser;
|
import android.content.res.XmlResourceParser;
|
||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
|
import android.os.Bundle;
|
||||||
import android.util.AttributeSet;
|
import android.util.AttributeSet;
|
||||||
import android.webkit.WebSettings;
|
import android.webkit.WebSettings;
|
||||||
import android.webkit.WebView;
|
import android.webkit.WebView;
|
||||||
import android.webkit.WebSettings.LayoutAlgorithm;
|
import android.webkit.WebSettings.LayoutAlgorithm;
|
||||||
import android.app.Activity;
|
|
||||||
|
|
||||||
public class CordovaWebView extends WebView {
|
public class CordovaWebView extends WebView {
|
||||||
|
|
||||||
public static final String TAG = "CordovaWebView";
|
public static final String TAG = "CordovaWebView";
|
||||||
|
|
||||||
/** The authorization tokens. */
|
/** The authorization tokens. */
|
||||||
private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
|
//private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
|
||||||
|
|
||||||
/** The whitelist **/
|
/** The whitelist **/
|
||||||
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
|
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
|
||||||
private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>();
|
private HashMap<String, Boolean> whiteListCache = new HashMap<String, Boolean>();
|
||||||
protected PluginManager pluginManager;
|
public PluginManager pluginManager;
|
||||||
public CallbackServer callbackServer;
|
public CallbackServer callbackServer;
|
||||||
|
|
||||||
|
|
||||||
/** Actvities and other important classes **/
|
/** Actvities and other important classes **/
|
||||||
private Context mCtx;
|
private CordovaInterface mCtx;
|
||||||
CordovaWebViewClient viewClient;
|
CordovaWebViewClient viewClient;
|
||||||
private CordovaChromeClient chromeClient;
|
private CordovaChromeClient chromeClient;
|
||||||
|
|
||||||
@ -68,46 +68,78 @@ public class CordovaWebView extends WebView {
|
|||||||
|
|
||||||
boolean useBrowserHistory = false;
|
boolean useBrowserHistory = false;
|
||||||
|
|
||||||
protected int loadUrlTimeout;
|
// Flag to track that a loadUrl timeout occurred
|
||||||
|
int loadUrlTimeout = 0;
|
||||||
|
|
||||||
protected long loadUrlTimeoutValue;
|
// LoadUrl timeout value in msec (default of 20 sec)
|
||||||
|
//protected int loadUrlTimeoutValue = 20000;
|
||||||
|
|
||||||
//preferences read from cordova.xml
|
//preferences read from cordova.xml
|
||||||
protected PreferenceSet preferences;
|
//protected PreferenceSet preferences;
|
||||||
|
|
||||||
public CordovaWebView(Context context) {
|
/**
|
||||||
super(context);
|
* Constructor.
|
||||||
mCtx = context;
|
*
|
||||||
setup();
|
* @param context
|
||||||
|
*/
|
||||||
|
public CordovaWebView(CordovaInterface context) {
|
||||||
|
super(context.getActivity());
|
||||||
|
this.mCtx = context;
|
||||||
|
//preferences = new PreferenceSet();
|
||||||
|
this.loadConfiguration();
|
||||||
|
this.setup();
|
||||||
}
|
}
|
||||||
|
|
||||||
public CordovaWebView(Context context, AttributeSet attrs) {
|
/**
|
||||||
super(context, attrs);
|
* Constructor.
|
||||||
mCtx = context;
|
*
|
||||||
preferences = new PreferenceSet();
|
* @param context
|
||||||
loadConfiguration();
|
* @param attrs
|
||||||
setup();
|
*/
|
||||||
|
public CordovaWebView(CordovaInterface context, AttributeSet attrs) {
|
||||||
|
super(context.getActivity(), attrs);
|
||||||
|
this.mCtx = context;
|
||||||
|
//preferences = new PreferenceSet();
|
||||||
|
this.loadConfiguration();
|
||||||
|
this.setup();
|
||||||
}
|
}
|
||||||
|
|
||||||
public CordovaWebView(Context context, AttributeSet attrs, int defStyle) {
|
/**
|
||||||
super(context, attrs, defStyle);
|
* Constructor.
|
||||||
mCtx = context;
|
*
|
||||||
preferences = new PreferenceSet();
|
* @param context
|
||||||
loadConfiguration();
|
* @param attrs
|
||||||
setup();
|
* @param defStyle
|
||||||
|
*/
|
||||||
|
public CordovaWebView(CordovaInterface context, AttributeSet attrs, int defStyle) {
|
||||||
|
super(context.getActivity(), attrs, defStyle);
|
||||||
|
this.mCtx = context;
|
||||||
|
//preferences = new PreferenceSet();
|
||||||
|
this.loadConfiguration();
|
||||||
|
this.setup();
|
||||||
}
|
}
|
||||||
|
|
||||||
public CordovaWebView(Context context, AttributeSet attrs, int defStyle,
|
/**
|
||||||
boolean privateBrowsing) {
|
* Constructor.
|
||||||
super(context, attrs, defStyle, privateBrowsing);
|
*
|
||||||
mCtx = context;
|
* @param context
|
||||||
preferences = new PreferenceSet();
|
* @param attrs
|
||||||
loadConfiguration();
|
* @param defStyle
|
||||||
setup();
|
* @param privateBrowsing
|
||||||
|
*/
|
||||||
|
public CordovaWebView(CordovaInterface context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
|
||||||
|
super(context.getActivity(), attrs, defStyle, privateBrowsing);
|
||||||
|
this.mCtx = context;
|
||||||
|
//preferences = new PreferenceSet();
|
||||||
|
this.loadConfiguration();
|
||||||
|
this.setup();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setup()
|
/**
|
||||||
{
|
* Initialize webview.
|
||||||
|
*/
|
||||||
|
private void setup() {
|
||||||
|
|
||||||
this.setInitialScale(0);
|
this.setInitialScale(0);
|
||||||
this.setVerticalScrollBarEnabled(false);
|
this.setVerticalScrollBarEnabled(false);
|
||||||
this.requestFocusFromTouch();
|
this.requestFocusFromTouch();
|
||||||
@ -123,12 +155,12 @@ public class CordovaWebView extends WebView {
|
|||||||
|
|
||||||
// Enable database
|
// Enable database
|
||||||
settings.setDatabaseEnabled(true);
|
settings.setDatabaseEnabled(true);
|
||||||
String databasePath = mCtx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
|
String databasePath = this.mCtx.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
|
||||||
settings.setDatabasePath(databasePath);
|
settings.setDatabasePath(databasePath);
|
||||||
|
|
||||||
//Setup the WebChromeClient and WebViewClient
|
//Setup the WebChromeClient and WebViewClient
|
||||||
setWebViewClient(new CordovaWebViewClient(mCtx, this));
|
//setWebViewClient(new CordovaWebViewClient(mCtx, this));
|
||||||
setWebChromeClient(new CordovaChromeClient(mCtx, this));
|
//setWebChromeClient(new CordovaChromeClient(mCtx, this));
|
||||||
|
|
||||||
// Enable DOM storage
|
// Enable DOM storage
|
||||||
settings.setDomStorageEnabled(true);
|
settings.setDomStorageEnabled(true);
|
||||||
@ -137,104 +169,28 @@ public class CordovaWebView extends WebView {
|
|||||||
settings.setGeolocationEnabled(true);
|
settings.setGeolocationEnabled(true);
|
||||||
|
|
||||||
//Start up the plugin manager
|
//Start up the plugin manager
|
||||||
this.pluginManager = new PluginManager(this, mCtx);
|
this.pluginManager = new PluginManager(this, this.mCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
//This sets it up so that we can save copies of the clients that we might need later.
|
* Set the WebViewClient.
|
||||||
public void setWebViewClient(CordovaWebViewClient client)
|
*
|
||||||
{
|
* @param client
|
||||||
viewClient = client;
|
*/
|
||||||
|
public void setWebViewClient(CordovaWebViewClient client) {
|
||||||
|
this.viewClient = client;
|
||||||
super.setWebViewClient(client);
|
super.setWebViewClient(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
public void setWebChromeClient(CordovaChromeClient client)
|
* Set the WebChromeClient.
|
||||||
{
|
*
|
||||||
chromeClient = client;
|
* @param client
|
||||||
|
*/
|
||||||
|
public void setWebChromeClient(CordovaChromeClient client) {
|
||||||
|
this.chromeClient = client;
|
||||||
super.setWebChromeClient(client);
|
super.setWebChromeClient(client);
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Sets the authentication token.
|
|
||||||
*
|
|
||||||
* @param authenticationToken
|
|
||||||
* the authentication token
|
|
||||||
* @param host
|
|
||||||
* the host
|
|
||||||
* @param realm
|
|
||||||
* the realm
|
|
||||||
*/
|
|
||||||
public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
|
|
||||||
|
|
||||||
if(host == null) {
|
|
||||||
host = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
if(realm == null) {
|
|
||||||
realm = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
authenticationTokens.put(host.concat(realm), authenticationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes the authentication token.
|
|
||||||
*
|
|
||||||
* @param host
|
|
||||||
* the host
|
|
||||||
* @param realm
|
|
||||||
* the realm
|
|
||||||
* @return the authentication token or null if did not exist
|
|
||||||
*/
|
|
||||||
public AuthenticationToken removeAuthenticationToken(String host, String realm) {
|
|
||||||
return authenticationTokens.remove(host.concat(realm));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the authentication token.
|
|
||||||
*
|
|
||||||
* In order it tries:
|
|
||||||
* 1- host + realm
|
|
||||||
* 2- host
|
|
||||||
* 3- realm
|
|
||||||
* 4- no host, no realm
|
|
||||||
*
|
|
||||||
* @param host
|
|
||||||
* the host
|
|
||||||
* @param realm
|
|
||||||
* the realm
|
|
||||||
* @return the authentication token
|
|
||||||
*/
|
|
||||||
public AuthenticationToken getAuthenticationToken(String host, String realm) {
|
|
||||||
AuthenticationToken token = null;
|
|
||||||
|
|
||||||
token = authenticationTokens.get(host.concat(realm));
|
|
||||||
|
|
||||||
if(token == null) {
|
|
||||||
// try with just the host
|
|
||||||
token = authenticationTokens.get(host);
|
|
||||||
|
|
||||||
// Try the realm
|
|
||||||
if(token == null) {
|
|
||||||
token = authenticationTokens.get(realm);
|
|
||||||
}
|
|
||||||
|
|
||||||
// if no host found, just query for default
|
|
||||||
if(token == null) {
|
|
||||||
token = authenticationTokens.get("");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all authentication tokens.
|
|
||||||
*/
|
|
||||||
public void clearAuthenticationTokens() {
|
|
||||||
authenticationTokens.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add entry to approved list of URLs (whitelist)
|
* Add entry to approved list of URLs (whitelist)
|
||||||
@ -245,31 +201,31 @@ public class CordovaWebView extends WebView {
|
|||||||
public void addWhiteListEntry(String origin, boolean subdomains) {
|
public void addWhiteListEntry(String origin, boolean subdomains) {
|
||||||
try {
|
try {
|
||||||
// Unlimited access to network resources
|
// Unlimited access to network resources
|
||||||
if(origin.compareTo("*") == 0) {
|
if (origin.compareTo("*") == 0) {
|
||||||
LOG.d(TAG, "Unlimited access to network resources");
|
LOG.d(TAG, "Unlimited access to network resources");
|
||||||
whiteList.add(Pattern.compile(".*"));
|
this.whiteList.add(Pattern.compile(".*"));
|
||||||
} else { // specific access
|
} else { // specific access
|
||||||
// check if subdomains should be included
|
// check if subdomains should be included
|
||||||
// TODO: we should not add more domains if * has already been added
|
// TODO: we should not add more domains if * has already been added
|
||||||
if (subdomains) {
|
if (subdomains) {
|
||||||
// XXX making it stupid friendly for people who forget to include protocol/SSL
|
// XXX making it stupid friendly for people who forget to include protocol/SSL
|
||||||
if(origin.startsWith("http")) {
|
if (origin.startsWith("http")) {
|
||||||
whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
|
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
|
||||||
} else {
|
} else {
|
||||||
whiteList.add(Pattern.compile("^https?://(.*\\.)?"+origin));
|
this.whiteList.add(Pattern.compile("^https?://(.*\\.)?" + origin));
|
||||||
}
|
}
|
||||||
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
|
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
|
||||||
} else {
|
} else {
|
||||||
// XXX making it stupid friendly for people who forget to include protocol/SSL
|
// XXX making it stupid friendly for people who forget to include protocol/SSL
|
||||||
if(origin.startsWith("http")) {
|
if (origin.startsWith("http")) {
|
||||||
whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
|
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
|
||||||
} else {
|
} else {
|
||||||
whiteList.add(Pattern.compile("^https?://"+origin));
|
this.whiteList.add(Pattern.compile("^https?://" + origin));
|
||||||
}
|
}
|
||||||
LOG.d(TAG, "Origin to allow: %s", origin);
|
LOG.d(TAG, "Origin to allow: %s", origin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch(Exception e) {
|
} catch (Exception e) {
|
||||||
LOG.d(TAG, "Failed to add origin %s", origin);
|
LOG.d(TAG, "Failed to add origin %s", origin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -283,19 +239,19 @@ public class CordovaWebView extends WebView {
|
|||||||
public boolean isUrlWhiteListed(String url) {
|
public boolean isUrlWhiteListed(String url) {
|
||||||
|
|
||||||
// Check to see if we have matched url previously
|
// Check to see if we have matched url previously
|
||||||
if (whiteListCache.get(url) != null) {
|
if (this.whiteListCache.get(url) != null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Look for match in white list
|
// Look for match in white list
|
||||||
Iterator<Pattern> pit = whiteList.iterator();
|
Iterator<Pattern> pit = this.whiteList.iterator();
|
||||||
while (pit.hasNext()) {
|
while (pit.hasNext()) {
|
||||||
Pattern p = pit.next();
|
Pattern p = pit.next();
|
||||||
Matcher m = p.matcher(url);
|
Matcher m = p.matcher(url);
|
||||||
|
|
||||||
// If match found, then cache it to speed up subsequent comparisons
|
// If match found, then cache it to speed up subsequent comparisons
|
||||||
if (m.find()) {
|
if (m.find()) {
|
||||||
whiteListCache.put(url, true);
|
this.whiteListCache.put(url, true);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -303,71 +259,179 @@ public class CordovaWebView extends WebView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* We override loadUrl so that we can track the back history
|
* Load the url into the webview.
|
||||||
* @see android.webkit.WebView#loadUrl(java.lang.String)
|
*
|
||||||
|
* @param url
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void loadUrl(String url)
|
public void loadUrl(String url) {
|
||||||
{
|
String initUrl = this.getProperty("url", null);
|
||||||
|
|
||||||
|
// If first page of app, then set URL to load to be the one passed in
|
||||||
|
if (initUrl == null || (this.urls.size() > 0)) {
|
||||||
|
this.loadUrlIntoView(url);
|
||||||
|
}
|
||||||
|
// Otherwise use the URL specified in the activity's extras bundle
|
||||||
|
else {
|
||||||
|
this.loadUrlIntoView(initUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the url into the webview after waiting for period of time.
|
||||||
|
* This is used to display the splashscreen for certain amount of time.
|
||||||
|
*
|
||||||
|
* @param url
|
||||||
|
* @param time The number of ms to wait before loading webview
|
||||||
|
*/
|
||||||
|
public void loadUrl(final String url, int time) {
|
||||||
|
String initUrl = this.getProperty("url", null);
|
||||||
|
|
||||||
|
// If first page of app, then set URL to load to be the one passed in
|
||||||
|
if (initUrl == null || (this.urls.size() > 0)) {
|
||||||
|
this.loadUrlIntoView(url, time);
|
||||||
|
}
|
||||||
|
// Otherwise use the URL specified in the activity's extras bundle
|
||||||
|
else {
|
||||||
|
this.loadUrlIntoView(initUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the url into the webview.
|
||||||
|
*
|
||||||
|
* @param url
|
||||||
|
*/
|
||||||
|
public void loadUrlIntoView(final String url) {
|
||||||
if (!url.startsWith("javascript:")) {
|
if (!url.startsWith("javascript:")) {
|
||||||
|
LOG.d(TAG, ">>> loadUrl(" + url + ")");
|
||||||
|
|
||||||
this.url = url;
|
this.url = url;
|
||||||
if (this.baseUrl == null) {
|
if (this.baseUrl == null) {
|
||||||
int i = url.lastIndexOf('/');
|
int i = url.lastIndexOf('/');
|
||||||
if (i > 0) {
|
if (i > 0) {
|
||||||
this.baseUrl = url.substring(0, i+1);
|
this.baseUrl = url.substring(0, i + 1);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.baseUrl = this.url + "/";
|
this.baseUrl = this.url + "/";
|
||||||
}
|
}
|
||||||
|
|
||||||
pluginManager.init();
|
this.pluginManager.init();
|
||||||
|
|
||||||
if(!useBrowserHistory)
|
if (!this.useBrowserHistory) {
|
||||||
this.urls.push(url);
|
this.urls.push(url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
super.loadUrl(url);
|
// Create a timeout timer for loadUrl
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void loadUrl(final String url, final int time)
|
|
||||||
{
|
|
||||||
// If not first page of app, then load immediately
|
|
||||||
// Add support for browser history if we use it.
|
|
||||||
if (this.urls.size() > 0 || this.canGoBack()) {
|
|
||||||
this.loadUrl(url);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!url.startsWith("javascript:")) {
|
|
||||||
LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time);
|
|
||||||
}
|
|
||||||
|
|
||||||
final CordovaWebView me = this;
|
final CordovaWebView me = this;
|
||||||
Runnable runnable = new Runnable() {
|
final int currentLoadUrlTimeout = me.loadUrlTimeout;
|
||||||
|
final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("loadUrlTimeoutValue", "20000"));
|
||||||
|
|
||||||
|
// Timeout error method
|
||||||
|
final Runnable loadError = new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
me.stopLoading();
|
||||||
|
LOG.e(TAG, "CordovaWebView: TIMEOUT ERROR!");
|
||||||
|
if (viewClient != null) {
|
||||||
|
viewClient.onReceivedError(me, -6, "The connection to the server was unsuccessful.", url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Timeout timer method
|
||||||
|
final Runnable timeoutCheck = new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
synchronized(this) {
|
synchronized (this) {
|
||||||
this.wait(time);
|
wait(loadUrlTimeoutValue);
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
//I'm pretty sure this has to be on the UI thread
|
|
||||||
me.loadUrl(url);
|
// If timeout, then stop loading and handle error
|
||||||
|
if (me.loadUrlTimeout == currentLoadUrlTimeout) {
|
||||||
|
me.mCtx.getActivity().runOnUiThread(loadError);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Thread thread = new Thread(runnable);
|
|
||||||
|
// Load url
|
||||||
|
this.mCtx.getActivity().runOnUiThread(new Runnable() {
|
||||||
|
public void run() {
|
||||||
|
Thread thread = new Thread(timeoutCheck);
|
||||||
thread.start();
|
thread.start();
|
||||||
|
me.loadUrlNow(url);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If Javascript, then just load it now
|
||||||
|
else {
|
||||||
|
super.loadUrl(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load URL in webview.
|
||||||
|
*
|
||||||
|
* @param url
|
||||||
|
*/
|
||||||
|
private void loadUrlNow(String url) {
|
||||||
|
LOG.d(TAG, ">>> loadUrlNow()");
|
||||||
|
super.loadUrl(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the url into the webview after waiting for period of time.
|
||||||
|
* This is used to display the splashscreen for certain amount of time.
|
||||||
|
*
|
||||||
|
* @param url
|
||||||
|
* @param time The number of ms to wait before loading webview
|
||||||
|
*/
|
||||||
|
public void loadUrlIntoView(final String url, final int time) {
|
||||||
|
|
||||||
|
// If not first page of app, then load immediately
|
||||||
|
// Add support for browser history if we use it.
|
||||||
|
if ((url.startsWith("javascript:")) || this.urls.size() > 0 || this.canGoBack()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
// If first page, then show splashscreen
|
||||||
|
else {
|
||||||
|
|
||||||
|
LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time);
|
||||||
|
|
||||||
|
// Send message to show splashscreen now if desired
|
||||||
|
this.postMessage("splashscreen", "show");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load url
|
||||||
|
this.loadUrlIntoView(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send JavaScript statement back to JavaScript.
|
||||||
|
* (This is a convenience method)
|
||||||
|
*
|
||||||
|
* @param message
|
||||||
|
*/
|
||||||
public void sendJavascript(String statement) {
|
public void sendJavascript(String statement) {
|
||||||
callbackServer.sendJavascript(statement);
|
if (this.callbackServer != null) {
|
||||||
|
this.callbackServer.sendJavascript(statement);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void postMessage(String id, String data) {
|
/**
|
||||||
pluginManager.postMessage(id, data);
|
* Send a message to all plugins.
|
||||||
|
*
|
||||||
|
* @param id The message id
|
||||||
|
* @param data The message data
|
||||||
|
*/
|
||||||
|
public void postMessage(String id, Object data) {
|
||||||
|
if (this.pluginManager != null) {
|
||||||
|
this.pluginManager.postMessage(id, data);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -375,8 +439,8 @@ public class CordovaWebView extends WebView {
|
|||||||
* the stack.
|
* the stack.
|
||||||
*/
|
*/
|
||||||
public String peekAtUrlStack() {
|
public String peekAtUrlStack() {
|
||||||
if (urls.size() > 0) {
|
if (this.urls.size() > 0) {
|
||||||
return urls.peek();
|
return this.urls.peek();
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
@ -387,7 +451,7 @@ public class CordovaWebView extends WebView {
|
|||||||
* @param url
|
* @param url
|
||||||
*/
|
*/
|
||||||
public void pushUrl(String url) {
|
public void pushUrl(String url) {
|
||||||
urls.push(url);
|
this.urls.push(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -399,8 +463,8 @@ public class CordovaWebView extends WebView {
|
|||||||
|
|
||||||
// Check webview first to see if there is a history
|
// Check webview first to see if there is a history
|
||||||
// This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior)
|
// This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior)
|
||||||
if (this.canGoBack()) {
|
if (super.canGoBack()) {
|
||||||
this.goBack();
|
super.goBack();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -408,13 +472,27 @@ public class CordovaWebView extends WebView {
|
|||||||
if (this.urls.size() > 1) {
|
if (this.urls.size() > 1) {
|
||||||
this.urls.pop(); // Pop current url
|
this.urls.pop(); // Pop current url
|
||||||
String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl()
|
String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl()
|
||||||
loadUrl(url);
|
this.loadUrl(url);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return true if there is a history item.
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public boolean canGoBack() {
|
||||||
|
if (super.canGoBack()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (this.urls.size() > 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load the specified URL in the Cordova webview or a new browser instance.
|
* Load the specified URL in the Cordova webview or a new browser instance.
|
||||||
@ -426,7 +504,7 @@ public class CordovaWebView extends WebView {
|
|||||||
* @param clearHistory Clear the history stack, so new page becomes top of history
|
* @param clearHistory Clear the history stack, so new page becomes top of history
|
||||||
* @param params DroidGap parameters for new app
|
* @param params DroidGap parameters for new app
|
||||||
*/
|
*/
|
||||||
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException {
|
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) {
|
||||||
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
|
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
|
||||||
|
|
||||||
// If clearing history
|
// If clearing history
|
||||||
@ -451,13 +529,13 @@ public class CordovaWebView extends WebView {
|
|||||||
}
|
}
|
||||||
// Load in default viewer if not
|
// Load in default viewer if not
|
||||||
else {
|
else {
|
||||||
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")");
|
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL=" + url + ")");
|
||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
mCtx.startActivity(intent);
|
mCtx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error loading url "+url, e);
|
LOG.e(TAG, "Error loading url " + url, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -467,9 +545,9 @@ public class CordovaWebView extends WebView {
|
|||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
mCtx.startActivity(intent);
|
mCtx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error loading url "+url, e);
|
LOG.e(TAG, "Error loading url " + url, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -482,7 +560,7 @@ public class CordovaWebView extends WebView {
|
|||||||
* <log level="DEBUG" />
|
* <log level="DEBUG" />
|
||||||
*/
|
*/
|
||||||
private void loadConfiguration() {
|
private void loadConfiguration() {
|
||||||
int id = getResources().getIdentifier("cordova", "xml", mCtx.getPackageName());
|
int id = getResources().getIdentifier("cordova", "xml", this.mCtx.getActivity().getPackageName());
|
||||||
if (id == 0) {
|
if (id == 0) {
|
||||||
LOG.i("CordovaLog", "cordova.xml missing. Ignoring...");
|
LOG.i("CordovaLog", "cordova.xml missing. Ignoring...");
|
||||||
return;
|
return;
|
||||||
@ -496,7 +574,7 @@ public class CordovaWebView extends WebView {
|
|||||||
String origin = xml.getAttributeValue(null, "origin");
|
String origin = xml.getAttributeValue(null, "origin");
|
||||||
String subdomains = xml.getAttributeValue(null, "subdomains");
|
String subdomains = xml.getAttributeValue(null, "subdomains");
|
||||||
if (origin != null) {
|
if (origin != null) {
|
||||||
addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
|
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (strNode.equals("log")) {
|
else if (strNode.equals("log")) {
|
||||||
@ -509,14 +587,19 @@ public class CordovaWebView extends WebView {
|
|||||||
else if (strNode.equals("preference")) {
|
else if (strNode.equals("preference")) {
|
||||||
String name = xml.getAttributeValue(null, "name");
|
String name = xml.getAttributeValue(null, "name");
|
||||||
String value = xml.getAttributeValue(null, "value");
|
String value = xml.getAttributeValue(null, "value");
|
||||||
String readonlyString = xml.getAttributeValue(null, "readonly");
|
|
||||||
|
|
||||||
boolean readonly = (readonlyString != null &&
|
// TODO @bc Is preferences needed? Just use Intent.putExtra?
|
||||||
readonlyString.equals("true"));
|
//String readonlyString = xml.getAttributeValue(null, "readonly");
|
||||||
|
|
||||||
LOG.i("CordovaLog", "Found preference for %s", name);
|
//boolean readonly = (readonlyString != null &&
|
||||||
|
// readonlyString.equals("true"));
|
||||||
|
|
||||||
preferences.add(new PreferenceNode(name, value, readonly));
|
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
|
||||||
|
|
||||||
|
//preferences.add(new PreferenceNode(name, value, readonly));
|
||||||
|
|
||||||
|
// Save preferences in Intent
|
||||||
|
this.mCtx.getActivity().getIntent().putExtra(name, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@ -527,6 +610,33 @@ public class CordovaWebView extends WebView {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Init preferences
|
||||||
|
//this.useBrowserHistory = preferences.prefMatches("useBrowserHistory", "true");
|
||||||
|
if ("true".equals(this.getProperty("useBrowserHistory", "true"))) {
|
||||||
|
this.useBrowserHistory = true;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
this.useBrowserHistory = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get string property for activity.
|
||||||
|
*
|
||||||
|
* @param name
|
||||||
|
* @param defaultValue
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public String getProperty(String name, String defaultValue) {
|
||||||
|
Bundle bundle = this.mCtx.getActivity().getIntent().getExtras();
|
||||||
|
if (bundle == null) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
Object p = bundle.get(name);
|
||||||
|
if (p == null) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
return p.toString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,10 +18,15 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.cordova;
|
package org.apache.cordova;
|
||||||
|
|
||||||
import org.apache.cordova.api.LOG;
|
import java.util.Hashtable;
|
||||||
|
|
||||||
import android.app.Activity;
|
import org.apache.cordova.api.CordovaInterface;
|
||||||
import android.content.Context;
|
import org.apache.cordova.api.LOG;
|
||||||
|
import org.json.JSONException;
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
//import android.app.Activity;
|
||||||
|
//import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.pm.ApplicationInfo;
|
import android.content.pm.ApplicationInfo;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
@ -29,7 +34,7 @@ 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.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;
|
||||||
@ -42,28 +47,40 @@ import android.webkit.WebViewClient;
|
|||||||
public class CordovaWebViewClient extends WebViewClient {
|
public class CordovaWebViewClient extends WebViewClient {
|
||||||
|
|
||||||
private static final String TAG = "Cordova";
|
private static final String TAG = "Cordova";
|
||||||
Activity ctx;
|
CordovaInterface ctx;
|
||||||
CordovaWebView appView;
|
CordovaWebView appView;
|
||||||
private boolean doClearHistory = false;
|
private boolean doClearHistory = false;
|
||||||
|
|
||||||
|
/** The authorization tokens. */
|
||||||
|
private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor.
|
* Constructor.
|
||||||
*
|
*
|
||||||
* @param ctx
|
* @param ctx
|
||||||
*/
|
*/
|
||||||
public CordovaWebViewClient(Activity ctx) {
|
public CordovaWebViewClient(CordovaInterface ctx) {
|
||||||
this.ctx = ctx;
|
this.ctx = ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
public CordovaWebViewClient(Context ctx, CordovaWebView view)
|
/**
|
||||||
{
|
* Constructor.
|
||||||
this.ctx = (Activity) ctx;
|
*
|
||||||
appView = view;
|
* @param ctx
|
||||||
|
* @param view
|
||||||
|
*/
|
||||||
|
public CordovaWebViewClient(CordovaInterface ctx, CordovaWebView view) {
|
||||||
|
this.ctx = ctx;
|
||||||
|
this.appView = view;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setWebView(CordovaWebView view)
|
/**
|
||||||
{
|
* Constructor.
|
||||||
appView = view;
|
*
|
||||||
|
* @param view
|
||||||
|
*/
|
||||||
|
public void setWebView(CordovaWebView view) {
|
||||||
|
this.appView = view;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -78,7 +95,7 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
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 ((appView.pluginManager != null) && appView.pluginManager.onOverrideUrlLoading(url)) {
|
if ((this.appView.pluginManager != null) && this.appView.pluginManager.onOverrideUrlLoading(url)) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// If dialing phone (tel:5551212)
|
// If dialing phone (tel:5551212)
|
||||||
@ -86,9 +103,9 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_DIAL);
|
Intent intent = new Intent(Intent.ACTION_DIAL);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
ctx.startActivity(intent);
|
this.ctx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
|
LOG.e(TAG, "Error dialing " + url + ": " + e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -97,9 +114,9 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
ctx.startActivity(intent);
|
this.ctx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
|
LOG.e(TAG, "Error showing map " + url + ": " + e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,9 +125,9 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
ctx.startActivity(intent);
|
this.ctx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
|
LOG.e(TAG, "Error sending email " + url + ": " + e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,12 +154,12 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
intent.setData(Uri.parse("sms:"+address));
|
intent.setData(Uri.parse("sms:" + address));
|
||||||
intent.putExtra("address", address);
|
intent.putExtra("address", address);
|
||||||
intent.setType("vnd.android-dir/mms-sms");
|
intent.setType("vnd.android-dir/mms-sms");
|
||||||
ctx.startActivity(intent);
|
this.ctx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
|
LOG.e(TAG, "Error sending sms " + url + ":" + e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -151,12 +168,12 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
|
|
||||||
// If our app or file:, then load into a new Cordova webview container by starting a new instance of our activity.
|
// If our app or file:, then load into a new Cordova webview container by starting a new instance of our activity.
|
||||||
// Our app continues to run. When BACK is pressed, our app is redisplayed.
|
// Our app continues to run. When BACK is pressed, our app is redisplayed.
|
||||||
if (url.startsWith("file://") || url.indexOf(appView.baseUrl) == 0 || appView.isUrlWhiteListed(url)) {
|
if (url.startsWith("file://") || url.indexOf(this.appView.baseUrl) == 0 || this.appView.isUrlWhiteListed(url)) {
|
||||||
//This will fix iFrames
|
//This will fix iFrames
|
||||||
if(appView.useBrowserHistory)
|
if (appView.useBrowserHistory)
|
||||||
return false;
|
return false;
|
||||||
else
|
else
|
||||||
appView.loadUrl(url);
|
this.appView.loadUrl(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If not our application, let default viewer handle
|
// If not our application, let default viewer handle
|
||||||
@ -164,9 +181,9 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
try {
|
try {
|
||||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||||
intent.setData(Uri.parse(url));
|
intent.setData(Uri.parse(url));
|
||||||
ctx.startActivity(intent);
|
this.ctx.getActivity().startActivity(intent);
|
||||||
} catch (android.content.ActivityNotFoundException e) {
|
} catch (android.content.ActivityNotFoundException e) {
|
||||||
LOG.e(TAG, "Error loading url "+url, e);
|
LOG.e(TAG, "Error loading url " + url, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -178,45 +195,40 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
* 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
|
|
||||||
* @param handler
|
* @param handler
|
||||||
* the handler
|
|
||||||
* @param host
|
* @param host
|
||||||
* the host
|
|
||||||
* @param realm
|
* @param realm
|
||||||
* the realm
|
|
||||||
*/
|
*/
|
||||||
@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
|
||||||
// Note: The WebView MUST be a CordoaWebView
|
AuthenticationToken token = this.getAuthenticationToken(host, realm);
|
||||||
AuthenticationToken token = ((CordovaWebView) view).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.
|
||||||
if(!appView.useBrowserHistory)
|
if (!this.appView.useBrowserHistory) {
|
||||||
{
|
|
||||||
view.clearHistory();
|
view.clearHistory();
|
||||||
this.doClearHistory = true;
|
this.doClearHistory = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create callback server and plugin manager
|
// Create callback server and plugin manager
|
||||||
if (appView.callbackServer == null) {
|
if (this.appView.callbackServer == null) {
|
||||||
appView.callbackServer = new CallbackServer();
|
this.appView.callbackServer = new CallbackServer();
|
||||||
appView.callbackServer.init(url);
|
this.appView.callbackServer.init(url);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
appView.callbackServer.reinit(url);
|
this.appView.callbackServer.reinit(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Broadcast message that page has loaded
|
||||||
|
this.appView.postMessage("onPageStarted", url);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -241,26 +253,29 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Clear timeout flag
|
// Clear timeout flag
|
||||||
appView.loadUrlTimeout++;
|
this.appView.loadUrlTimeout++;
|
||||||
|
|
||||||
// Try firing the onNativeReady event in JS. If it fails because the JS is
|
// Try firing the onNativeReady event in JS. If it fails because the JS is
|
||||||
// not loaded yet then just set a flag so that the onNativeReady can be fired
|
// not loaded yet then just set a flag so that the onNativeReady can be fired
|
||||||
// from the JS side when the JS gets to that code.
|
// from the JS side when the JS gets to that code.
|
||||||
if (!url.equals("about:blank")) {
|
if (!url.equals("about:blank")) {
|
||||||
appView.loadUrl("javascript:try{ cordova.require('cordova/channel').onNativeReady.fire();}catch(e){_nativeReady = true;}");
|
this.appView.loadUrl("javascript:try{ cordova.require('cordova/channel').onNativeReady.fire();}catch(e){_nativeReady = true;}");
|
||||||
appView.postMessage("onNativeReady", null);
|
this.appView.postMessage("onNativeReady", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Broadcast message that page has loaded
|
||||||
|
this.appView.postMessage("onPageFinished", url);
|
||||||
|
|
||||||
// Make app visible after 2 sec in case there was a JS error and Cordova JS never initialized correctly
|
// Make app visible after 2 sec in case there was a JS error and Cordova JS never initialized correctly
|
||||||
if (appView.getVisibility() == View.INVISIBLE) {
|
if (this.appView.getVisibility() == View.INVISIBLE) {
|
||||||
Thread t = new Thread(new Runnable() {
|
Thread t = new Thread(new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(2000);
|
Thread.sleep(2000);
|
||||||
ctx.runOnUiThread(new Runnable() {
|
ctx.getActivity().runOnUiThread(new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
appView.setVisibility(View.VISIBLE);
|
//appView.setVisibility(View.VISIBLE);
|
||||||
//ctx.spinnerStop();
|
appView.postMessage("spinner", "stop");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
@ -270,14 +285,13 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
t.start();
|
t.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Shutdown if blank loaded
|
// Shutdown if blank loaded
|
||||||
if (url.equals("about:blank")) {
|
if (url.equals("about:blank")) {
|
||||||
if (appView.callbackServer != null) {
|
if (this.appView.callbackServer != null) {
|
||||||
appView.callbackServer.destroy();
|
this.appView.callbackServer.destroy();
|
||||||
}
|
}
|
||||||
//this.ctx.endActivity();
|
//this.ctx.endActivity();
|
||||||
this.ctx.finish();
|
this.ctx.getActivity().finish();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -292,22 +306,32 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
|
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
|
||||||
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
|
LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
|
||||||
|
|
||||||
// Clear timeout flag
|
// Clear timeout flag
|
||||||
//this.ctx.loadUrlTimeout++;
|
this.appView.loadUrlTimeout++;
|
||||||
|
|
||||||
// Stop "app loading" spinner if showing
|
// Stop "app loading" spinner if showing
|
||||||
//this.ctx.spinnerStop();
|
//this.ctx.spinnerStop();
|
||||||
|
|
||||||
// Handle error
|
// Handle error
|
||||||
//this.ctx.onReceivedError(errorCode, description, failingUrl);
|
//this.ctx.onReceivedError(errorCode, description, failingUrl);
|
||||||
|
JSONObject data = new JSONObject();
|
||||||
|
try {
|
||||||
|
data.put("errorCode", errorCode);
|
||||||
|
data.put("description", description);
|
||||||
|
data.put("url", failingUrl);
|
||||||
|
} catch (JSONException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
this.appView.postMessage("onReceivedError", data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
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.getActivity().getPackageName();
|
||||||
final PackageManager pm = this.ctx.getPackageManager();
|
final PackageManager pm = this.ctx.getActivity().getPackageManager();
|
||||||
ApplicationInfo appInfo;
|
ApplicationInfo appInfo;
|
||||||
try {
|
try {
|
||||||
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
|
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
|
||||||
@ -331,8 +355,81 @@ public class CordovaWebViewClient extends WebViewClient {
|
|||||||
* 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.
|
||||||
*/
|
*/
|
||||||
if (!appView.peekAtUrlStack().equals(url)) {
|
if (!this.appView.peekAtUrlStack().equals(url)) {
|
||||||
appView.pushUrl(url);
|
this.appView.pushUrl(url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the authentication token.
|
||||||
|
*
|
||||||
|
* @param authenticationToken
|
||||||
|
* @param host
|
||||||
|
* @param realm
|
||||||
|
*/
|
||||||
|
public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
|
||||||
|
if (host == null) {
|
||||||
|
host = "";
|
||||||
|
}
|
||||||
|
if (realm == null) {
|
||||||
|
realm = "";
|
||||||
|
}
|
||||||
|
this.authenticationTokens.put(host.concat(realm), authenticationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the authentication token.
|
||||||
|
*
|
||||||
|
* @param host
|
||||||
|
* @param realm
|
||||||
|
*
|
||||||
|
* @return the authentication token or null if did not exist
|
||||||
|
*/
|
||||||
|
public AuthenticationToken removeAuthenticationToken(String host, String realm) {
|
||||||
|
return this.authenticationTokens.remove(host.concat(realm));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the authentication token.
|
||||||
|
*
|
||||||
|
* In order it tries:
|
||||||
|
* 1- host + realm
|
||||||
|
* 2- host
|
||||||
|
* 3- realm
|
||||||
|
* 4- no host, no realm
|
||||||
|
*
|
||||||
|
* @param host
|
||||||
|
* @param realm
|
||||||
|
*
|
||||||
|
* @return the authentication token
|
||||||
|
*/
|
||||||
|
public AuthenticationToken getAuthenticationToken(String host, String realm) {
|
||||||
|
AuthenticationToken token = null;
|
||||||
|
token = this.authenticationTokens.get(host.concat(realm));
|
||||||
|
|
||||||
|
if (token == null) {
|
||||||
|
// try with just the host
|
||||||
|
token = this.authenticationTokens.get(host);
|
||||||
|
|
||||||
|
// Try the realm
|
||||||
|
if (token == null) {
|
||||||
|
token = this.authenticationTokens.get(realm);
|
||||||
|
}
|
||||||
|
|
||||||
|
// if no host found, just query for default
|
||||||
|
if (token == null) {
|
||||||
|
token = this.authenticationTokens.get("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all authentication tokens.
|
||||||
|
*/
|
||||||
|
public void clearAuthenticationTokens() {
|
||||||
|
this.authenticationTokens.clear();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -56,7 +56,7 @@ public class Device extends Plugin {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
super.setContext(ctx);
|
super.setContext(ctx);
|
||||||
Device.uuid = getUuid();
|
Device.uuid = getUuid();
|
||||||
this.initTelephonyReceiver();
|
this.initTelephonyReceiver();
|
||||||
@ -110,7 +110,7 @@ public class Device extends Plugin {
|
|||||||
* Unregister receiver.
|
* Unregister receiver.
|
||||||
*/
|
*/
|
||||||
public void onDestroy() {
|
public void onDestroy() {
|
||||||
this.ctx.unregisterReceiver(this.telephonyReceiver);
|
this.ctx.getActivity().unregisterReceiver(this.telephonyReceiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
@ -123,9 +123,9 @@ public class Device extends Plugin {
|
|||||||
* DroidGap.onMessage("telephone", "ringing" | "offhook" | "idle")
|
* DroidGap.onMessage("telephone", "ringing" | "offhook" | "idle")
|
||||||
*/
|
*/
|
||||||
private void initTelephonyReceiver() {
|
private void initTelephonyReceiver() {
|
||||||
IntentFilter intentFilter = new IntentFilter() ;
|
IntentFilter intentFilter = new IntentFilter();
|
||||||
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
|
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
|
||||||
final Context myctx = this.ctx;
|
//final CordovaInterface myctx = this.ctx;
|
||||||
this.telephonyReceiver = new BroadcastReceiver() {
|
this.telephonyReceiver = new BroadcastReceiver() {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -153,7 +153,7 @@ public class Device extends Plugin {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Register the receiver
|
// Register the receiver
|
||||||
this.ctx.registerReceiver(this.telephonyReceiver, intentFilter);
|
this.ctx.getActivity().registerReceiver(this.telephonyReceiver, intentFilter);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -171,7 +171,7 @@ public class Device extends Plugin {
|
|||||||
* @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.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
|
||||||
return uuid;
|
return uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -205,15 +205,14 @@ public class Device extends Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getSDKVersion() {
|
public String getSDKVersion() {
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
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());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -51,7 +51,6 @@ import android.net.Uri;
|
|||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
import android.webkit.CookieManager;
|
import android.webkit.CookieManager;
|
||||||
|
|
||||||
|
|
||||||
public class FileTransfer extends Plugin {
|
public class FileTransfer extends Plugin {
|
||||||
|
|
||||||
private static final String LOG_TAG = "FileTransfer";
|
private static final String LOG_TAG = "FileTransfer";
|
||||||
@ -76,8 +75,7 @@ public class FileTransfer extends Plugin {
|
|||||||
try {
|
try {
|
||||||
source = args.getString(0);
|
source = args.getString(0);
|
||||||
target = args.getString(1);
|
target = args.getString(1);
|
||||||
}
|
} catch (JSONException e) {
|
||||||
catch (JSONException e) {
|
|
||||||
Log.d(LOG_TAG, "Missing source or target");
|
Log.d(LOG_TAG, "Missing source or target");
|
||||||
return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing source or target");
|
return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing source or target");
|
||||||
}
|
}
|
||||||
@ -199,7 +197,7 @@ public class FileTransfer extends Plugin {
|
|||||||
*/
|
*/
|
||||||
private String getArgument(JSONArray args, int position, String defaultString) {
|
private String getArgument(JSONArray args, int position, String defaultString) {
|
||||||
String arg = defaultString;
|
String arg = defaultString;
|
||||||
if(args.length() >= position) {
|
if (args.length() >= position) {
|
||||||
arg = args.optString(position);
|
arg = args.optString(position);
|
||||||
if (arg == null || "null".equals(arg)) {
|
if (arg == null || "null".equals(arg)) {
|
||||||
arg = defaultString;
|
arg = defaultString;
|
||||||
@ -275,12 +273,13 @@ public class FileTransfer extends Plugin {
|
|||||||
// Use a post method.
|
// Use a post method.
|
||||||
conn.setRequestMethod("POST");
|
conn.setRequestMethod("POST");
|
||||||
conn.setRequestProperty("Connection", "Keep-Alive");
|
conn.setRequestProperty("Connection", "Keep-Alive");
|
||||||
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
|
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);
|
||||||
|
|
||||||
// Handle the other headers
|
// Handle the other headers
|
||||||
try {
|
try {
|
||||||
JSONObject headers = params.getJSONObject("headers");
|
JSONObject headers = params.getJSONObject("headers");
|
||||||
for (Iterator iter = headers.keys(); iter.hasNext();)
|
for (@SuppressWarnings("rawtypes")
|
||||||
|
Iterator iter = headers.keys(); iter.hasNext();)
|
||||||
{
|
{
|
||||||
String headerKey = iter.next().toString();
|
String headerKey = iter.next().toString();
|
||||||
conn.setRequestProperty(headerKey, headers.getString(headerKey));
|
conn.setRequestProperty(headerKey, headers.getString(headerKey));
|
||||||
@ -295,16 +294,16 @@ public class FileTransfer extends Plugin {
|
|||||||
conn.setRequestProperty("Cookie", cookie);
|
conn.setRequestProperty("Cookie", cookie);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Store the non-file portions of the multipart data as a string, so that we can add it
|
* Store the non-file portions of the multipart data as a string, so that we can add it
|
||||||
* to the contentSize, since it is part of the body of the HTTP request.
|
* to the contentSize, since it is part of the body of the HTTP request.
|
||||||
*/
|
*/
|
||||||
String extraParams = "";
|
String extraParams = "";
|
||||||
try {
|
try {
|
||||||
for (Iterator iter = params.keys(); iter.hasNext();) {
|
for (@SuppressWarnings("rawtypes")
|
||||||
|
Iterator iter = params.keys(); iter.hasNext();) {
|
||||||
Object key = iter.next();
|
Object key = iter.next();
|
||||||
if(key.toString() != "headers")
|
if (key.toString() != "headers")
|
||||||
{
|
{
|
||||||
extraParams += LINE_START + BOUNDRY + LINE_END;
|
extraParams += LINE_START + BOUNDRY + LINE_END;
|
||||||
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
|
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
|
||||||
@ -336,8 +335,7 @@ public class FileTransfer extends Plugin {
|
|||||||
conn.setFixedLengthStreamingMode(fixedLength);
|
conn.setFixedLengthStreamingMode(fixedLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dos = new DataOutputStream(conn.getOutputStream());
|
||||||
dos = new DataOutputStream( conn.getOutputStream() );
|
|
||||||
dos.writeBytes(extraParams);
|
dos.writeBytes(extraParams);
|
||||||
//We don't want to chagne encoding, we just want this to write for all Unicode.
|
//We don't want to chagne encoding, we just want this to write for all Unicode.
|
||||||
dos.write(fileName.getBytes("UTF-8"));
|
dos.write(fileName.getBytes("UTF-8"));
|
||||||
@ -373,13 +371,13 @@ public class FileTransfer extends Plugin {
|
|||||||
StringBuffer responseString = new StringBuffer("");
|
StringBuffer responseString = new StringBuffer("");
|
||||||
DataInputStream inStream;
|
DataInputStream inStream;
|
||||||
try {
|
try {
|
||||||
inStream = new DataInputStream ( conn.getInputStream() );
|
inStream = new DataInputStream(conn.getInputStream());
|
||||||
} catch(FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
throw new IOException("Received error from server");
|
throw new IOException("Received error from server");
|
||||||
}
|
}
|
||||||
|
|
||||||
String line;
|
String line;
|
||||||
while (( line = inStream.readLine()) != null) {
|
while ((line = inStream.readLine()) != null) {
|
||||||
responseString.append(line);
|
responseString.append(line);
|
||||||
}
|
}
|
||||||
Log.d(LOG_TAG, "got response from server");
|
Log.d(LOG_TAG, "got response from server");
|
||||||
@ -394,7 +392,7 @@ public class FileTransfer extends Plugin {
|
|||||||
|
|
||||||
// Revert back to the proper verifier and socket factories
|
// Revert back to the proper verifier and socket factories
|
||||||
if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
|
if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
|
||||||
((HttpsURLConnection)conn).setHostnameVerifier(defaultHostnameVerifier);
|
((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
|
||||||
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
|
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -416,7 +414,7 @@ public class FileTransfer extends Plugin {
|
|||||||
file.getParentFile().mkdirs();
|
file.getParentFile().mkdirs();
|
||||||
|
|
||||||
// connect to server
|
// connect to server
|
||||||
if(webView.isUrlWhiteListed(source))
|
if (webView.isUrlWhiteListed(source))
|
||||||
{
|
{
|
||||||
URL url = new URL(source);
|
URL url = new URL(source);
|
||||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||||
@ -424,7 +422,7 @@ public class FileTransfer extends Plugin {
|
|||||||
|
|
||||||
//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);
|
||||||
}
|
}
|
||||||
@ -440,8 +438,8 @@ public class FileTransfer extends Plugin {
|
|||||||
FileOutputStream outputStream = new FileOutputStream(file);
|
FileOutputStream outputStream = new FileOutputStream(file);
|
||||||
|
|
||||||
// write bytes to file
|
// write bytes to file
|
||||||
while ( (bytesRead = inputStream.read(buffer)) > 0 ) {
|
while ((bytesRead = inputStream.read(buffer)) > 0) {
|
||||||
outputStream.write(buffer,0, bytesRead);
|
outputStream.write(buffer, 0, bytesRead);
|
||||||
}
|
}
|
||||||
|
|
||||||
outputStream.close();
|
outputStream.close();
|
||||||
@ -473,7 +471,7 @@ public class FileTransfer extends Plugin {
|
|||||||
private InputStream getPathFromUri(String path) throws FileNotFoundException {
|
private InputStream getPathFromUri(String path) throws FileNotFoundException {
|
||||||
if (path.startsWith("content:")) {
|
if (path.startsWith("content:")) {
|
||||||
Uri uri = Uri.parse(path);
|
Uri uri = Uri.parse(path);
|
||||||
return ctx.getContentResolver().openInputStream(uri);
|
return ctx.getActivity().getContentResolver().openInputStream(uri);
|
||||||
}
|
}
|
||||||
else if (path.startsWith("file://")) {
|
else if (path.startsWith("file://")) {
|
||||||
int question = path.indexOf("?");
|
int question = path.indexOf("?");
|
||||||
|
@ -37,15 +37,15 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.database.Cursor;
|
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.util.Log;
|
||||||
import android.webkit.MimeTypeMap;
|
import android.webkit.MimeTypeMap;
|
||||||
import android.app.Activity;
|
|
||||||
|
|
||||||
|
//import android.app.Activity;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class provides SD card file and directory services to JavaScript.
|
* This class provides SD card file and directory services to JavaScript.
|
||||||
@ -132,7 +132,7 @@ public class FileUtils extends Plugin {
|
|||||||
else if (action.equals("requestFileSystem")) {
|
else if (action.equals("requestFileSystem")) {
|
||||||
long size = args.optLong(1);
|
long size = args.optLong(1);
|
||||||
if (size != 0) {
|
if (size != 0) {
|
||||||
if (size > (DirectoryManager.getFreeDiskSpace(true)*1024)) {
|
if (size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
|
||||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR);
|
return new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -222,9 +222,9 @@ public class FileUtils extends Plugin {
|
|||||||
* @param filePath the path to check
|
* @param filePath the path to check
|
||||||
*/
|
*/
|
||||||
private void notifyDelete(String filePath) {
|
private void notifyDelete(String filePath) {
|
||||||
int result = this.ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
int result = this.ctx.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||||
MediaStore.Images.Media.DATA + " = ?",
|
MediaStore.Images.Media.DATA + " = ?",
|
||||||
new String[] {filePath});
|
new String[] { filePath });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -244,7 +244,7 @@ public class FileUtils extends Plugin {
|
|||||||
|
|
||||||
// Handle the special case where you get an Android content:// uri.
|
// Handle the special case where you get an Android content:// uri.
|
||||||
if (decoded.startsWith("content:")) {
|
if (decoded.startsWith("content:")) {
|
||||||
Cursor cursor = ((Activity) this.ctx).managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
|
Cursor cursor = this.ctx.getActivity().managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
|
||||||
// Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
|
// Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
|
||||||
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
|
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
|
||||||
cursor.moveToFirst();
|
cursor.moveToFirst();
|
||||||
@ -295,7 +295,7 @@ public class FileUtils extends Plugin {
|
|||||||
|
|
||||||
if (fp.isDirectory()) {
|
if (fp.isDirectory()) {
|
||||||
File[] files = fp.listFiles();
|
File[] files = fp.listFiles();
|
||||||
for (int i=0; i<files.length; i++) {
|
for (int i = 0; i < files.length; i++) {
|
||||||
entries.put(getEntry(files[i]));
|
entries.put(getEntry(files[i]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -321,7 +321,6 @@ public class FileUtils extends Plugin {
|
|||||||
fileName = stripFileProtocol(fileName);
|
fileName = stripFileProtocol(fileName);
|
||||||
newParent = stripFileProtocol(newParent);
|
newParent = stripFileProtocol(newParent);
|
||||||
|
|
||||||
|
|
||||||
// Check for invalid file name
|
// Check for invalid file name
|
||||||
if (newName != null && newName.contains(":")) {
|
if (newName != null && newName.contains(":")) {
|
||||||
throw new EncodingException("Bad file name");
|
throw new EncodingException("Bad file name");
|
||||||
@ -378,7 +377,7 @@ public class FileUtils extends Plugin {
|
|||||||
File destFile = null;
|
File destFile = null;
|
||||||
|
|
||||||
// I know this looks weird but it is to work around a JSON bug.
|
// I know this looks weird but it is to work around a JSON bug.
|
||||||
if ("null".equals(newName) || "".equals(newName) ) {
|
if ("null".equals(newName) || "".equals(newName)) {
|
||||||
newName = null;
|
newName = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -478,7 +477,7 @@ public class FileUtils extends Plugin {
|
|||||||
// This weird test is to determine if we are copying or moving a directory into itself.
|
// This weird test is to determine if we are copying or moving a directory into itself.
|
||||||
// Copy /sdcard/myDir to /sdcard/myDir-backup is okay but
|
// Copy /sdcard/myDir to /sdcard/myDir-backup is okay but
|
||||||
// Copy /sdcard/myDir to /sdcard/myDir/backup should thow an INVALID_MODIFICATION_ERR
|
// Copy /sdcard/myDir to /sdcard/myDir/backup should thow an INVALID_MODIFICATION_ERR
|
||||||
if (dest.startsWith(src) && dest.indexOf(File.separator, src.length()-1) != -1) {
|
if (dest.startsWith(src) && dest.indexOf(File.separator, src.length() - 1) != -1) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -727,9 +726,9 @@ public class FileUtils extends Plugin {
|
|||||||
private boolean atRootDirectory(String filePath) {
|
private boolean atRootDirectory(String filePath) {
|
||||||
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.getActivity().getPackageName() + "/cache") ||
|
||||||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
|
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
|
||||||
filePath.equals("/data/data/" + ctx.getPackageName())) {
|
filePath.equals("/data/data/" + ctx.getActivity().getPackageName())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@ -818,16 +817,16 @@ public class FileUtils extends Plugin {
|
|||||||
fs.put("name", "temporary");
|
fs.put("name", "temporary");
|
||||||
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
||||||
fp = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
|
fp = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
|
||||||
"/Android/data/" + ctx.getPackageName() + "/cache/");
|
"/Android/data/" + ctx.getActivity().getPackageName() + "/cache/");
|
||||||
// Create the cache dir if it doesn't exist.
|
// Create the cache dir if it doesn't exist.
|
||||||
fp.mkdirs();
|
fp.mkdirs();
|
||||||
fs.put("root", getEntry(Environment.getExternalStorageDirectory().getAbsolutePath() +
|
fs.put("root", getEntry(Environment.getExternalStorageDirectory().getAbsolutePath() +
|
||||||
"/Android/data/" + ctx.getPackageName() + "/cache/"));
|
"/Android/data/" + ctx.getActivity().getPackageName() + "/cache/"));
|
||||||
} else {
|
} else {
|
||||||
fp = new File("/data/data/" + ctx.getPackageName() + "/cache/");
|
fp = new File("/data/data/" + ctx.getActivity().getPackageName() + "/cache/");
|
||||||
// Create the cache dir if it doesn't exist.
|
// Create the cache dir if it doesn't exist.
|
||||||
fp.mkdirs();
|
fp.mkdirs();
|
||||||
fs.put("root", getEntry("/data/data/" + ctx.getPackageName() + "/cache/"));
|
fs.put("root", getEntry("/data/data/" + ctx.getActivity().getPackageName() + "/cache/"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (type == PERSISTENT) {
|
else if (type == PERSISTENT) {
|
||||||
@ -835,7 +834,7 @@ public class FileUtils extends Plugin {
|
|||||||
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
||||||
fs.put("root", getEntry(Environment.getExternalStorageDirectory()));
|
fs.put("root", getEntry(Environment.getExternalStorageDirectory()));
|
||||||
} else {
|
} else {
|
||||||
fs.put("root", getEntry("/data/data/" + ctx.getPackageName()));
|
fs.put("root", getEntry("/data/data/" + ctx.getActivity().getPackageName()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@ -942,7 +941,7 @@ public class FileUtils extends Plugin {
|
|||||||
String contentType = null;
|
String contentType = null;
|
||||||
if (filename.startsWith("content:")) {
|
if (filename.startsWith("content:")) {
|
||||||
Uri fileUri = Uri.parse(filename);
|
Uri fileUri = Uri.parse(filename);
|
||||||
contentType = this.ctx.getContentResolver().getType(fileUri);
|
contentType = this.ctx.getActivity().getContentResolver().getType(fileUri);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
contentType = getMimeType(filename);
|
contentType = getMimeType(filename);
|
||||||
@ -961,7 +960,7 @@ public class FileUtils extends Plugin {
|
|||||||
*/
|
*/
|
||||||
public static String getMimeType(String filename) {
|
public static String getMimeType(String filename) {
|
||||||
MimeTypeMap map = MimeTypeMap.getSingleton();
|
MimeTypeMap map = MimeTypeMap.getSingleton();
|
||||||
return map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename));
|
return map.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filename));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -982,7 +981,7 @@ public class FileUtils extends Plugin {
|
|||||||
append = true;
|
append = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
byte [] rawData = data.getBytes();
|
byte[] rawData = data.getBytes();
|
||||||
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
|
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
|
||||||
FileOutputStream out = new FileOutputStream(filename, append);
|
FileOutputStream out = new FileOutputStream(filename, append);
|
||||||
byte buff[] = new byte[rawData.length];
|
byte buff[] = new byte[rawData.length];
|
||||||
@ -1025,7 +1024,7 @@ public class FileUtils extends Plugin {
|
|||||||
private InputStream getPathFromUri(String path) throws FileNotFoundException {
|
private InputStream getPathFromUri(String path) throws FileNotFoundException {
|
||||||
if (path.startsWith("content")) {
|
if (path.startsWith("content")) {
|
||||||
Uri uri = Uri.parse(path);
|
Uri uri = Uri.parse(path);
|
||||||
return ctx.getContentResolver().openInputStream(uri);
|
return ctx.getActivity().getContentResolver().openInputStream(uri);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
path = stripFileProtocol(path);
|
path = stripFileProtocol(path);
|
||||||
@ -1040,9 +1039,9 @@ public class FileUtils extends Plugin {
|
|||||||
* @param ctx) the current applicaiton context
|
* @param ctx) the current applicaiton context
|
||||||
* @return the full path to the file
|
* @return the full path to the file
|
||||||
*/
|
*/
|
||||||
protected static String getRealPathFromURI(Uri contentUri, Activity ctx) {
|
protected static String getRealPathFromURI(Uri contentUri, CordovaInterface ctx) {
|
||||||
String[] proj = { _DATA };
|
String[] proj = { _DATA };
|
||||||
Cursor cursor = ctx.managedQuery(contentUri, proj, null, null, null);
|
Cursor cursor = ctx.getActivity().managedQuery(contentUri, proj, null, null, null);
|
||||||
int column_index = cursor.getColumnIndexOrThrow(_DATA);
|
int column_index = cursor.getColumnIndexOrThrow(_DATA);
|
||||||
cursor.moveToFirst();
|
cursor.moveToFirst();
|
||||||
return cursor.getString(column_index);
|
return cursor.getString(column_index);
|
||||||
|
@ -21,7 +21,8 @@ package org.apache.cordova;
|
|||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.location.Location;
|
import android.location.Location;
|
||||||
import android.location.LocationManager;
|
import android.location.LocationManager;
|
||||||
import android.webkit.WebView;
|
|
||||||
|
//import android.webkit.WebView;
|
||||||
|
|
||||||
public class GeoListener {
|
public class GeoListener {
|
||||||
public static int PERMISSION_DENIED = 1;
|
public static int PERMISSION_DENIED = 1;
|
||||||
@ -53,7 +54,7 @@ public class GeoListener {
|
|||||||
this.broker = broker;
|
this.broker = broker;
|
||||||
this.mGps = null;
|
this.mGps = null;
|
||||||
this.mNetwork = null;
|
this.mNetwork = null;
|
||||||
this.mLocMan = (LocationManager) broker.ctx.getSystemService(Context.LOCATION_SERVICE);
|
this.mLocMan = (LocationManager) broker.ctx.getActivity().getSystemService(Context.LOCATION_SERVICE);
|
||||||
|
|
||||||
// If GPS provider, then create and start GPS listener
|
// If GPS provider, then create and start GPS listener
|
||||||
if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
|
if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
|
||||||
|
@ -33,7 +33,7 @@ import android.os.Bundle;
|
|||||||
*/
|
*/
|
||||||
public class GpsListener implements LocationListener {
|
public class GpsListener implements LocationListener {
|
||||||
|
|
||||||
private Context mCtx; // CordovaActivity object
|
private CordovaInterface mCtx; // CordovaActivity object
|
||||||
|
|
||||||
private LocationManager mLocMan; // Location manager object
|
private LocationManager mLocMan; // Location manager object
|
||||||
private GeoListener owner; // Geolistener object (parent)
|
private GeoListener owner; // Geolistener object (parent)
|
||||||
@ -49,10 +49,10 @@ public class GpsListener implements LocationListener {
|
|||||||
* @param interval
|
* @param interval
|
||||||
* @param m
|
* @param m
|
||||||
*/
|
*/
|
||||||
public GpsListener(Context ctx, int interval, GeoListener m) {
|
public GpsListener(CordovaInterface ctx, int interval, GeoListener m) {
|
||||||
this.owner = m;
|
this.owner = m;
|
||||||
this.mCtx = ctx;
|
this.mCtx = ctx;
|
||||||
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
|
this.mLocMan = (LocationManager) this.mCtx.getActivity().getSystemService(Context.LOCATION_SERVICE);
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.start(interval);
|
this.start(interval);
|
||||||
}
|
}
|
||||||
@ -85,7 +85,7 @@ public class GpsListener implements LocationListener {
|
|||||||
* @param provider
|
* @param provider
|
||||||
*/
|
*/
|
||||||
public void onProviderEnabled(String provider) {
|
public void onProviderEnabled(String provider) {
|
||||||
System.out.println("GpsListener: The provider "+ provider + " is enabled");
|
System.out.println("GpsListener: The provider " + provider + " is enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -34,10 +34,16 @@ public class HttpHandler {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,13 +52,16 @@ public class HttpHandler {
|
|||||||
* 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,11 +70,11 @@ public class HttpHandler {
|
|||||||
* 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);
|
||||||
|
@ -17,10 +17,11 @@
|
|||||||
under the License.
|
under the License.
|
||||||
*/
|
*/
|
||||||
package org.apache.cordova;
|
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.view.View.MeasureSpec;
|
||||||
import android.widget.LinearLayout;
|
import android.widget.LinearLayout;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -76,7 +77,7 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
|
|||||||
LOG.d(TAG, "Ignore this event");
|
LOG.d(TAG, "Ignore this event");
|
||||||
}
|
}
|
||||||
// Account for orientation change and ignore this event/Fire orientation change
|
// Account for orientation change and ignore this event/Fire orientation change
|
||||||
else if(screenHeight == width)
|
else if (screenHeight == width)
|
||||||
{
|
{
|
||||||
int tmp_var = screenHeight;
|
int tmp_var = screenHeight;
|
||||||
screenHeight = screenWidth;
|
screenHeight = screenWidth;
|
||||||
@ -86,14 +87,14 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
|
|||||||
// 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.appView.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)
|
||||||
app.sendJavascript("cordova.fireDocumentEvent('showkeyboard');");
|
app.appView.sendJavascript("cordova.fireDocumentEvent('showkeyboard');");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the old height for the next event
|
// Update the old height for the next event
|
||||||
|
@ -28,7 +28,7 @@ import android.os.Bundle;
|
|||||||
|
|
||||||
public class NetworkListener implements LocationListener {
|
public class NetworkListener implements LocationListener {
|
||||||
|
|
||||||
private Context mCtx; // CordovaActivity object
|
private CordovaInterface mCtx; // CordovaActivity object
|
||||||
|
|
||||||
private LocationManager mLocMan; // Location manager object
|
private LocationManager mLocMan; // Location manager object
|
||||||
private GeoListener owner; // Geolistener object (parent)
|
private GeoListener owner; // Geolistener object (parent)
|
||||||
@ -44,10 +44,10 @@ public class NetworkListener implements LocationListener {
|
|||||||
* @param interval
|
* @param interval
|
||||||
* @param m
|
* @param m
|
||||||
*/
|
*/
|
||||||
public NetworkListener(Context ctx, int interval, GeoListener m) {
|
public NetworkListener(CordovaInterface ctx, int interval, GeoListener m) {
|
||||||
this.owner = m;
|
this.owner = m;
|
||||||
this.mCtx = ctx;
|
this.mCtx = ctx;
|
||||||
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
|
this.mLocMan = (LocationManager) this.mCtx.getActivity().getSystemService(Context.LOCATION_SERVICE);
|
||||||
this.running = false;
|
this.running = false;
|
||||||
this.start(interval);
|
this.start(interval);
|
||||||
}
|
}
|
||||||
@ -80,7 +80,7 @@ public class NetworkListener implements LocationListener {
|
|||||||
* @param provider
|
* @param provider
|
||||||
*/
|
*/
|
||||||
public void onProviderEnabled(String provider) {
|
public void onProviderEnabled(String provider) {
|
||||||
System.out.println("NetworkListener: The provider "+ provider + " is enabled");
|
System.out.println("NetworkListener: The provider " + provider + " is enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -23,7 +23,6 @@ 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 android.content.BroadcastReceiver;
|
import android.content.BroadcastReceiver;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
@ -87,22 +86,23 @@ public class NetworkManager extends Plugin {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
super.setContext(ctx);
|
super.setContext(ctx);
|
||||||
this.sockMan = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
|
this.sockMan = (ConnectivityManager) ctx.getActivity().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);
|
||||||
if (this.receiver == null) {
|
if (this.receiver == null) {
|
||||||
this.receiver = new BroadcastReceiver() {
|
this.receiver = new BroadcastReceiver() {
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
@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.getActivity().registerReceiver(this.receiver, intentFilter);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -146,7 +146,7 @@ public class NetworkManager extends Plugin {
|
|||||||
public void onDestroy() {
|
public void onDestroy() {
|
||||||
if (this.receiver != null) {
|
if (this.receiver != null) {
|
||||||
try {
|
try {
|
||||||
this.ctx.unregisterReceiver(this.receiver);
|
this.ctx.getActivity().unregisterReceiver(this.receiver);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e);
|
Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e);
|
||||||
}
|
}
|
||||||
@ -157,7 +157,6 @@ public class NetworkManager extends Plugin {
|
|||||||
// LOCAL METHODS
|
// LOCAL METHODS
|
||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates the JavaScript side whenever the connection changes
|
* Updates the JavaScript side whenever the connection changes
|
||||||
*
|
*
|
||||||
|
@ -31,7 +31,6 @@ import android.media.Ringtone;
|
|||||||
import android.media.RingtoneManager;
|
import android.media.RingtoneManager;
|
||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
import android.os.Vibrator;
|
import android.os.Vibrator;
|
||||||
import android.app.Activity;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class provides access to notifications on the device.
|
* This class provides access to notifications on the device.
|
||||||
@ -68,25 +67,25 @@ public class Notification extends Plugin {
|
|||||||
this.vibrate(args.getLong(0));
|
this.vibrate(args.getLong(0));
|
||||||
}
|
}
|
||||||
else if (action.equals("alert")) {
|
else if (action.equals("alert")) {
|
||||||
this.alert(args.getString(0),args.getString(1),args.getString(2), callbackId);
|
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackId);
|
||||||
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;
|
||||||
}
|
}
|
||||||
else if (action.equals("confirm")) {
|
else if (action.equals("confirm")) {
|
||||||
this.confirm(args.getString(0),args.getString(1),args.getString(2), callbackId);
|
this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackId);
|
||||||
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;
|
||||||
}
|
}
|
||||||
else if (action.equals("activityStart")) {
|
else if (action.equals("activityStart")) {
|
||||||
this.activityStart(args.getString(0),args.getString(1));
|
this.activityStart(args.getString(0), args.getString(1));
|
||||||
}
|
}
|
||||||
else if (action.equals("activityStop")) {
|
else if (action.equals("activityStop")) {
|
||||||
this.activityStop();
|
this.activityStop();
|
||||||
}
|
}
|
||||||
else if (action.equals("progressStart")) {
|
else if (action.equals("progressStart")) {
|
||||||
this.progressStart(args.getString(0),args.getString(1));
|
this.progressStart(args.getString(0), args.getString(1));
|
||||||
}
|
}
|
||||||
else if (action.equals("progressValue")) {
|
else if (action.equals("progressValue")) {
|
||||||
this.progressValue(args.getInt(0));
|
this.progressValue(args.getInt(0));
|
||||||
@ -144,7 +143,7 @@ public class Notification extends Plugin {
|
|||||||
*/
|
*/
|
||||||
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, ringtone);
|
Ringtone notification = RingtoneManager.getRingtone(this.ctx.getActivity().getBaseContext(), ringtone);
|
||||||
|
|
||||||
// If phone is not set to silent mode
|
// If phone is not set to silent mode
|
||||||
if (notification != null) {
|
if (notification != null) {
|
||||||
@ -167,12 +166,12 @@ public class Notification extends Plugin {
|
|||||||
*
|
*
|
||||||
* @param time Time to vibrate in ms.
|
* @param time Time to vibrate in ms.
|
||||||
*/
|
*/
|
||||||
public void vibrate(long time){
|
public void vibrate(long time) {
|
||||||
// Start the vibration, 0 defaults to half a second.
|
// Start the vibration, 0 defaults to half a second.
|
||||||
if (time == 0) {
|
if (time == 0) {
|
||||||
time = 500;
|
time = 500;
|
||||||
}
|
}
|
||||||
Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE);
|
Vibrator vibrator = (Vibrator) this.ctx.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
|
||||||
vibrator.vibrate(time);
|
vibrator.vibrate(time);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -185,13 +184,13 @@ public class Notification extends Plugin {
|
|||||||
*/
|
*/
|
||||||
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 Context 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);
|
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getActivity());
|
||||||
dlg.setMessage(message);
|
dlg.setMessage(message);
|
||||||
dlg.setTitle(title);
|
dlg.setTitle(title);
|
||||||
dlg.setCancelable(false);
|
dlg.setCancelable(false);
|
||||||
@ -206,7 +205,7 @@ public class Notification extends Plugin {
|
|||||||
dlg.show();
|
dlg.show();
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
((Activity) this.ctx).runOnUiThread(runnable);
|
this.ctx.getActivity().runOnUiThread(runnable);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -221,13 +220,13 @@ public class Notification extends Plugin {
|
|||||||
*/
|
*/
|
||||||
public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
|
public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
|
||||||
|
|
||||||
final Context ctx = this.ctx;
|
final CordovaInterface ctx = this.ctx;
|
||||||
final Notification notification = this;
|
final Notification notification = this;
|
||||||
final String[] fButtons = buttonLabels.split(",");
|
final String[] fButtons = buttonLabels.split(",");
|
||||||
|
|
||||||
Runnable runnable = new Runnable() {
|
Runnable runnable = new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
|
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getActivity());
|
||||||
dlg.setMessage(message);
|
dlg.setMessage(message);
|
||||||
dlg.setTitle(title);
|
dlg.setTitle(title);
|
||||||
dlg.setCancelable(false);
|
dlg.setCancelable(false);
|
||||||
@ -270,7 +269,7 @@ public class Notification extends Plugin {
|
|||||||
dlg.show();
|
dlg.show();
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
((Activity) this.ctx).runOnUiThread(runnable);
|
this.ctx.getActivity().runOnUiThread(runnable);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -285,10 +284,10 @@ public class Notification extends Plugin {
|
|||||||
this.spinnerDialog = null;
|
this.spinnerDialog = null;
|
||||||
}
|
}
|
||||||
final Notification notification = this;
|
final Notification notification = this;
|
||||||
final Activity ctx = (Activity) 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, title , message, true, true,
|
notification.spinnerDialog = ProgressDialog.show(ctx.getActivity(), title, message, true, true,
|
||||||
new DialogInterface.OnCancelListener() {
|
new DialogInterface.OnCancelListener() {
|
||||||
public void onCancel(DialogInterface dialog) {
|
public void onCancel(DialogInterface dialog) {
|
||||||
notification.spinnerDialog = null;
|
notification.spinnerDialog = null;
|
||||||
@ -296,7 +295,7 @@ public class Notification extends Plugin {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
ctx.runOnUiThread(runnable);
|
this.ctx.getActivity().runOnUiThread(runnable);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -321,10 +320,10 @@ public class Notification extends Plugin {
|
|||||||
this.progressDialog = null;
|
this.progressDialog = null;
|
||||||
}
|
}
|
||||||
final Notification notification = this;
|
final Notification notification = this;
|
||||||
final Activity ctx = (Activity) this.ctx;
|
final CordovaInterface ctx = this.ctx;
|
||||||
Runnable runnable = new Runnable() {
|
Runnable runnable = new Runnable() {
|
||||||
public void run() {
|
public void run() {
|
||||||
notification.progressDialog = new ProgressDialog(ctx);
|
notification.progressDialog = new ProgressDialog(ctx.getActivity());
|
||||||
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
|
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
|
||||||
notification.progressDialog.setTitle(title);
|
notification.progressDialog.setTitle(title);
|
||||||
notification.progressDialog.setMessage(message);
|
notification.progressDialog.setMessage(message);
|
||||||
@ -340,7 +339,7 @@ public class Notification extends Plugin {
|
|||||||
notification.progressDialog.show();
|
notification.progressDialog.show();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
ctx.runOnUiThread(runnable);
|
this.ctx.getActivity().runOnUiThread(runnable);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -31,7 +31,8 @@ public class SplashScreen extends Plugin {
|
|||||||
String result = "";
|
String result = "";
|
||||||
|
|
||||||
if (action.equals("hide")) {
|
if (action.equals("hide")) {
|
||||||
((DroidGap)this.ctx).removeSplashScreen();
|
//((DroidGap)this.ctx).removeSplashScreen();
|
||||||
|
this.webView.postMessage("splashscreen", "hide");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
status = PluginResult.Status.INVALID_ACTION;
|
status = PluginResult.Status.INVALID_ACTION;
|
||||||
|
@ -18,9 +18,9 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.cordova;
|
package org.apache.cordova;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
//import java.lang.reflect.Field;
|
||||||
|
|
||||||
import android.app.Activity;
|
//import android.app.Activity;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
|
|
||||||
public class StandAlone extends DroidGap {
|
public class StandAlone extends DroidGap {
|
||||||
|
@ -141,7 +141,7 @@ public class Storage extends Plugin {
|
|||||||
|
|
||||||
// If no database path, generate from application package
|
// If no database path, generate from application package
|
||||||
if (this.path == null) {
|
if (this.path == null) {
|
||||||
this.path = this.ctx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
|
this.path = this.ctx.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.dbName = this.path + File.pathSeparator + db + ".db";
|
this.dbName = this.path + File.pathSeparator + db + ".db";
|
||||||
@ -169,8 +169,7 @@ public class Storage extends Plugin {
|
|||||||
this.processResults(myCursor, tx_id);
|
this.processResults(myCursor, tx_id);
|
||||||
myCursor.close();
|
myCursor.close();
|
||||||
}
|
}
|
||||||
}
|
} catch (SQLiteException ex) {
|
||||||
catch (SQLiteException ex) {
|
|
||||||
ex.printStackTrace();
|
ex.printStackTrace();
|
||||||
System.out.println("Storage.executeSql(): Error=" + ex.getMessage());
|
System.out.println("Storage.executeSql(): Error=" + ex.getMessage());
|
||||||
|
|
||||||
|
@ -25,7 +25,6 @@ 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 android.hardware.Sensor;
|
import android.hardware.Sensor;
|
||||||
import android.hardware.SensorEvent;
|
import android.hardware.SensorEvent;
|
||||||
import android.hardware.SensorEventListener;
|
import android.hardware.SensorEventListener;
|
||||||
@ -49,9 +48,9 @@ public class TempListener extends Plugin implements SensorEventListener {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
super.setContext(ctx);
|
super.setContext(ctx);
|
||||||
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
|
this.sensorManager = (SensorManager) ctx.getActivity().getSystemService(Context.SENSOR_SERVICE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -88,6 +87,7 @@ public class TempListener extends Plugin implements SensorEventListener {
|
|||||||
//--------------------------------------------------------------------------
|
//--------------------------------------------------------------------------
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
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);
|
||||||
|
@ -18,23 +18,22 @@
|
|||||||
*/
|
*/
|
||||||
package org.apache.cordova.api;
|
package org.apache.cordova.api;
|
||||||
|
|
||||||
import java.util.HashMap;
|
//import java.util.HashMap;
|
||||||
|
|
||||||
import android.app.Activity;
|
import android.app.Activity;
|
||||||
import android.app.Service;
|
//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;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.IntentFilter;
|
//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.hardware.SensorManager;
|
||||||
import android.net.Uri;
|
//import android.net.Uri;
|
||||||
import android.view.Menu;
|
//import android.view.Menu;
|
||||||
import android.view.MenuItem;
|
//import android.view.MenuItem;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Cordova activity abstract class that is extended by DroidGap.
|
* The Cordova activity abstract class that is extended by DroidGap.
|
||||||
@ -42,7 +41,6 @@ import android.view.MenuItem;
|
|||||||
*/
|
*/
|
||||||
public interface CordovaInterface {
|
public interface CordovaInterface {
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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.
|
||||||
@ -61,13 +59,15 @@ public interface CordovaInterface {
|
|||||||
abstract public void setActivityResultCallback(IPlugin plugin);
|
abstract public void setActivityResultCallback(IPlugin plugin);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Causes the Activity to override the back button behaviour
|
* Causes the Activity to override the back button behavior.
|
||||||
|
*
|
||||||
* @param override
|
* @param override
|
||||||
*/
|
*/
|
||||||
public abstract void bindBackButton(boolean override);
|
public abstract void bindBackButton(boolean override);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A hook required to check if the Back Button is bound
|
* A hook required to check if the Back Button is bound.
|
||||||
|
*
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public abstract boolean isBackButtonBound();
|
public abstract boolean isBackButtonBound();
|
||||||
@ -77,14 +77,18 @@ public interface CordovaInterface {
|
|||||||
* (This is in the Android SDK, do we need this on the Interface?)
|
* (This is in the Android SDK, do we need this on the Interface?)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public abstract boolean onCreateOptionsMenu(Menu menu);
|
//public abstract boolean onCreateOptionsMenu(Menu menu);
|
||||||
|
|
||||||
public abstract boolean onPrepareOptionsMenu(Menu menu);
|
|
||||||
|
|
||||||
public abstract boolean onOptionsItemSelected(MenuItem item);
|
|
||||||
|
|
||||||
|
//public abstract boolean onPrepareOptionsMenu(Menu menu);
|
||||||
|
|
||||||
|
//public abstract boolean onOptionsItemSelected(MenuItem item);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Android activity.
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public abstract Activity getActivity();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
@ -95,8 +99,8 @@ public interface CordovaInterface {
|
|||||||
* @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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
@ -104,8 +108,8 @@ public interface CordovaInterface {
|
|||||||
*
|
*
|
||||||
* @param message
|
* @param message
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
abstract public void sendJavascript(String statement);
|
// abstract public void sendJavascript(String statement);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
@ -113,9 +117,8 @@ public interface CordovaInterface {
|
|||||||
*
|
*
|
||||||
* @param intent The intent to start
|
* @param intent The intent to start
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
abstract public void startActivity(Intent intent);
|
// abstract public void startActivity(Intent intent);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
@ -123,8 +126,8 @@ public interface CordovaInterface {
|
|||||||
*
|
*
|
||||||
* @param url The URL to load.
|
* @param url The URL to load.
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
abstract public void loadUrl(String url);
|
// abstract public void loadUrl(String url);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated
|
* @deprecated
|
||||||
@ -133,66 +136,84 @@ public interface CordovaInterface {
|
|||||||
* @param id The message id
|
* @param id The message id
|
||||||
* @param data The message data
|
* @param data The message data
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
abstract public void postMessage(String id, Object data);
|
// abstract public void postMessage(String id, Object data);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Resources getResources();
|
// public abstract Resources getResources();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract String getPackageName();
|
// public abstract String getPackageName();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Object getSystemService(String service);
|
// public abstract Object getSystemService(String service);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Context getContext();
|
// public abstract Context getContext();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Context getBaseContext();
|
// public abstract Context getBaseContext();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Intent registerReceiver(BroadcastReceiver receiver,
|
// public abstract Intent registerReceiver(BroadcastReceiver receiver,
|
||||||
IntentFilter intentFilter);
|
// IntentFilter intentFilter);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract ContentResolver getContentResolver();
|
// public abstract ContentResolver getContentResolver();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract void unregisterReceiver(BroadcastReceiver receiver);
|
// public abstract void unregisterReceiver(BroadcastReceiver receiver);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
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);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract void runOnUiThread(Runnable runnable);
|
// public abstract void runOnUiThread(Runnable runnable);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract AssetManager getAssets();
|
// public abstract AssetManager getAssets();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract void clearCache();
|
// public abstract void clearCache();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract void clearHistory();
|
// public abstract void clearHistory();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract boolean backHistory();
|
// public abstract boolean backHistory();
|
||||||
|
|
||||||
//public abstract void addWhiteListEntry(String origin, boolean subdomains);
|
//public abstract void addWhiteListEntry(String origin, boolean subdomains);
|
||||||
|
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public abstract void cancelLoadUrl();
|
public abstract void cancelLoadUrl();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract void showWebPage(String url, boolean openExternal,
|
// public abstract void showWebPage(String url, boolean openExternal,
|
||||||
boolean clearHistory, HashMap<String, Object> params);
|
// boolean clearHistory, HashMap<String, Object> params);
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract Context getApplicationContext();
|
// public abstract Context getApplicationContext();
|
||||||
|
|
||||||
@Deprecated
|
// @Deprecated
|
||||||
public abstract boolean isUrlWhiteListed(String source);
|
// public abstract boolean isUrlWhiteListed(String source);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when a message is sent to plugin.
|
||||||
|
*
|
||||||
|
* @param id The message id
|
||||||
|
* @param data The message data
|
||||||
|
*/
|
||||||
|
public void onMessage(String id, Object data);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @param errorCode The error code corresponding to an ERROR_* value.
|
||||||
|
* @param description A String describing the error.
|
||||||
|
* @param failingUrl The url that failed to load.
|
||||||
|
*/
|
||||||
|
//public void onReceivedError(final int errorCode, final String description, final String failingUrl);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -21,9 +21,10 @@ package org.apache.cordova.api;
|
|||||||
import org.apache.cordova.CordovaWebView;
|
import org.apache.cordova.CordovaWebView;
|
||||||
import org.json.JSONArray;
|
import org.json.JSONArray;
|
||||||
|
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.webkit.WebView;
|
|
||||||
|
//import android.webkit.WebView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin interface must be implemented by any plugin classes.
|
* Plugin interface must be implemented by any plugin classes.
|
||||||
@ -56,7 +57,7 @@ public interface IPlugin {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
void setContext(Context ctx);
|
void setContext(CordovaInterface ctx);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sets the main View of the application, this is the WebView within which
|
* Sets the main View of the application, this is the WebView within which
|
||||||
|
@ -22,9 +22,10 @@ import org.apache.cordova.CordovaWebView;
|
|||||||
import org.json.JSONArray;
|
import org.json.JSONArray;
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.webkit.WebView;
|
|
||||||
|
//import android.webkit.WebView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin interface must be implemented by any plugin classes.
|
* Plugin interface must be implemented by any plugin classes.
|
||||||
@ -35,7 +36,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
|
|
||||||
public String id;
|
public String id;
|
||||||
public CordovaWebView webView; // WebView object
|
public CordovaWebView webView; // WebView object
|
||||||
public Context ctx; // CordovaActivity object
|
public CordovaInterface ctx; // CordovaActivity object
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes the request and returns PluginResult.
|
* Executes the request and returns PluginResult.
|
||||||
@ -63,7 +64,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
*
|
*
|
||||||
* @param ctx The context of the main Activity.
|
* @param ctx The context of the main Activity.
|
||||||
*/
|
*/
|
||||||
public void setContext(Context ctx) {
|
public void setContext(CordovaInterface ctx) {
|
||||||
this.ctx = ctx;
|
this.ctx = ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -143,7 +144,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param statement
|
* @param statement
|
||||||
*/
|
*/
|
||||||
public void sendJavascript(String statement) {
|
public void sendJavascript(String statement) {
|
||||||
webView.sendJavascript(statement);
|
this.webView.sendJavascript(statement);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -157,7 +158,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void success(PluginResult pluginResult, String callbackId) {
|
public void success(PluginResult pluginResult, String callbackId) {
|
||||||
webView.sendJavascript(pluginResult.toSuccessCallbackString(callbackId));
|
this.webView.sendJavascript(pluginResult.toSuccessCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -167,7 +168,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void success(JSONObject message, String callbackId) {
|
public void success(JSONObject message, String callbackId) {
|
||||||
webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
|
this.webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -177,7 +178,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void success(String message, String callbackId) {
|
public void success(String message, String callbackId) {
|
||||||
webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
|
this.webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -187,7 +188,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void error(PluginResult pluginResult, String callbackId) {
|
public void error(PluginResult pluginResult, String callbackId) {
|
||||||
webView.sendJavascript(pluginResult.toErrorCallbackString(callbackId));
|
this.webView.sendJavascript(pluginResult.toErrorCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -197,7 +198,7 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void error(JSONObject message, String callbackId) {
|
public void error(JSONObject message, String callbackId) {
|
||||||
webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
|
this.webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -207,6 +208,6 @@ public abstract class Plugin implements IPlugin {
|
|||||||
* @param callbackId The callback id used when calling back into JavaScript.
|
* @param callbackId The callback id used when calling back into JavaScript.
|
||||||
*/
|
*/
|
||||||
public void error(String message, String callbackId) {
|
public void error(String message, String callbackId) {
|
||||||
webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
|
this.webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,8 +20,8 @@ package org.apache.cordova.api;
|
|||||||
|
|
||||||
import org.apache.cordova.CordovaWebView;
|
import org.apache.cordova.CordovaWebView;
|
||||||
|
|
||||||
import android.content.Context;
|
//import android.content.Context;
|
||||||
import android.webkit.WebView;
|
//import android.webkit.WebView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents a service entry object.
|
* This class represents a service entry object.
|
||||||
@ -69,12 +69,12 @@ public class PluginEntry {
|
|||||||
*
|
*
|
||||||
* @return The plugin object
|
* @return The plugin object
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
public IPlugin createPlugin(CordovaWebView webView, CordovaInterface ctx) {
|
||||||
public IPlugin createPlugin(CordovaWebView webView, Context ctx) {
|
|
||||||
if (this.plugin != null) {
|
if (this.plugin != null) {
|
||||||
return this.plugin;
|
return this.plugin;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
Class c = getClassByName(this.pluginClass);
|
Class c = getClassByName(this.pluginClass);
|
||||||
if (isCordovaPlugin(c)) {
|
if (isCordovaPlugin(c)) {
|
||||||
this.plugin = (IPlugin) c.newInstance();
|
this.plugin = (IPlugin) c.newInstance();
|
||||||
@ -96,7 +96,7 @@ public class PluginEntry {
|
|||||||
* @return
|
* @return
|
||||||
* @throws ClassNotFoundException
|
* @throws ClassNotFoundException
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("rawtypes")
|
||||||
private Class getClassByName(final String clazz) throws ClassNotFoundException {
|
private Class getClassByName(final String clazz) throws ClassNotFoundException {
|
||||||
Class c = null;
|
Class c = null;
|
||||||
if (clazz != null) {
|
if (clazz != null) {
|
||||||
@ -112,7 +112,7 @@ public class PluginEntry {
|
|||||||
* @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
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("rawtypes")
|
||||||
private boolean isCordovaPlugin(Class c) {
|
private boolean isCordovaPlugin(Class c) {
|
||||||
if (c != null) {
|
if (c != null) {
|
||||||
return org.apache.cordova.api.Plugin.class.isAssignableFrom(c) || org.apache.cordova.api.IPlugin.class.isAssignableFrom(c);
|
return org.apache.cordova.api.Plugin.class.isAssignableFrom(c) || org.apache.cordova.api.IPlugin.class.isAssignableFrom(c);
|
||||||
|
@ -28,10 +28,8 @@ import org.json.JSONArray;
|
|||||||
import org.json.JSONException;
|
import org.json.JSONException;
|
||||||
import org.xmlpull.v1.XmlPullParserException;
|
import org.xmlpull.v1.XmlPullParserException;
|
||||||
|
|
||||||
import android.content.Context;
|
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.res.XmlResourceParser;
|
import android.content.res.XmlResourceParser;
|
||||||
import android.webkit.WebView;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PluginManager is exposed to JavaScript in the Cordova WebView.
|
* PluginManager is exposed to JavaScript in the Cordova WebView.
|
||||||
@ -45,7 +43,7 @@ public class PluginManager {
|
|||||||
// List of service entries
|
// List of service entries
|
||||||
private final HashMap<String, PluginEntry> entries = new HashMap<String, PluginEntry>();
|
private final HashMap<String, PluginEntry> entries = new HashMap<String, PluginEntry>();
|
||||||
|
|
||||||
private final Context ctx;
|
private final CordovaInterface ctx;
|
||||||
private final CordovaWebView app;
|
private final CordovaWebView app;
|
||||||
|
|
||||||
// Flag to track first time through
|
// Flag to track first time through
|
||||||
@ -61,26 +59,25 @@ public class PluginManager {
|
|||||||
* @param app
|
* @param app
|
||||||
* @param ctx
|
* @param ctx
|
||||||
*/
|
*/
|
||||||
public PluginManager(CordovaWebView app, Context ctx) {
|
public PluginManager(CordovaWebView app, CordovaInterface ctx) {
|
||||||
this.ctx = ctx;
|
this.ctx = ctx;
|
||||||
this.app = app;
|
this.app = app;
|
||||||
this.firstRun = true;
|
this.firstRun = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Called by com.phonegap.api.PluginManager only
|
||||||
public PluginManager(WebView mApp, CordovaInterface mCtx) throws Exception {
|
// public PluginManager(WebView mApp, CordovaInterface mCtx) throws Exception {
|
||||||
this.ctx = mCtx.getContext();
|
// this.ctx = mCtx; //mCtx.getContext();
|
||||||
if(CordovaWebView.class.isInstance(mApp))
|
// if (CordovaWebView.class.isInstance(mApp))
|
||||||
{
|
// {
|
||||||
this.app = (CordovaWebView) mApp;
|
// this.app = (CordovaWebView) mApp;
|
||||||
}
|
// }
|
||||||
else
|
// else
|
||||||
{
|
// {
|
||||||
//Throw an exception here
|
// //Throw an exception here
|
||||||
throw new Exception();
|
// throw new Exception();
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Init when loading a new HTML page into webview.
|
* Init when loading a new HTML page into webview.
|
||||||
@ -89,9 +86,9 @@ public class PluginManager {
|
|||||||
LOG.d(TAG, "init()");
|
LOG.d(TAG, "init()");
|
||||||
|
|
||||||
// If first time, then load plugins from plugins.xml file
|
// If first time, then load plugins from plugins.xml file
|
||||||
if (firstRun) {
|
if (this.firstRun) {
|
||||||
this.loadPlugins();
|
this.loadPlugins();
|
||||||
firstRun = false;
|
this.firstRun = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop plugins on current HTML page and discard plugin objects
|
// Stop plugins on current HTML page and discard plugin objects
|
||||||
@ -109,11 +106,11 @@ public class PluginManager {
|
|||||||
* Load plugins from res/xml/plugins.xml
|
* Load plugins from res/xml/plugins.xml
|
||||||
*/
|
*/
|
||||||
public void loadPlugins() {
|
public void loadPlugins() {
|
||||||
int id = ctx.getResources().getIdentifier("plugins", "xml", ctx.getPackageName());
|
int id = this.ctx.getActivity().getResources().getIdentifier("plugins", "xml", this.ctx.getActivity().getPackageName());
|
||||||
if (id == 0) {
|
if (id == 0) {
|
||||||
pluginConfigurationMissing();
|
this.pluginConfigurationMissing();
|
||||||
}
|
}
|
||||||
XmlResourceParser xml = ctx.getResources().getXml(id);
|
XmlResourceParser xml = this.ctx.getActivity().getResources().getXml(id);
|
||||||
int eventType = -1;
|
int eventType = -1;
|
||||||
String service = "", pluginClass = "";
|
String service = "", pluginClass = "";
|
||||||
boolean onload = false;
|
boolean onload = false;
|
||||||
@ -184,14 +181,13 @@ public class PluginManager {
|
|||||||
*
|
*
|
||||||
* @return JSON encoded string with a response message and status.
|
* @return JSON encoded string with a response message and status.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
public String exec(final String service, final String action, final String callbackId, final String jsonArgs, final boolean async) {
|
public String exec(final String service, final String action, final String callbackId, final String jsonArgs, final boolean async) {
|
||||||
PluginResult cr = null;
|
PluginResult cr = null;
|
||||||
boolean runAsync = async;
|
boolean runAsync = async;
|
||||||
try {
|
try {
|
||||||
final JSONArray args = new JSONArray(jsonArgs);
|
final JSONArray args = new JSONArray(jsonArgs);
|
||||||
final IPlugin plugin = this.getPlugin(service);
|
final IPlugin plugin = this.getPlugin(service);
|
||||||
final Context ctx = this.ctx;
|
//final CordovaInterface ctx = this.ctx;
|
||||||
if (plugin != null) {
|
if (plugin != null) {
|
||||||
runAsync = async && !plugin.isSynch(action);
|
runAsync = async && !plugin.isSynch(action);
|
||||||
if (runAsync) {
|
if (runAsync) {
|
||||||
@ -257,7 +253,7 @@ public class PluginManager {
|
|||||||
* @return IPlugin or null
|
* @return IPlugin or null
|
||||||
*/
|
*/
|
||||||
private IPlugin getPlugin(String service) {
|
private IPlugin getPlugin(String service) {
|
||||||
PluginEntry entry = entries.get(service);
|
PluginEntry entry = this.entries.get(service);
|
||||||
if (entry == null) {
|
if (entry == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -334,6 +330,7 @@ public class PluginManager {
|
|||||||
* @param data The message data
|
* @param data The message data
|
||||||
*/
|
*/
|
||||||
public void postMessage(String id, Object data) {
|
public void postMessage(String id, Object data) {
|
||||||
|
this.ctx.onMessage(id, data);
|
||||||
for (PluginEntry entry : this.entries.values()) {
|
for (PluginEntry entry : this.entries.values()) {
|
||||||
if (entry.plugin != null) {
|
if (entry.plugin != null) {
|
||||||
entry.plugin.onMessage(id, data);
|
entry.plugin.onMessage(id, data);
|
||||||
|
@ -21,7 +21,7 @@ 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;
|
//import android.util.Log;
|
||||||
|
|
||||||
public class PluginResult {
|
public class PluginResult {
|
||||||
private final int status;
|
private final int status;
|
||||||
@ -50,17 +50,17 @@ public class PluginResult {
|
|||||||
|
|
||||||
public PluginResult(Status status, int i) {
|
public PluginResult(Status status, int i) {
|
||||||
this.status = status.ordinal();
|
this.status = status.ordinal();
|
||||||
this.message = ""+i;
|
this.message = "" + i;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PluginResult(Status status, float f) {
|
public PluginResult(Status status, float f) {
|
||||||
this.status = status.ordinal();
|
this.status = status.ordinal();
|
||||||
this.message = ""+f;
|
this.message = "" + f;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PluginResult(Status status, boolean b) {
|
public PluginResult(Status status, boolean b) {
|
||||||
this.status = status.ordinal();
|
this.status = status.ordinal();
|
||||||
this.message = ""+b;
|
this.message = "" + b;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setKeepCallback(boolean b) {
|
public void setKeepCallback(boolean b) {
|
||||||
@ -84,11 +84,11 @@ public class PluginResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String toSuccessCallbackString(String callbackId) {
|
public String toSuccessCallbackString(String callbackId) {
|
||||||
return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
|
return "cordova.callbackSuccess('" + callbackId + "'," + this.getJSONString() + ");";
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toErrorCallbackString(String callbackId) {
|
public String toErrorCallbackString(String callbackId) {
|
||||||
return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
|
return "cordova.callbackError('" + callbackId + "', " + this.getJSONString() + ");";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String[] StatusMessages = new String[] {
|
public static String[] StatusMessages = new String[] {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user