mirror of
https://github.com/apache/cordova-android.git
synced 2026-04-23 00:00:09 +08:00
Merge branch 'master' of git://github.com/phonegap/phonegap-android
Conflicts: framework/src/com/phonegap/ContactManager.java
This commit is contained in:
@@ -105,13 +105,18 @@ public class AccelListener implements SensorEventListener, Plugin{
|
||||
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
|
||||
}
|
||||
// Wait until running
|
||||
while (this.status == STARTING) {
|
||||
long timeout = 2000;
|
||||
while ((this.status == STARTING) && (timeout > 0)) {
|
||||
timeout = timeout - 100;
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (timeout == 0) {
|
||||
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
|
||||
}
|
||||
}
|
||||
JSONObject r = new JSONObject();
|
||||
r.put("x", this.x);
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.phonegap;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
@@ -20,6 +21,7 @@ import android.graphics.Bitmap.CompressFormat;
|
||||
import android.net.Uri;
|
||||
import android.os.Environment;
|
||||
import android.webkit.WebView;
|
||||
import android.provider.MediaStore;
|
||||
|
||||
/**
|
||||
* This class launches the camera view, allows the user to take a picture, closes the camera view,
|
||||
@@ -28,12 +30,18 @@ import android.webkit.WebView;
|
||||
*/
|
||||
public class CameraLauncher implements Plugin {
|
||||
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
private static final int DATA_URL = 0; // Return base64 encoded string
|
||||
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
|
||||
|
||||
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
|
||||
private static final int CAMERA = 1; // Take picture from camera
|
||||
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
|
||||
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
|
||||
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
|
||||
private Uri imageUri; // Uri of captured image
|
||||
private boolean base64 = true;
|
||||
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
|
||||
private Uri imageUri; // Uri of captured image
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@@ -74,7 +82,20 @@ public class CameraLauncher implements Plugin {
|
||||
|
||||
try {
|
||||
if (action.equals("takePicture")) {
|
||||
this.takePicture(args.getInt(0), args.getString(1));
|
||||
int destType = DATA_URL;
|
||||
if (args.length() > 1) {
|
||||
destType = args.getInt(1);
|
||||
}
|
||||
int srcType = CAMERA;
|
||||
if (args.length() > 2) {
|
||||
srcType = args.getInt(2);
|
||||
}
|
||||
if (srcType == CAMERA) {
|
||||
this.takePicture(args.getInt(0), destType);
|
||||
}
|
||||
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
|
||||
this.getImage(srcType, destType);
|
||||
}
|
||||
}
|
||||
return new PluginResult(status, result);
|
||||
} catch (JSONException e) {
|
||||
@@ -130,12 +151,8 @@ public class CameraLauncher implements Plugin {
|
||||
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
|
||||
* @param returnType Set the type of image to return.
|
||||
*/
|
||||
public void takePicture(int quality, String returnType) {
|
||||
public void takePicture(int quality, int returnType) {
|
||||
this.mQuality = quality;
|
||||
this.base64 = false;
|
||||
if (returnType.equals("base64")) {
|
||||
this.base64 = true;
|
||||
}
|
||||
|
||||
// Display camera
|
||||
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
|
||||
@@ -146,7 +163,22 @@ public class CameraLauncher implements Plugin {
|
||||
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
|
||||
this.imageUri = Uri.fromFile(photo);
|
||||
|
||||
this.ctx.startActivityForResult((Plugin) this, intent);
|
||||
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get image from photo library.
|
||||
*
|
||||
* @param returnType
|
||||
*/
|
||||
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
|
||||
public void getImage(int srcType, int returnType) {
|
||||
Intent intent = new Intent();
|
||||
intent.setType("image/*");
|
||||
intent.setAction(Intent.ACTION_GET_CONTENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
|
||||
new String("Get Picture")), (srcType+1)*16 + returnType + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,61 +190,98 @@ public class CameraLauncher implements Plugin {
|
||||
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
|
||||
*/
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
|
||||
// Get src and dest types from request code
|
||||
int srcType = (requestCode/16) - 1;
|
||||
int destType = (requestCode % 16) - 1;
|
||||
|
||||
// If image available
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
try {
|
||||
// Read in bitmap of captured image
|
||||
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
|
||||
|
||||
// If CAMERA
|
||||
if (srcType == CAMERA) {
|
||||
|
||||
// If image available
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
try {
|
||||
// Read in bitmap of captured image
|
||||
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
|
||||
|
||||
// If sending base64 image back
|
||||
if (destType == DATA_URL) {
|
||||
this.processPicture(bitmap);
|
||||
}
|
||||
|
||||
// If sending filename back
|
||||
else if (destType == FILE_URI){
|
||||
// Create entry in media store for image
|
||||
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
|
||||
Uri uri = null;
|
||||
try {
|
||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println("Can't write to external media storage.");
|
||||
try {
|
||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
|
||||
} catch (UnsupportedOperationException ex) {
|
||||
System.out.println("Can't write to internal media storage.");
|
||||
this.failPicture("Error capturing image - no media storage found.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add compressed version of captured image to returned media store Uri
|
||||
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
|
||||
os.close();
|
||||
|
||||
// Send Uri back to JavaScript for viewing image
|
||||
this.ctx.sendJavascript("navigator.camera.success('" + uri.toString() + "');");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
this.failPicture("Error capturing image.");
|
||||
}
|
||||
}
|
||||
|
||||
// If cancelled
|
||||
else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Camera cancelled.");
|
||||
}
|
||||
|
||||
// If something else
|
||||
else {
|
||||
this.failPicture("Did not complete!");
|
||||
}
|
||||
}
|
||||
|
||||
// If retrieving photo from library
|
||||
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
Uri uri = intent.getData();
|
||||
android.content.ContentResolver resolver = this.ctx.getContentResolver();
|
||||
// If sending base64 image back
|
||||
if (this.base64) {
|
||||
this.processPicture(bitmap);
|
||||
if (destType == DATA_URL) {
|
||||
try {
|
||||
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
|
||||
this.processPicture(bitmap);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
this.failPicture("Error retrieving image.");
|
||||
}
|
||||
}
|
||||
|
||||
// If sending filename back
|
||||
else {
|
||||
// Create entry in media store for image
|
||||
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
|
||||
Uri uri = null;
|
||||
try {
|
||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println("Can't write to external media storage.");
|
||||
try {
|
||||
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
|
||||
} catch (UnsupportedOperationException ex) {
|
||||
System.out.println("Can't write to internal media storage.");
|
||||
this.failPicture("Error capturing image - no media storage found.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add compressed version of captured image to returned media store Uri
|
||||
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
|
||||
os.close();
|
||||
|
||||
// Send Uri back to JavaScript for viewing image
|
||||
this.ctx.sendJavascript("navigator.camera.success('" + uri.toString() + "');");
|
||||
else if (destType == FILE_URI) {
|
||||
this.ctx.sendJavascript("navigator.camera.success('" + uri + "');");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
this.failPicture("Error capturing image.");
|
||||
}
|
||||
}
|
||||
else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Selection cancelled.");
|
||||
}
|
||||
else {
|
||||
this.failPicture("Selection did not complete!");
|
||||
}
|
||||
}
|
||||
|
||||
// If cancelled
|
||||
else if (resultCode == Activity.RESULT_CANCELED) {
|
||||
this.failPicture("Camera cancelled.");
|
||||
}
|
||||
|
||||
// If something else
|
||||
else {
|
||||
this.failPicture("Did not complete!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -98,13 +98,18 @@ public class CompassListener implements SensorEventListener, Plugin{
|
||||
return new PluginResult(PluginResult.Status.IO_EXCEPTION, ERROR_FAILED_TO_START);
|
||||
}
|
||||
// Wait until running
|
||||
while (this.status == STARTING) {
|
||||
long timeout = 2000;
|
||||
while ((this.status == STARTING) && (timeout > 0)) {
|
||||
timeout = timeout - 100;
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (timeout == 0) {
|
||||
return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
|
||||
}
|
||||
}
|
||||
float f = this.getHeading();
|
||||
return new PluginResult(status, f);
|
||||
|
||||
@@ -6,33 +6,17 @@ import org.json.JSONException;
|
||||
import com.phonegap.api.Plugin;
|
||||
import com.phonegap.api.PluginResult;
|
||||
|
||||
import android.provider.Contacts.ContactMethods;
|
||||
import android.provider.Contacts.People;
|
||||
import android.util.Log;
|
||||
import android.webkit.WebView;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteException;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class ContactManager implements Plugin {
|
||||
|
||||
// public class ContactTriplet
|
||||
// {
|
||||
// public String name = "";
|
||||
// public String email = "";
|
||||
// public String phone = "";
|
||||
// }
|
||||
|
||||
private static ContactAccessor contactAccessor;
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
|
||||
private static final String LOG_TAG = "Contact Query";
|
||||
Uri mPeople = android.provider.Contacts.People.CONTENT_URI;
|
||||
Uri mPhone = android.provider.Contacts.Phones.CONTENT_URI;
|
||||
Uri mEmail = android.provider.Contacts.ContactMethods.CONTENT_URI;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@@ -75,16 +59,21 @@ public class ContactManager implements Plugin {
|
||||
String result = "";
|
||||
|
||||
try {
|
||||
//if (action.equals("getContactsAndSendBack")) {
|
||||
// contactAccessor.getContactsAndSendBack();
|
||||
//}
|
||||
//else if (action.equals("search")) {
|
||||
if (action.equals("search")) {
|
||||
Log.d(LOG_TAG, "Executing search using accessor");
|
||||
contactAccessor.search(args.getString(0), args.getString(1), args.getString(2));
|
||||
contactAccessor.search(args.getJSONArray(0), args.getJSONObject(1));
|
||||
}
|
||||
else if (action.equals("create")) {
|
||||
// TODO Coming soon!
|
||||
}
|
||||
else if (action.equals("save")) {
|
||||
// TODO Coming soon!
|
||||
}
|
||||
else if (action.equals("remove")) {
|
||||
// TODO Coming soon!
|
||||
}
|
||||
return new PluginResult(status, result);
|
||||
} catch (JSONException e) {
|
||||
Log.e(LOG_TAG, e.getMessage(), e);
|
||||
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
|
||||
}
|
||||
}
|
||||
@@ -129,269 +118,4 @@ public class ContactManager implements Plugin {
|
||||
*/
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// LOCAL METHODS
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// This is to add backwards compatibility to the OLD Contacts API\
|
||||
// public void getContactsAndSendBack()
|
||||
// {
|
||||
// String[] projection = new String[] {
|
||||
// People._ID,
|
||||
// People.NAME,
|
||||
// People.NUMBER,
|
||||
// People.PRIMARY_EMAIL_ID
|
||||
// };
|
||||
//
|
||||
// try{
|
||||
// Cursor myCursor = this.ctx.managedQuery(mPeople, projection,
|
||||
// null, null , People.NAME + " ASC");
|
||||
// processResults(myCursor, true);
|
||||
// }
|
||||
// catch (SQLiteException ex)
|
||||
// {
|
||||
// Log.d(LOG_TAG, ex.getMessage());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void search(String name, String npa, String email)
|
||||
// {
|
||||
//
|
||||
// if (email.length() > 0)
|
||||
// searchByEmail(email);
|
||||
// else
|
||||
// searchPeople(name, npa);
|
||||
// }
|
||||
//
|
||||
// private void searchByEmail(String email)
|
||||
// {
|
||||
// String[] projection = new String[] {
|
||||
// ContactMethods._ID,
|
||||
// ContactMethods.DATA,
|
||||
// ContactMethods.KIND,
|
||||
// ContactMethods.PERSON_ID
|
||||
// };
|
||||
// String[] variables = new String[] {
|
||||
// email
|
||||
// };
|
||||
//
|
||||
// try{
|
||||
// Cursor myCursor = this.ctx.managedQuery(mEmail, projection,
|
||||
// "contact_methods." + ContactMethods.DATA + " = ?" + "AND contact_methods.kind = 1", variables , ContactMethods.DATA + " ASC");
|
||||
// getMethodData(myCursor);
|
||||
//
|
||||
// }
|
||||
// catch (SQLiteException ex)
|
||||
// {
|
||||
// Log.d(LOG_TAG, ex.getMessage());
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private void searchPeople(String name, String number)
|
||||
// {
|
||||
// String conditions = "";
|
||||
//
|
||||
// if (name.length() == 0)
|
||||
// {
|
||||
// name = "%";
|
||||
// conditions += People.NAME + " LIKE ? AND ";
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// conditions += People.NAME + " = ? AND ";
|
||||
// }
|
||||
//
|
||||
// if (number.length() == 0)
|
||||
// number = "%";
|
||||
// else
|
||||
// {
|
||||
// number = number.replace('+', '%');
|
||||
// number = number.replace('.', '%');
|
||||
// number = number.replace('-', '%');
|
||||
// }
|
||||
//
|
||||
// conditions += People.NUMBER + " LIKE ? ";
|
||||
//
|
||||
// String[] projection = new String[] {
|
||||
// People._ID,
|
||||
// People.NAME,
|
||||
// People.NUMBER,
|
||||
// People.PRIMARY_EMAIL_ID
|
||||
// };
|
||||
//
|
||||
// String[] variables = new String[] {
|
||||
// name, number
|
||||
// };
|
||||
//
|
||||
// try{
|
||||
// Cursor myCursor = this.ctx.managedQuery(mPeople, projection,
|
||||
// conditions, variables , People.NAME + " ASC");
|
||||
// processResults(myCursor, false);
|
||||
// }
|
||||
// catch (SQLiteException ex)
|
||||
// {
|
||||
// Log.d(LOG_TAG, ex.getMessage());
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private void processResults(Cursor cur, boolean all){
|
||||
//
|
||||
// if (cur.moveToFirst()) {
|
||||
//
|
||||
// String name;
|
||||
// String phoneNumber;
|
||||
// String email_id;
|
||||
// String email;
|
||||
//
|
||||
// int nameColumn = cur.getColumnIndex(People.NAME);
|
||||
// int phoneColumn = cur.getColumnIndex(People.NUMBER);
|
||||
// int emailIdColumn = cur.getColumnIndex(People.PRIMARY_EMAIL_ID);
|
||||
//
|
||||
// do {
|
||||
// // Get the field values
|
||||
// name = cur.getString(nameColumn);
|
||||
// phoneNumber = cur.getString(phoneColumn);
|
||||
// email_id = cur.getString(emailIdColumn);
|
||||
// if (email_id != null && email_id.length() > 0)
|
||||
// email = getEmail(email_id);
|
||||
// else
|
||||
// email = "";
|
||||
//
|
||||
// // Code for backwards compatibility with the OLD Contacts API
|
||||
// if (all) {
|
||||
// this.ctx.sendJavascript("navigator.ContactManager.droidAddContact('" + name + "','" + phoneNumber + "','" + email +"');");
|
||||
// }
|
||||
// else {
|
||||
// this.ctx.sendJavascript("navigator.contacts.droidFoundContact('" + name + "','" + phoneNumber + "','" + email +"');");
|
||||
// }
|
||||
// } while (cur.moveToNext());
|
||||
// if (all) {
|
||||
// this.ctx.sendJavascript("navigator.ContactManager.droidDone();");
|
||||
// }
|
||||
// else {
|
||||
// this.ctx.sendJavascript("navigator.contacts.droidDone();");
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// if (all) {
|
||||
// this.ctx.sendJavascript("navigator.ContactManager.fail();");
|
||||
// }
|
||||
// else {
|
||||
// this.ctx.sendJavascript("navigator.contacts.fail('None found!');");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void getMethodData(Cursor cur)
|
||||
// {
|
||||
// ContactTriplet data = new ContactTriplet();
|
||||
// String id;
|
||||
// String email;
|
||||
//
|
||||
// if (cur.moveToFirst()) {
|
||||
//
|
||||
// int idColumn = cur.getColumnIndex(ContactMethods._ID);
|
||||
// int emailColumn = cur.getColumnIndex(ContactMethods.DATA);
|
||||
// do {
|
||||
// // Get the field values
|
||||
// id = cur.getString(idColumn);
|
||||
// email = cur.getString(emailColumn);
|
||||
//
|
||||
// data = getContactData(id);
|
||||
// if(data != null)
|
||||
// {
|
||||
// data.email = email;
|
||||
// this.ctx.sendJavascript("navigator.Contacts.droidFoundContact('" + data.name + "','" + data.phone + "','" + data.email +"');");
|
||||
// }
|
||||
// } while (cur.moveToNext());
|
||||
// this.ctx.sendJavascript("navigator.contacts.droidDoneContacts();");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private ContactTriplet getContactData(String id) {
|
||||
// ContactTriplet data = null;
|
||||
// String[] projection = new String[] {
|
||||
// People._ID,
|
||||
// People.NAME,
|
||||
// People.NUMBER,
|
||||
// People.PRIMARY_EMAIL_ID
|
||||
// };
|
||||
//
|
||||
// String[] variables = new String[] {
|
||||
// id
|
||||
// };
|
||||
//
|
||||
// try{
|
||||
// Cursor myCursor = this.ctx.managedQuery(mPeople, projection,
|
||||
// People.PRIMARY_EMAIL_ID + " = ?", variables , People.NAME + " ASC");
|
||||
// data = getTriplet(myCursor);
|
||||
// }
|
||||
// catch (SQLiteException ex)
|
||||
// {
|
||||
// Log.d(LOG_TAG, ex.getMessage());
|
||||
// }
|
||||
//
|
||||
// return data;
|
||||
// }
|
||||
//
|
||||
// private ContactTriplet getTriplet(Cursor cur) {
|
||||
// ContactTriplet data = new ContactTriplet();
|
||||
// if (cur.moveToFirst()) {
|
||||
//
|
||||
// int nameColumn = cur.getColumnIndex(People.NAME);
|
||||
// int numberColumn = cur.getColumnIndex(People.NUMBER);
|
||||
// do {
|
||||
//
|
||||
// data.name = cur.getString(nameColumn);
|
||||
// data.phone = cur.getString(numberColumn);
|
||||
//
|
||||
// } while (cur.moveToNext());
|
||||
// }
|
||||
// return data;
|
||||
// }
|
||||
//
|
||||
// private String getEmailColumnData(Cursor cur)
|
||||
// {
|
||||
// String email = "";
|
||||
// if (cur != null && cur.moveToFirst()) {
|
||||
// int emailColumn = cur.getColumnIndex(ContactMethods.DATA);
|
||||
// do {
|
||||
// // Get the field values
|
||||
// email = cur.getString(emailColumn);
|
||||
// } while (cur.moveToNext());
|
||||
// }
|
||||
// return email;
|
||||
// }
|
||||
//
|
||||
// private String getEmail(String id)
|
||||
// {
|
||||
// String email = "";
|
||||
// String[] projection = new String[] {
|
||||
// ContactMethods._ID,
|
||||
// ContactMethods.DATA,
|
||||
// ContactMethods.KIND
|
||||
// };
|
||||
// String[] variables = new String[] {
|
||||
// id
|
||||
// };
|
||||
//
|
||||
// try
|
||||
// {
|
||||
// Cursor myCursor = this.ctx.managedQuery(mEmail, projection,
|
||||
// "contact_methods." + ContactMethods._ID + " = ?" + " AND contact_methods.kind = 1", variables , ContactMethods.DATA + " ASC");
|
||||
// email = getEmailColumnData(myCursor);
|
||||
// }
|
||||
// catch (SQLiteException ex)
|
||||
// {
|
||||
// Log.d(LOG_TAG, ex.getMessage());
|
||||
// }
|
||||
//
|
||||
// return email;
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -24,7 +24,15 @@ package com.phonegap;
|
||||
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import com.phonegap.api.Plugin;
|
||||
import com.phonegap.api.PluginResult;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Vibrator;
|
||||
import android.provider.Settings;
|
||||
@@ -33,76 +41,210 @@ import android.webkit.WebView;
|
||||
import android.media.Ringtone;
|
||||
import android.media.RingtoneManager;
|
||||
|
||||
public class Device{
|
||||
public class Device implements Plugin {
|
||||
|
||||
private static final String LOG_TAG = "PhoneGap";
|
||||
/*
|
||||
* UUID, version and availability
|
||||
*/
|
||||
public boolean droid = true;
|
||||
public static String version = "0.91";
|
||||
public static String platform = "Android";
|
||||
public static String uuid;
|
||||
private Context mCtx;
|
||||
private WebView mAppView;
|
||||
AudioPlayer audio;
|
||||
public static String phonegapVersion = "pre-0.92 EDGE"; // PhoneGap version
|
||||
public static String platform = "Android"; // Device OS
|
||||
public static String uuid; // Device UUID
|
||||
private DroidGap ctx; // DroidGap object
|
||||
@SuppressWarnings("unused")
|
||||
private WebView webView; // Webview object
|
||||
|
||||
public Device(WebView appView, Context ctx) {
|
||||
this.mCtx = ctx;
|
||||
this.mAppView = appView;
|
||||
uuid = getUuid();
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public Device() {
|
||||
}
|
||||
|
||||
public void beep(long pattern)
|
||||
{
|
||||
/**
|
||||
* Sets the context of the Command. This can then be used to do things like
|
||||
* get file paths associated with the Activity.
|
||||
*
|
||||
* @param ctx The context of the main Activity.
|
||||
*/
|
||||
public void setContext(DroidGap ctx) {
|
||||
this.ctx = ctx;
|
||||
Device.uuid = getUuid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the main View of the application, this is the WebView within which
|
||||
* a PhoneGap app runs.
|
||||
*
|
||||
* @param webView The PhoneGap WebView
|
||||
*/
|
||||
public void setView(WebView webView) {
|
||||
this.webView = webView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the request and returns CommandResult.
|
||||
*
|
||||
* @param action The command to execute.
|
||||
* @param args JSONArry of arguments for the command.
|
||||
* @return A CommandResult object with a status and message.
|
||||
*/
|
||||
public PluginResult execute(String action, JSONArray args) {
|
||||
PluginResult.Status status = PluginResult.Status.OK;
|
||||
String result = "";
|
||||
|
||||
try {
|
||||
if (action.equals("getDeviceInfo")) {
|
||||
JSONObject r = new JSONObject();
|
||||
r.put("uuid", Device.uuid);
|
||||
r.put("version", this.getOSVersion());
|
||||
r.put("platform", Device.platform);
|
||||
r.put("name", this.getProductName());
|
||||
r.put("phonegap", Device.phonegapVersion);
|
||||
//JSONObject pg = new JSONObject();
|
||||
//pg.put("version", Device.phonegapVersion);
|
||||
//r.put("phonegap", pg);
|
||||
return new PluginResult(status, r);
|
||||
}
|
||||
else if (action.equals("beep")) {
|
||||
this.beep(args.getLong(0));
|
||||
}
|
||||
else if (action.equals("vibrate")) {
|
||||
this.vibrate(args.getLong(0));
|
||||
}
|
||||
return new PluginResult(status, result);
|
||||
} catch (JSONException e) {
|
||||
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies if action to be executed returns a value and should be run synchronously.
|
||||
*
|
||||
* @param action The action to execute
|
||||
* @return T=returns value
|
||||
*/
|
||||
public boolean isSynch(String action) {
|
||||
if (action.equals("getDeviceInfo")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the system is about to start resuming a previous activity.
|
||||
*/
|
||||
public void onPause() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the activity will start interacting with the user.
|
||||
*/
|
||||
public void onResume() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the activity is to be shut down.
|
||||
* Stop listener.
|
||||
*/
|
||||
public void onDestroy() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an activity you launched exits, giving you the requestCode you started it with,
|
||||
* the resultCode it returned, and any additional data from it.
|
||||
*
|
||||
* @param requestCode The request code originally supplied to startActivityForResult(),
|
||||
* allowing you to identify who this result came from.
|
||||
* @param resultCode The integer result code returned by the child activity through its setResult().
|
||||
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
|
||||
*/
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// LOCAL METHODS
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Beep plays the default notification ringtone.
|
||||
*
|
||||
* @param count Number of times to play notification
|
||||
*/
|
||||
public void beep(long count) {
|
||||
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
|
||||
Ringtone notification = RingtoneManager.getRingtone(mCtx, ringtone);
|
||||
if (notification != null) { // This will be the case when the phone is set to silent for example
|
||||
for (long i = 0; i < pattern; ++i)
|
||||
{
|
||||
Ringtone notification = RingtoneManager.getRingtone(this.ctx, ringtone);
|
||||
|
||||
// If phone is not set to silent mode
|
||||
if (notification != null) {
|
||||
for (long i = 0; i < count; ++i) {
|
||||
notification.play();
|
||||
long timeout = 5000;
|
||||
while (notification.isPlaying() && (timeout > 0)) {
|
||||
timeout = timeout - 100;
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void vibrate(long pattern){
|
||||
/**
|
||||
* Vibrates the device for the specified amount of time.
|
||||
*
|
||||
* @param time Time to vibrate in ms.
|
||||
*/
|
||||
public void vibrate(long time){
|
||||
// Start the vibration, 0 defaults to half a second.
|
||||
if (pattern == 0)
|
||||
pattern = 500;
|
||||
Vibrator vibrator = (Vibrator) mCtx.getSystemService(Context.VIBRATOR_SERVICE);
|
||||
vibrator.vibrate(pattern);
|
||||
if (time == 0) {
|
||||
time = 500;
|
||||
}
|
||||
Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE);
|
||||
vibrator.vibrate(time);
|
||||
}
|
||||
|
||||
public String getPlatform()
|
||||
{
|
||||
return this.platform;
|
||||
/**
|
||||
* Get the OS name.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getPlatform() {
|
||||
return Device.platform;
|
||||
}
|
||||
|
||||
public String getUuid()
|
||||
{
|
||||
//TelephonyManager operator = (TelephonyManager) mCtx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
//String uuid = operator.getDeviceId();
|
||||
String uuid = Settings.Secure.getString(mCtx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
|
||||
/**
|
||||
* Get the device's Universally Unique Identifier (UUID).
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getUuid() {
|
||||
String uuid = Settings.Secure.getString(this.ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PhoneGap version.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getPhonegapVersion() {
|
||||
return Device.phonegapVersion;
|
||||
}
|
||||
|
||||
public String getLine1Number(){
|
||||
TelephonyManager operator = (TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
TelephonyManager operator = (TelephonyManager)this.ctx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
return operator.getLine1Number();
|
||||
}
|
||||
|
||||
public String getDeviceId(){
|
||||
TelephonyManager operator = (TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
TelephonyManager operator = (TelephonyManager)this.ctx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
return operator.getDeviceId();
|
||||
}
|
||||
|
||||
public String getSimSerialNumber(){
|
||||
TelephonyManager operator = (TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
TelephonyManager operator = (TelephonyManager)this.ctx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
return operator.getSimSerialNumber();
|
||||
}
|
||||
|
||||
public String getSubscriberId(){
|
||||
TelephonyManager operator = (TelephonyManager)mCtx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
TelephonyManager operator = (TelephonyManager)this.ctx.getSystemService(Context.TELEPHONY_SERVICE);
|
||||
return operator.getSubscriberId();
|
||||
}
|
||||
|
||||
@@ -116,21 +258,23 @@ public class Device{
|
||||
String productname = android.os.Build.PRODUCT;
|
||||
return productname;
|
||||
}
|
||||
public String getOSVersion()
|
||||
{
|
||||
|
||||
/**
|
||||
* Get the OS version.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getOSVersion() {
|
||||
String osversion = android.os.Build.VERSION.RELEASE;
|
||||
return osversion;
|
||||
}
|
||||
|
||||
public String getSDKVersion()
|
||||
{
|
||||
String sdkversion = android.os.Build.VERSION.SDK;
|
||||
return sdkversion;
|
||||
}
|
||||
|
||||
public String getVersion()
|
||||
{
|
||||
return version;
|
||||
}
|
||||
|
||||
public String getTimeZoneID() {
|
||||
TimeZone tz = TimeZone.getDefault();
|
||||
|
||||
@@ -6,26 +6,47 @@ import android.os.Environment;
|
||||
import android.os.StatFs;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* This class provides file directory utilities.
|
||||
* All file operations are performed on the SD card.
|
||||
*
|
||||
* It is used by the FileUtils class.
|
||||
*/
|
||||
public class DirectoryManager {
|
||||
|
||||
protected static boolean testFileExists (String name){
|
||||
/**
|
||||
* Determine if a file or directory exists.
|
||||
*
|
||||
* @param name The name of the file to check.
|
||||
* @return T=exists, F=not found
|
||||
*/
|
||||
protected static boolean testFileExists(String name) {
|
||||
boolean status;
|
||||
if ((testSaveLocationExists())&&(!name.equals(""))){
|
||||
|
||||
// If SD card exists
|
||||
if ((testSaveLocationExists()) && (!name.equals(""))) {
|
||||
File path = Environment.getExternalStorageDirectory();
|
||||
File newPath = constructFilePaths(path.toString(), name);
|
||||
status = newPath.exists();
|
||||
}else{
|
||||
}
|
||||
|
||||
// If no SD card
|
||||
else{
|
||||
status = false;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
protected static long getFreeDiskSpace(){
|
||||
/*
|
||||
* gets the available SD card free space or returns -1 if the SD card is not mounted.
|
||||
*/
|
||||
/**
|
||||
* Get the free disk space on the SD card
|
||||
*
|
||||
* @return Size in KB or -1 if not available
|
||||
*/
|
||||
protected static long getFreeDiskSpace() {
|
||||
String status = Environment.getExternalStorageState();
|
||||
long freeSpace = 0;
|
||||
|
||||
// If SD card exists
|
||||
if (status.equals(Environment.MEDIA_MOUNTED)) {
|
||||
try {
|
||||
File path = Environment.getExternalStorageDirectory();
|
||||
@@ -34,44 +55,82 @@ public class DirectoryManager {
|
||||
long availableBlocks = stat.getAvailableBlocks();
|
||||
freeSpace = availableBlocks*blockSize/1024;
|
||||
} catch (Exception e) {e.printStackTrace(); }
|
||||
} else { return -1; }
|
||||
}
|
||||
|
||||
// If no SD card, then return -1
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return (freeSpace);
|
||||
}
|
||||
|
||||
protected static boolean createDirectory(String directoryName){
|
||||
/**
|
||||
* Create directory on SD card.
|
||||
*
|
||||
* @param directoryName The name of the directory to create.
|
||||
* @return T=successful, F=failed
|
||||
*/
|
||||
protected static boolean createDirectory(String directoryName) {
|
||||
boolean status;
|
||||
if ((testSaveLocationExists())&&(!directoryName.equals(""))){
|
||||
|
||||
// Make sure SD card exists
|
||||
if ((testSaveLocationExists()) && (!directoryName.equals(""))) {
|
||||
File path = Environment.getExternalStorageDirectory();
|
||||
File newPath = constructFilePaths(path.toString(), directoryName);
|
||||
status = newPath.mkdir();
|
||||
status = true;
|
||||
}else
|
||||
}
|
||||
|
||||
// If no SD card or invalid dir name
|
||||
else {
|
||||
status = false;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
protected static boolean testSaveLocationExists(){
|
||||
/**
|
||||
* Determine if SD card exists.
|
||||
*
|
||||
* @return T=exists, F=not found
|
||||
*/
|
||||
protected static boolean testSaveLocationExists() {
|
||||
String sDCardStatus = Environment.getExternalStorageState();
|
||||
boolean status;
|
||||
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)){
|
||||
|
||||
// If SD card is mounted
|
||||
if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
|
||||
status = true;
|
||||
}else
|
||||
}
|
||||
|
||||
// If no SD card
|
||||
else {
|
||||
status = false;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
protected static boolean deleteDirectory(String fileName){
|
||||
/**
|
||||
* Delete directory.
|
||||
*
|
||||
* @param fileName The name of the directory to delete
|
||||
* @return T=deleted, F=could not delete
|
||||
*/
|
||||
protected static boolean deleteDirectory(String fileName) {
|
||||
boolean status;
|
||||
SecurityManager checker = new SecurityManager();
|
||||
|
||||
if ((testSaveLocationExists())&&(!fileName.equals(""))){
|
||||
|
||||
// Make sure SD card exists
|
||||
if ((testSaveLocationExists()) && (!fileName.equals(""))) {
|
||||
File path = Environment.getExternalStorageDirectory();
|
||||
File newPath = constructFilePaths(path.toString(), fileName);
|
||||
checker.checkDelete(newPath.toString());
|
||||
if(newPath.isDirectory()){
|
||||
|
||||
// If dir to delete is really a directory
|
||||
if (newPath.isDirectory()) {
|
||||
String[] listfile = newPath.list();
|
||||
// delete all files within the specified directory and then delete the directory
|
||||
|
||||
// Delete all files within the specified directory and then delete the directory
|
||||
try{
|
||||
for (int i=0; i < listfile.length; i++){
|
||||
File deletedFile = new File (newPath.toString()+"/"+listfile[i].toString());
|
||||
@@ -80,27 +139,43 @@ public class DirectoryManager {
|
||||
newPath.delete();
|
||||
Log.i("DirectoryManager deleteDirectory", fileName);
|
||||
status = true;
|
||||
}catch (Exception e){
|
||||
}
|
||||
catch (Exception e){
|
||||
e.printStackTrace();
|
||||
status = false;
|
||||
}
|
||||
|
||||
}else
|
||||
}
|
||||
|
||||
// If dir not a directory, then error
|
||||
else {
|
||||
status = false;
|
||||
}else
|
||||
}
|
||||
}
|
||||
|
||||
// If no SD card
|
||||
else {
|
||||
status = false;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
protected static boolean deleteFile(String fileName){
|
||||
/**
|
||||
* Delete file.
|
||||
*
|
||||
* @param fileName The name of the file to delete
|
||||
* @return T=deleted, F=not deleted
|
||||
*/
|
||||
protected static boolean deleteFile(String fileName) {
|
||||
boolean status;
|
||||
SecurityManager checker = new SecurityManager();
|
||||
|
||||
if ((testSaveLocationExists())&&(!fileName.equals(""))){
|
||||
|
||||
// Make sure SD card exists
|
||||
if ((testSaveLocationExists()) && (!fileName.equals(""))) {
|
||||
File path = Environment.getExternalStorageDirectory();
|
||||
File newPath = constructFilePaths(path.toString(), fileName);
|
||||
checker.checkDelete(newPath.toString());
|
||||
|
||||
// If file to delete is really a file
|
||||
if (newPath.isFile()){
|
||||
try {
|
||||
Log.i("DirectoryManager deleteFile", fileName);
|
||||
@@ -110,14 +185,28 @@ public class DirectoryManager {
|
||||
se.printStackTrace();
|
||||
status = false;
|
||||
}
|
||||
}else
|
||||
}
|
||||
// If not a file, then error
|
||||
else {
|
||||
status = false;
|
||||
}else
|
||||
}
|
||||
}
|
||||
|
||||
// If no SD card
|
||||
else {
|
||||
status = false;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
private static File constructFilePaths (String file1, String file2){
|
||||
/**
|
||||
* Create a new file object from two file paths.
|
||||
*
|
||||
* @param file1 Base file path
|
||||
* @param file2 Remaining file path
|
||||
* @return File object
|
||||
*/
|
||||
private static File constructFilePaths (String file1, String file2) {
|
||||
File newPath;
|
||||
newPath = new File(file1+"/"+file2);
|
||||
return newPath;
|
||||
|
||||
@@ -25,7 +25,6 @@ package com.phonegap;
|
||||
|
||||
|
||||
import com.phonegap.api.Plugin;
|
||||
import java.util.HashMap;
|
||||
import com.phonegap.api.PluginManager;
|
||||
|
||||
import android.app.Activity;
|
||||
@@ -83,8 +82,6 @@ public class DroidGap extends Activity {
|
||||
protected Boolean loadInWebView = false;
|
||||
private LinearLayout root;
|
||||
|
||||
private Device gap;
|
||||
private FileUtils fs;
|
||||
private BrowserKey mKey;
|
||||
public CallbackServer callbackServer;
|
||||
private PluginManager pluginManager;
|
||||
@@ -92,10 +89,8 @@ public class DroidGap extends Activity {
|
||||
private String url; // The initial URL for our app
|
||||
private String baseUrl; // The base of the initial URL for our app
|
||||
|
||||
// Variables to manage ActivityResultCallbacks
|
||||
private int activityResultCallbackCounter = 1000;
|
||||
private HashMap<Integer,Plugin> activityResultCallbacks = new HashMap<Integer,Plugin>();
|
||||
|
||||
private Plugin activityResultCallback = null; // Plugin to call when activity result is received
|
||||
|
||||
/**
|
||||
* Called when the activity is first created.
|
||||
*
|
||||
@@ -270,15 +265,11 @@ public class DroidGap extends Activity {
|
||||
private void bindBrowser(WebView appView) {
|
||||
this.callbackServer = new CallbackServer();
|
||||
this.pluginManager = new PluginManager(appView, this);
|
||||
this.gap = new Device(appView, this);
|
||||
this.fs = new FileUtils(appView, this);
|
||||
this.mKey = new BrowserKey(appView, this);
|
||||
|
||||
// This creates the new javascript interfaces for PhoneGap
|
||||
appView.addJavascriptInterface(this.pluginManager, "PluginManager");
|
||||
appView.addJavascriptInterface(this.gap, "DroidGap");
|
||||
|
||||
appView.addJavascriptInterface(this.fs, "FileUtil");
|
||||
appView.addJavascriptInterface(this.mKey, "BackButton");
|
||||
|
||||
appView.addJavascriptInterface(this.callbackServer, "CallbackServer");
|
||||
@@ -291,16 +282,18 @@ public class DroidGap extends Activity {
|
||||
Storage cupcakeStorage = (Storage)this.pluginManager.addPlugin("com.phonegap.Storage");
|
||||
cupcakeStorage.setStorage(appPackage);
|
||||
|
||||
this.pluginManager.addPlugin("com.phonegap.GeoBroker");
|
||||
|
||||
}
|
||||
|
||||
this.addService("Geolocation", "com.phonegap.GeoBroker");
|
||||
this.addService("Device", "com.phonegap.Device");
|
||||
this.addService("Accelerometer", "com.phonegap.AccelListener");
|
||||
this.addService("Compass", "com.phonegap.CompassListener");
|
||||
this.addService("Media", "com.phonegap.AudioHandler");
|
||||
this.addService("Camera", "com.phonegap.CameraLauncher");
|
||||
this.addService("Contacts", "com.phonegap.ContactManager");
|
||||
this.addService("Crypto", "com.phonegap.CryptoHandler");
|
||||
this.addService("File", "com.phonegap.FileUtils");
|
||||
this.addService("Location", "com.phonegap.GeoBroker");
|
||||
this.addService("Network Status", "com.phonegap.NetworkManager");
|
||||
this.addService("Storage", "com.phonegap.Storage");
|
||||
@@ -679,13 +672,11 @@ public class DroidGap extends Activity {
|
||||
*
|
||||
* @param command The command object
|
||||
* @param intent The intent to start
|
||||
* @return The request code to use for the callback
|
||||
* @param requestCode The request code that is passed to callback to identify the activity
|
||||
*/
|
||||
public int startActivityForResult(Plugin command, Intent intent) {
|
||||
int requestCode = this.activityResultCallbackCounter++;
|
||||
this.activityResultCallbacks.put(requestCode, command);
|
||||
public void startActivityForResult(Plugin command, Intent intent, int requestCode) {
|
||||
this.activityResultCallback = command;
|
||||
super.startActivityForResult(intent, requestCode);
|
||||
return requestCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -700,8 +691,7 @@ public class DroidGap extends Activity {
|
||||
*/
|
||||
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
super.onActivityResult(requestCode, resultCode, intent);
|
||||
|
||||
Plugin callback = this.activityResultCallbacks.remove(requestCode);
|
||||
Plugin callback = this.activityResultCallback;
|
||||
if (callback != null) {
|
||||
callback.onActivityResult(requestCode, resultCode, intent);
|
||||
}
|
||||
|
||||
Regular → Executable
+240
-99
@@ -2,123 +2,264 @@ package com.phonegap;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
|
||||
import com.phonegap.api.Plugin;
|
||||
import com.phonegap.api.PluginResult;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.webkit.WebView;
|
||||
|
||||
public class FileUtils {
|
||||
/**
|
||||
* This class provides SD card file and directory services to JavaScript.
|
||||
* Only files on the SD card can be accessed.
|
||||
*/
|
||||
public class FileUtils implements Plugin {
|
||||
|
||||
public static int NOT_FOUND_ERR = 8;
|
||||
public static int SECURITY_ERR = 18;
|
||||
public static int ABORT_ERR = 20;
|
||||
|
||||
public static int NOT_READABLE_ERR = 24;
|
||||
public static int ENCODING_ERR = 26;
|
||||
|
||||
|
||||
WebView mView;
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
|
||||
FileReader f_in;
|
||||
FileWriter f_out;
|
||||
|
||||
public FileUtils(WebView view, DroidGap gap)
|
||||
{
|
||||
mView = view;
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public FileUtils() {
|
||||
System.out.println("FileUtils()");
|
||||
}
|
||||
|
||||
public int testSaveLocationExists(){
|
||||
if (DirectoryManager.testSaveLocationExists())
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
public long getFreeDiskSpace(){
|
||||
long freeDiskSpace=DirectoryManager.getFreeDiskSpace();
|
||||
return freeDiskSpace;
|
||||
}
|
||||
|
||||
public int testFileExists(String file){
|
||||
if (DirectoryManager.testFileExists(file))
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
public int testDirectoryExists(String file){
|
||||
if (DirectoryManager.testFileExists(file))
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a specific directory.
|
||||
* Everyting in side the directory would be gone.
|
||||
* TODO: JavaScript Call backs for success and error handling
|
||||
/**
|
||||
* Sets the context of the Command. This can then be used to do things like
|
||||
* get file paths associated with the Activity.
|
||||
*
|
||||
* @param ctx The context of the main Activity.
|
||||
*/
|
||||
public int deleteDirectory (String dir){
|
||||
if (DirectoryManager.deleteDirectory(dir))
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
public void setContext(DroidGap ctx) {
|
||||
this.ctx = ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a specific file.
|
||||
* TODO: JavaScript Call backs for success and error handling
|
||||
/**
|
||||
* Sets the main View of the application, this is the WebView within which
|
||||
* a PhoneGap app runs.
|
||||
*
|
||||
* @param webView The PhoneGap WebView
|
||||
*/
|
||||
public int deleteFile (String file){
|
||||
if (DirectoryManager.deleteFile(file))
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
public void setView(WebView webView) {
|
||||
this.webView = webView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new directory.
|
||||
* TODO: JavaScript Call backs for success and error handling
|
||||
/**
|
||||
* Executes the request and returns CommandResult.
|
||||
*
|
||||
* @param action The command to execute.
|
||||
* @param args JSONArry of arguments for the command.
|
||||
* @return A CommandResult object with a status and message.
|
||||
*/
|
||||
public int createDirectory(String dir){
|
||||
if (DirectoryManager.createDirectory(dir))
|
||||
return 0;
|
||||
else
|
||||
return 1;
|
||||
}
|
||||
|
||||
public String read(String filename)
|
||||
{
|
||||
String data = "";
|
||||
String output = "";
|
||||
try {
|
||||
FileInputStream fstream = new FileInputStream(filename);
|
||||
DataInputStream in = new DataInputStream(fstream);
|
||||
while (in.available() !=0)
|
||||
{
|
||||
data += in.readLine();
|
||||
}
|
||||
|
||||
} catch (FileNotFoundException e) {
|
||||
data = "FAIL: File not found";
|
||||
} catch (IOException e) {
|
||||
data = "FAIL: IO ERROR";
|
||||
}
|
||||
public PluginResult execute(String action, JSONArray args) {
|
||||
PluginResult.Status status = PluginResult.Status.OK;
|
||||
String result = "";
|
||||
//System.out.println("FileUtils.execute("+action+")");
|
||||
|
||||
//mView.loadUrl("javascript:navigator.FileReader.hasRead('" + data + "')");
|
||||
try {
|
||||
if (action.equals("testSaveLocationExists")) {
|
||||
boolean b = DirectoryManager.testSaveLocationExists();
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("getFreeDiskSpace")) {
|
||||
long l = DirectoryManager.getFreeDiskSpace();
|
||||
return new PluginResult(status, l);
|
||||
}
|
||||
else if (action.equals("testFileExists")) {
|
||||
boolean b = DirectoryManager.testFileExists(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("testDirectoryExists")) {
|
||||
boolean b = DirectoryManager.testFileExists(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("deleteDirectory")) {
|
||||
boolean b = DirectoryManager.deleteDirectory(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("deleteFile")) {
|
||||
boolean b = DirectoryManager.deleteFile(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("createDirectory")) {
|
||||
boolean b = DirectoryManager.createDirectory(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("readAsText")) {
|
||||
try {
|
||||
String s = this.readAsText(args.getString(0), args.getString(1));
|
||||
return new PluginResult(status, s);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
|
||||
}
|
||||
}
|
||||
else if (action.equals("readAsDataURL")) {
|
||||
try {
|
||||
String s = this.readAsDataURL(args.getString(0));
|
||||
return new PluginResult(status, s);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
|
||||
}
|
||||
}
|
||||
else if (action.equals("writeAsText")) {
|
||||
try {
|
||||
this.writeAsText(args.getString(0), args.getString(1), args.getBoolean(2));
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
|
||||
}
|
||||
}
|
||||
return new PluginResult(status, result);
|
||||
} catch (JSONException e) {
|
||||
e.printStackTrace();
|
||||
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies if action to be executed returns a value and should be run synchronously.
|
||||
*
|
||||
* @param action The action to execute
|
||||
* @return T=returns value
|
||||
*/
|
||||
public boolean isSynch(String action) {
|
||||
if (action.equals("readAsText")) {
|
||||
return false;
|
||||
}
|
||||
else if (action.equals("readAsDataURL")) {
|
||||
return false;
|
||||
}
|
||||
else if (action.equals("writeAsText")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the system is about to start resuming a previous activity.
|
||||
*/
|
||||
public void onPause() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the activity will start interacting with the user.
|
||||
*/
|
||||
public void onResume() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by AccelBroker when listener is to be shut down.
|
||||
* Stop listener.
|
||||
*/
|
||||
public void onDestroy() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an activity you launched exits, giving you the requestCode you started it with,
|
||||
* the resultCode it returned, and any additional data from it.
|
||||
*
|
||||
* @param requestCode The request code originally supplied to startActivityForResult(),
|
||||
* allowing you to identify who this result came from.
|
||||
* @param resultCode The integer result code returned by the child activity through its setResult().
|
||||
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
|
||||
*/
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// LOCAL METHODS
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Read content of text file.
|
||||
*
|
||||
* @param filename The name of the file.
|
||||
* @param encoding The encoding to return contents as. Typical value is UTF-8.
|
||||
* (see http://www.iana.org/assignments/character-sets)
|
||||
* @return Contents of file.
|
||||
* @throws FileNotFoundException, IOException
|
||||
*/
|
||||
public String readAsText(String filename, String encoding) throws FileNotFoundException, IOException {
|
||||
System.out.println("FileUtils.readAsText("+filename+", "+encoding+")");
|
||||
StringBuilder data = new StringBuilder();
|
||||
FileInputStream fis = new FileInputStream(filename);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, encoding), 1024);
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
data.append(line);
|
||||
}
|
||||
return data.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Read content of text file and return as base64 encoded data url.
|
||||
*
|
||||
* @param filename The name of the file.
|
||||
* @return Contents of file = data:<media type>;base64,<data>
|
||||
* @throws FileNotFoundException, IOException
|
||||
*/
|
||||
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
|
||||
byte[] bytes = new byte[1000];
|
||||
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename), 1024);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
int numRead = 0;
|
||||
while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
|
||||
bos.write(bytes, 0, numRead);
|
||||
}
|
||||
|
||||
// Determine content type from file name
|
||||
// TODO
|
||||
String contentType = "";
|
||||
|
||||
byte[] base64 = Base64.encodeBase64(bos.toByteArray());
|
||||
String data = "data:" + contentType + ";base64," + new String(base64);
|
||||
return data;
|
||||
}
|
||||
|
||||
public int write(String filename, String data, boolean append)
|
||||
{
|
||||
String FilePath= filename;
|
||||
try {
|
||||
byte [] rawData = data.getBytes();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
|
||||
FileOutputStream out= new FileOutputStream(FilePath, append);
|
||||
byte buff[] = new byte[rawData.length];
|
||||
in.read(buff, 0, buff.length);
|
||||
out.write(buff, 0, rawData.length);
|
||||
out.flush();
|
||||
out.close();
|
||||
//mView.loadUrl("javascript:navigator.FileReader.onsuccess('File written')");
|
||||
} catch (Exception e) {
|
||||
//mView.loadUrl("javascript:navigator.FileReader.onerror('Fail')");
|
||||
// So, do we just return -1 at this point!
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
/**
|
||||
* Write contents of file.
|
||||
*
|
||||
* @param filename The name of the file.
|
||||
* @param data The contents of the file.
|
||||
* @param append T=append, F=overwrite
|
||||
* @throws FileNotFoundException, IOException
|
||||
*/
|
||||
public void writeAsText(String filename, String data, boolean append) throws FileNotFoundException, IOException {
|
||||
String FilePath= filename;
|
||||
byte [] rawData = data.getBytes();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
|
||||
FileOutputStream out= new FileOutputStream(FilePath, append);
|
||||
byte buff[] = new byte[rawData.length];
|
||||
in.read(buff, 0, buff.length);
|
||||
out.write(buff, 0, rawData.length);
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
Regular → Executable
+63
-14
@@ -1,6 +1,7 @@
|
||||
package com.phonegap;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
@@ -22,6 +23,7 @@ public class GeoBroker implements Plugin {
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
|
||||
// List of gGeolocation listeners
|
||||
private HashMap<String, GeoListener> geoListeners;
|
||||
private GeoListener global;
|
||||
|
||||
@@ -65,10 +67,10 @@ public class GeoBroker implements Plugin {
|
||||
|
||||
try {
|
||||
if (action.equals("getCurrentLocation")) {
|
||||
this.getCurrentLocation();
|
||||
this.getCurrentLocation(args.getBoolean(0), args.getInt(1), args.getInt(2));
|
||||
}
|
||||
else if (action.equals("start")) {
|
||||
String s = this.start(args.getInt(0), args.getString(1));
|
||||
String s = this.start(args.getString(0), args.getBoolean(1), args.getInt(2), args.getInt(3));
|
||||
return new PluginResult(status, s);
|
||||
}
|
||||
else if (action.equals("stop")) {
|
||||
@@ -87,7 +89,8 @@ public class GeoBroker implements Plugin {
|
||||
* @return T=returns value
|
||||
*/
|
||||
public boolean isSynch(String action) {
|
||||
return false;
|
||||
// Starting listeners is easier to run on main thread, so don't run async.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,10 +106,22 @@ public class GeoBroker implements Plugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by AccelBroker when listener is to be shut down.
|
||||
* Called when the activity is to be shut down.
|
||||
* Stop listener.
|
||||
*/
|
||||
public void onDestroy() {
|
||||
public void onDestroy() {
|
||||
java.util.Set<Entry<String,GeoListener>> s = this.geoListeners.entrySet();
|
||||
java.util.Iterator<Entry<String,GeoListener>> it = s.iterator();
|
||||
while (it.hasNext()) {
|
||||
Entry<String,GeoListener> entry = it.next();
|
||||
GeoListener listener = entry.getValue();
|
||||
listener.destroy();
|
||||
}
|
||||
this.geoListeners.clear();
|
||||
if (this.global != null) {
|
||||
this.global.destroy();
|
||||
}
|
||||
this.global = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,23 +140,57 @@ public class GeoBroker implements Plugin {
|
||||
// LOCAL METHODS
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
public void getCurrentLocation() {
|
||||
//It's supposed to run async!
|
||||
if (global == null) {
|
||||
global = new GeoListener("global", this.ctx, 10000, this.webView);
|
||||
/**
|
||||
* Get current location.
|
||||
* The result is returned to JavaScript via a callback.
|
||||
*
|
||||
* @param enableHighAccuracy
|
||||
* @param timeout
|
||||
* @param maximumAge
|
||||
*/
|
||||
public void getCurrentLocation(boolean enableHighAccuracy, int timeout, int maximumAge) {
|
||||
|
||||
// Create a geolocation listener just for getCurrentLocation and call it "global"
|
||||
if (this.global == null) {
|
||||
this.global = new GeoListener("global", this.ctx, maximumAge, this.webView);
|
||||
}
|
||||
else {
|
||||
global.start(10000);
|
||||
this.global.start(maximumAge);
|
||||
}
|
||||
}
|
||||
|
||||
public String start(int freq, String key) {
|
||||
GeoListener listener = new GeoListener(key, this.ctx, freq, this.webView);
|
||||
geoListeners.put(key, listener);
|
||||
/**
|
||||
* Start geolocation listener and add to listener list.
|
||||
*
|
||||
* @param key The listener id
|
||||
* @param enableHighAccuracy
|
||||
* @param timeout
|
||||
* @param maximumAge
|
||||
* @return
|
||||
*/
|
||||
public String start(String key, boolean enableHighAccuracy, int timeout, int maximumAge) {
|
||||
|
||||
// Make sure this listener doesn't already exist
|
||||
GeoListener listener = geoListeners.get(key);
|
||||
if (listener == null) {
|
||||
listener = new GeoListener(key, this.ctx, maximumAge, this.webView);
|
||||
geoListeners.put(key, listener);
|
||||
}
|
||||
|
||||
// Start it
|
||||
listener.start(maximumAge);
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop geolocation listener and remove from listener list.
|
||||
*
|
||||
* @param key The listener id
|
||||
*/
|
||||
public void stop(String key) {
|
||||
GeoListener geo = geoListeners.get(key);
|
||||
GeoListener listener = geoListeners.remove(key);
|
||||
if (listener != null) {
|
||||
listener.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Regular → Executable
+81
-52
@@ -6,83 +6,112 @@ import android.location.LocationManager;
|
||||
import android.webkit.WebView;
|
||||
|
||||
public class GeoListener {
|
||||
String id;
|
||||
String successCallback;
|
||||
public static int PERMISSION_DENIED = 1;
|
||||
public static int POSITION_UNAVAILABLE = 2;
|
||||
public static int TIMEOUT = 3;
|
||||
|
||||
String id; // Listener ID
|
||||
String successCallback; //
|
||||
String failCallback;
|
||||
GpsListener mGps;
|
||||
NetworkListener mNetwork;
|
||||
LocationManager mLocMan;
|
||||
private DroidGap mCtx;
|
||||
private WebView mAppView;
|
||||
GpsListener mGps; // GPS listener
|
||||
NetworkListener mNetwork; // Network listener
|
||||
LocationManager mLocMan; // Location manager
|
||||
|
||||
private DroidGap ctx; // DroidGap object
|
||||
@SuppressWarnings("unused")
|
||||
private WebView mAppView; // Webview object
|
||||
|
||||
int interval;
|
||||
|
||||
GeoListener(String i, DroidGap ctx, int time, WebView appView) {
|
||||
id = i;
|
||||
interval = time;
|
||||
mCtx = ctx;
|
||||
mGps = null;
|
||||
mNetwork = null;
|
||||
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param id Listener id
|
||||
* @param ctx
|
||||
* @param time Sampling period in msec
|
||||
* @param appView
|
||||
*/
|
||||
GeoListener(String id, DroidGap ctx, int time, WebView appView) {
|
||||
this.id = id;
|
||||
this.interval = time;
|
||||
this.ctx = ctx;
|
||||
this.mGps = null;
|
||||
this.mNetwork = null;
|
||||
this.mLocMan = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
|
||||
|
||||
if (mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
|
||||
mGps = new GpsListener(mCtx, interval, this);
|
||||
// If GPS provider, then create and start GPS listener
|
||||
if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
|
||||
this.mGps = new GpsListener(ctx, time, this);
|
||||
}
|
||||
if (mLocMan.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
|
||||
mNetwork = new NetworkListener(mCtx, interval, this);
|
||||
|
||||
// If network provider, then create and start network listener
|
||||
if (this.mLocMan.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
|
||||
this.mNetwork = new NetworkListener(ctx, time, this);
|
||||
}
|
||||
mAppView = appView;
|
||||
this.mAppView = appView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy listener.
|
||||
*/
|
||||
public void destroy() {
|
||||
this.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Location found. Send location back to JavaScript.
|
||||
*
|
||||
* @param loc
|
||||
*/
|
||||
void success(Location loc) {
|
||||
/*
|
||||
* We only need to figure out what we do when we succeed!
|
||||
*/
|
||||
|
||||
String params;
|
||||
/*
|
||||
* Build the giant string to send back to Javascript!
|
||||
*/
|
||||
params = loc.getLatitude() + "," + loc.getLongitude() + ", " + loc.getAltitude() + "," + loc.getAccuracy() + "," + loc.getBearing();
|
||||
params += "," + loc.getSpeed() + "," + loc.getTime();
|
||||
if (id != "global") {
|
||||
mCtx.sendJavascript("navigator._geo.success(" + id + "," + params + ");");
|
||||
}
|
||||
else {
|
||||
mCtx.sendJavascript("navigator.geolocation.gotCurrentPosition(" + params + ");");
|
||||
String params = loc.getLatitude() + "," + loc.getLongitude() + ", " + loc.getAltitude() +
|
||||
"," + loc.getAccuracy() + "," + loc.getBearing() +
|
||||
"," + loc.getSpeed() + "," + loc.getTime();
|
||||
|
||||
if (id == "global") {
|
||||
this.stop();
|
||||
}
|
||||
this.ctx.sendJavascript("navigator._geo.success('" + id + "'," + params + ");");
|
||||
}
|
||||
|
||||
void fail() {
|
||||
// Do we need to know why? How would we handle this?
|
||||
if (id != "global") {
|
||||
mCtx.sendJavascript("navigator._geo.fail(" + id + ");");
|
||||
} else {
|
||||
mCtx.sendJavascript("navigator._geo.fail();");
|
||||
}
|
||||
/**
|
||||
* Location failed. Send error back to JavaScript.
|
||||
*
|
||||
* @param code The error code
|
||||
* @param msg The error message
|
||||
*/
|
||||
void fail(int code, String msg) {
|
||||
this.ctx.sendJavascript("navigator._geo.fail('" + this.id + "', " + ", " + code + ", '" + msg + "');");
|
||||
this.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start retrieving location.
|
||||
*
|
||||
* @param interval
|
||||
*/
|
||||
void start(int interval) {
|
||||
if (mGps != null) {
|
||||
mGps.start(interval);
|
||||
if (this.mGps != null) {
|
||||
this.mGps.start(interval);
|
||||
}
|
||||
if (mNetwork != null) {
|
||||
mNetwork.start(interval);
|
||||
if (this.mNetwork != null) {
|
||||
this.mNetwork.start(interval);
|
||||
}
|
||||
if (mNetwork == null && mGps == null) {
|
||||
// Really, how were you going to get the location???
|
||||
mCtx.sendJavascript("navigator._geo.fail();");
|
||||
if (this.mNetwork == null && this.mGps == null) {
|
||||
this.fail(POSITION_UNAVAILABLE, "No location providers available.");
|
||||
}
|
||||
}
|
||||
|
||||
// This stops the listener
|
||||
/**
|
||||
* Stop listening for location.
|
||||
*/
|
||||
void stop() {
|
||||
if (mGps != null) {
|
||||
mGps.stop();
|
||||
if (this.mGps != null) {
|
||||
this.mGps.stop();
|
||||
}
|
||||
if (mNetwork != null) {
|
||||
mNetwork.stop();
|
||||
if (this.mNetwork != null) {
|
||||
this.mNetwork.stop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Regular → Executable
+103
-46
@@ -26,81 +26,138 @@ import android.location.Location;
|
||||
import android.location.LocationManager;
|
||||
import android.location.LocationListener;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* This class handles requests for GPS location services.
|
||||
*
|
||||
*/
|
||||
public class GpsListener implements LocationListener {
|
||||
|
||||
private Context mCtx;
|
||||
private Location cLoc;
|
||||
private LocationManager mLocMan;
|
||||
private static final String LOG_TAG = "PhoneGap";
|
||||
private GeoListener owner;
|
||||
private boolean hasData = false;
|
||||
private DroidGap mCtx; // DroidGap object
|
||||
|
||||
public GpsListener(Context ctx, int interval, GeoListener m)
|
||||
{
|
||||
owner = m;
|
||||
mCtx = ctx;
|
||||
private LocationManager mLocMan; // Location manager object
|
||||
private GeoListener owner; // Geolistener object (parent)
|
||||
private boolean hasData = false; // Flag indicates if location data is available in cLoc
|
||||
private Location cLoc; // Last recieved location
|
||||
private boolean running = false; // Flag indicates if listener is running
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* Automatically starts listening.
|
||||
*
|
||||
* @param ctx
|
||||
* @param interval
|
||||
* @param m
|
||||
*/
|
||||
public GpsListener(DroidGap ctx, int interval, GeoListener m) {
|
||||
this.owner = m;
|
||||
this.mCtx = ctx;
|
||||
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
|
||||
this.running = false;
|
||||
this.start(interval);
|
||||
}
|
||||
|
||||
public Location getLocation()
|
||||
{
|
||||
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
|
||||
hasData = true;
|
||||
return cLoc;
|
||||
/**
|
||||
* Get last location.
|
||||
*
|
||||
* @return Location object
|
||||
*/
|
||||
public Location getLocation() {
|
||||
this.cLoc = this.mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
|
||||
if (this.cLoc != null) {
|
||||
this.hasData = true;
|
||||
}
|
||||
return this.cLoc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the provider is disabled by the user.
|
||||
*
|
||||
* @param provider
|
||||
*/
|
||||
public void onProviderDisabled(String provider) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The provider " + provider + " is disabled");
|
||||
owner.fail();
|
||||
this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS provider disabled.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the provider is enabled by the user.
|
||||
*
|
||||
* @param provider
|
||||
*/
|
||||
public void onProviderEnabled(String provider) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The provider "+ provider + " is enabled");
|
||||
System.out.println("GpsListener: The provider "+ provider + " is enabled");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the provider status changes. This method is called when a
|
||||
* provider is unable to fetch a location or if the provider has recently
|
||||
* become available after a period of unavailability.
|
||||
*
|
||||
* @param provider
|
||||
* @param status
|
||||
* @param extras
|
||||
*/
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The status of the provider " + provider + " has changed");
|
||||
if(status == 0)
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is OUT OF SERVICE");
|
||||
owner.fail();
|
||||
System.out.println("GpsListener: The status of the provider " + provider + " has changed");
|
||||
if (status == 0) {
|
||||
System.out.println("GpsListener: " + provider + " is OUT OF SERVICE");
|
||||
this.owner.fail(GeoListener.POSITION_UNAVAILABLE, "GPS out of service.");
|
||||
}
|
||||
else if(status == 1)
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is TEMPORARILY_UNAVAILABLE");
|
||||
else if (status == 1) {
|
||||
System.out.println("GpsListener: " + provider + " is TEMPORARILY_UNAVAILABLE");
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is Available");
|
||||
else {
|
||||
System.out.println("GpsListener: " + provider + " is Available");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the location has changed.
|
||||
*
|
||||
* @param location
|
||||
*/
|
||||
public void onLocationChanged(Location location) {
|
||||
Log.d(LOG_TAG, "The location has been updated!");
|
||||
owner.success(location);
|
||||
System.out.println("GpsListener: The location has been updated!");
|
||||
this.hasData = true;
|
||||
this.cLoc = location;
|
||||
this.owner.success(location);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if location data is available.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean hasLocation() {
|
||||
return hasData;
|
||||
return this.hasData;
|
||||
}
|
||||
|
||||
public void start(int interval)
|
||||
{
|
||||
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
|
||||
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, 0, this);
|
||||
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
|
||||
/**
|
||||
* Start requesting location updates.
|
||||
*
|
||||
* @param interval
|
||||
*/
|
||||
public void start(int interval) {
|
||||
if (!this.running) {
|
||||
this.running = true;
|
||||
this.mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, 0, this);
|
||||
this.getLocation();
|
||||
|
||||
// If GPS provider has data, then send now
|
||||
if (this.hasData) {
|
||||
this.owner.success(this.cLoc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
mLocMan.removeUpdates(this);
|
||||
/**
|
||||
* Stop receiving location updates.
|
||||
*/
|
||||
public void stop() {
|
||||
if (this.running) {
|
||||
this.mLocMan.removeUpdates(this);
|
||||
}
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Regular → Executable
+96
-49
@@ -26,82 +26,129 @@ import android.location.Location;
|
||||
import android.location.LocationManager;
|
||||
import android.location.LocationListener;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
public class NetworkListener implements LocationListener {
|
||||
|
||||
private Context mCtx;
|
||||
private Location cLoc;
|
||||
private LocationManager mLocMan;
|
||||
private static final String LOG_TAG = "PhoneGap";
|
||||
GeoListener owner;
|
||||
|
||||
public NetworkListener(Context ctx, int interval, GeoListener m)
|
||||
{
|
||||
owner = m;
|
||||
mCtx = ctx;
|
||||
private DroidGap mCtx; // DroidGap object
|
||||
|
||||
private LocationManager mLocMan; // Location manager object
|
||||
private GeoListener owner; // Geolistener object (parent)
|
||||
private boolean hasData = false; // Flag indicates if location data is available in cLoc
|
||||
private Location cLoc; // Last recieved location
|
||||
private boolean running = false; // Flag indicates if listener is running
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* Automatically starts listening.
|
||||
*
|
||||
* @param ctx
|
||||
* @param interval
|
||||
* @param m
|
||||
*/
|
||||
public NetworkListener(DroidGap ctx, int interval, GeoListener m) {
|
||||
this.owner = m;
|
||||
this.mCtx = ctx;
|
||||
this.mLocMan = (LocationManager) this.mCtx.getSystemService(Context.LOCATION_SERVICE);
|
||||
this.running = false;
|
||||
this.start(interval);
|
||||
}
|
||||
|
||||
public Location getLocation()
|
||||
{
|
||||
cLoc = mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
return cLoc;
|
||||
/**
|
||||
* Get last location.
|
||||
*
|
||||
* @return Location object
|
||||
*/
|
||||
public Location getLocation() {
|
||||
this.cLoc = this.mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
if (this.cLoc != null) {
|
||||
this.hasData = true;
|
||||
}
|
||||
return this.cLoc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the provider is disabled by the user.
|
||||
*
|
||||
* @param provider
|
||||
*/
|
||||
public void onProviderDisabled(String provider) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The provider " + provider + " is disabled");
|
||||
System.out.println("NetworkListener: The provider " + provider + " is disabled");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the provider is enabled by the user.
|
||||
*
|
||||
* @param provider
|
||||
*/
|
||||
public void onProviderEnabled(String provider) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The provider "+ provider + " is enabled");
|
||||
System.out.println("NetworkListener: The provider "+ provider + " is enabled");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the provider status changes. This method is called when a
|
||||
* provider is unable to fetch a location or if the provider has recently
|
||||
* become available after a period of unavailability.
|
||||
*
|
||||
* @param provider
|
||||
* @param status
|
||||
* @param extras
|
||||
*/
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) {
|
||||
// TODO Auto-generated method stub
|
||||
Log.d(LOG_TAG, "The status of the provider " + provider + " has changed");
|
||||
if(status == 0)
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is OUT OF SERVICE");
|
||||
System.out.println("NetworkListener: The status of the provider " + provider + " has changed");
|
||||
if (status == 0) {
|
||||
System.out.println("NetworkListener: " + provider + " is OUT OF SERVICE");
|
||||
}
|
||||
else if(status == 1)
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is TEMPORARILY_UNAVAILABLE");
|
||||
else if (status == 1) {
|
||||
System.out.println("NetworkListener: " + provider + " is TEMPORARILY_UNAVAILABLE");
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.d(LOG_TAG, provider + " is Available");
|
||||
else {
|
||||
System.out.println("NetworkListener: " + provider + " is Available");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* The GPS is the primary form of Geolocation in PhoneGap. Only fire the success variables if the GPS is down
|
||||
* for some reason
|
||||
/**
|
||||
* Called when the location has changed.
|
||||
*
|
||||
* @param location
|
||||
*/
|
||||
public void onLocationChanged(Location location) {
|
||||
Log.d(LOG_TAG, "The location has been updated!");
|
||||
if (!owner.mGps.hasLocation())
|
||||
{
|
||||
owner.success(location);
|
||||
System.out.println("NetworkListener: The location has been updated!");
|
||||
this.hasData = true;
|
||||
this.cLoc = location;
|
||||
|
||||
// The GPS is the primary form of Geolocation in PhoneGap.
|
||||
// Only fire the success variables if the GPS is down for some reason.
|
||||
if (!this.owner.mGps.hasLocation()) {
|
||||
this.owner.success(location);
|
||||
}
|
||||
cLoc = location;
|
||||
}
|
||||
|
||||
public void start(int interval)
|
||||
{
|
||||
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
|
||||
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, 0, this);
|
||||
cLoc = mLocMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
||||
/**
|
||||
* Start requesting location updates.
|
||||
*
|
||||
* @param interval
|
||||
*/
|
||||
public void start(int interval) {
|
||||
if (!this.running) {
|
||||
this.running = true;
|
||||
this.mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, 0, this);
|
||||
this.getLocation();
|
||||
|
||||
// If Network provider has data but GPS provider doesn't, then send ours
|
||||
if (this.hasData && !this.owner.mGps.hasLocation()) {
|
||||
this.owner.success(this.cLoc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
mLocMan.removeUpdates(this);
|
||||
/**
|
||||
* Stop receiving location updates.
|
||||
*/
|
||||
public void stop() {
|
||||
if (this.running) {
|
||||
this.mLocMan.removeUpdates(this);
|
||||
}
|
||||
this.running = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,6 +14,11 @@ import android.net.*;
|
||||
import android.webkit.WebView;
|
||||
|
||||
public class NetworkManager implements Plugin {
|
||||
|
||||
public static int NOT_REACHABLE = 0;
|
||||
public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1;
|
||||
public static int REACHABLE_VIA_WIFI_NETWORK = 2;
|
||||
|
||||
|
||||
WebView webView; // WebView object
|
||||
DroidGap ctx; // DroidGap object
|
||||
@@ -67,8 +72,8 @@ public class NetworkManager implements Plugin {
|
||||
return new PluginResult(status, b);
|
||||
}
|
||||
else if (action.equals("isReachable")) {
|
||||
boolean b = this.isReachable(args.getString(0));
|
||||
return new PluginResult(status, b);
|
||||
int i = this.isReachable(args.getString(0), args.getBoolean(1));
|
||||
return new PluginResult(status, i);
|
||||
}
|
||||
return new PluginResult(status, result);
|
||||
} catch (JSONException e) {
|
||||
@@ -122,6 +127,11 @@ public class NetworkManager implements Plugin {
|
||||
// LOCAL METHODS
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Determine if a network connection exists.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isAvailable() {
|
||||
NetworkInfo info = sockMan.getActiveNetworkInfo();
|
||||
boolean conn = false;
|
||||
@@ -131,6 +141,11 @@ public class NetworkManager implements Plugin {
|
||||
return conn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a WIFI connection exists.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean isWifiActive() {
|
||||
NetworkInfo info = sockMan.getActiveNetworkInfo();
|
||||
if (info != null) {
|
||||
@@ -140,18 +155,37 @@ public class NetworkManager implements Plugin {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReachable(String uri) {
|
||||
/**
|
||||
* Determine if a URI is reachable over the network.
|
||||
*
|
||||
* @param uri
|
||||
* @param isIpAddress
|
||||
* @return
|
||||
*/
|
||||
public int isReachable(String uri, boolean isIpAddress) {
|
||||
int reachable = NOT_REACHABLE;
|
||||
|
||||
if (uri.indexOf("http://") == -1) {
|
||||
uri = "http://" + uri;
|
||||
}
|
||||
boolean reached = isAvailable();
|
||||
try {
|
||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||
HttpGet httpget = new HttpGet(uri);
|
||||
httpclient.execute(httpget);
|
||||
} catch (Exception e) {
|
||||
reached = false;
|
||||
|
||||
if (isAvailable()) {
|
||||
try {
|
||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||
HttpGet httpget = new HttpGet(uri);
|
||||
httpclient.execute(httpget);
|
||||
|
||||
if (isWifiActive()) {
|
||||
reachable = REACHABLE_VIA_WIFI_NETWORK;
|
||||
}
|
||||
else {
|
||||
reachable = REACHABLE_VIA_CARRIER_DATA_NETWORK;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
reachable = NOT_REACHABLE;
|
||||
}
|
||||
}
|
||||
return reached;
|
||||
|
||||
return reachable;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,8 @@ public class PluginResult {
|
||||
"Malformed url",
|
||||
"IO error",
|
||||
"Invalid action",
|
||||
"JSON error"
|
||||
"JSON error",
|
||||
"Error"
|
||||
};
|
||||
|
||||
public enum Status {
|
||||
@@ -74,6 +75,7 @@ public class PluginResult {
|
||||
MALFORMED_URL_EXCEPTION,
|
||||
IO_EXCEPTION,
|
||||
INVALID_ACTION,
|
||||
JSON_EXCEPTION
|
||||
JSON_EXCEPTION,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user