Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancements to Android version #116

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
.DS_Store
node_modules
.idea
android.iml
settings.gradle
28 changes: 15 additions & 13 deletions src/android/AddGeofenceCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,31 @@ public void onAddGeofencesResult(int statusCode, String[] arg1) {
public void ExecuteCustomCode() {
// TODO Auto-generated method stub
logger.log(Log.DEBUG, "Adding new geofences");
LocationServices.GeofencingApi
.addGeofences(mGoogleApiClient, geofencesToAdd, pendingIntent)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
logger.log(Log.DEBUG, "Geofences successfully added");
if(geofencesToAdd!=null && geofencesToAdd.size() > 0) {
LocationServices.GeofencingApi
.addGeofences(mGoogleApiClient, geofencesToAdd, pendingIntent)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
logger.log(Log.DEBUG, "Geofences successfully added");
/*
* Handle successful addition of geofences here. You can send out a
* broadcast intent or update the UI. geofences into the Intent's
* extended data.
*/
} else {
logger.log(Log.DEBUG, "Adding geofences failed");
// If adding the geofences failed
} else {
logger.log(Log.DEBUG, "Adding geofences failed");
// If adding the geofences failed
/*
* Report errors here. You can log the error using Log.e() or update
* the UI.
*/
}
CommandExecuted();
}
CommandExecuted();
}
});
});
}
}

@Override
Expand Down
44 changes: 41 additions & 3 deletions src/android/GeoNotification.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,21 @@
import com.google.android.gms.location.Geofence;
import com.google.gson.annotations.Expose;

import java.util.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class GeoNotification {
@Expose public String id;
@Expose public double latitude;
@Expose public double longitude;
@Expose public int radius;
@Expose public int transitionType;
@Expose public String endDate;
@Expose public long lastShown = 0;
@Expose public int frequency = 0;
@Expose public int loiteringDelay = 120000;

@Expose public Notification notification;

Expand All @@ -17,15 +26,44 @@ public GeoNotification() {

public Geofence toGeofence() {
return new Geofence.Builder().setRequestId(id)
.setTransitionTypes(transitionType)
.setCircularRegion(latitude, longitude, radius)
.setExpirationDuration(Long.MAX_VALUE).build();
.setTransitionTypes(transitionType)
.setExpirationDuration(getExpireTime())
.setLoiteringDelay(loiteringDelay)
.setCircularRegion(latitude, longitude, radius)
.build();
}

public String toJson() {
return Gson.get().toJson(this);
}

public long getExpireTime() {
if(endDate == null || endDate.isEmpty() || endDate == "false") {
return Geofence.NEVER_EXPIRE;
}

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date();

try {
date = sdf.parse(endDate);
}catch(ParseException ex) {
return Geofence.NEVER_EXPIRE;
}

Date now = new Date();
long dateMill = date.getTime();
long nowMill = now.getTime();

long diff = dateMill - nowMill;

if(diff < 0) {
return 0;
}else {
return diff;
}
}

public static GeoNotification fromJson(String json) {
if (json == null)
return null;
Expand Down
1 change: 0 additions & 1 deletion src/android/GeoNotificationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
public class GeoNotificationManager {
private Context context;
private GeoNotificationStore geoNotificationStore;
//private LocationClient locationClient;
private Logger logger;
private boolean connectionInProgress = false;
private List<Geofence> geoFences;
Expand Down
23 changes: 10 additions & 13 deletions src/android/GeoNotificationNotifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void notify(Notification notification) {
.setVibrate(notification.getVibrate())
.setSmallIcon(notification.getSmallIcon())
.setLargeIcon(notification.getLargeIcon())
.setAutoCancel(true)
.setAutoCancel(notification.getAutoCancel())
.setContentTitle(notification.getTitle())
.setContentText(notification.getText());

Expand All @@ -43,18 +43,15 @@ public void notify(Notification notification) {
if (notification.data != null) {
resultIntent.putExtra("geofence.notification.data", notification.getDataJson());
}
// The stack builder object will contain an artificial back stack
// for the
// started Activity.
// This ensures that navigating backward from the Activity leads out
// of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0, PendingIntent.FLAG_UPDATE_CURRENT);

resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent resultPendingIntent =
PendingIntent.getActivity(context,
1001,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
}
try {
Expand Down
147 changes: 109 additions & 38 deletions src/android/GeofencePlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,70 +16,120 @@
import java.util.List;

public class GeofencePlugin extends CordovaPlugin {

public static final String TAG = "GeofencePlugin";

private GeoNotificationManager geoNotificationManager;
private Context context;
protected static Boolean isInBackground = true;
public static CordovaWebView webView = null;
private static Context context;
public static CordovaWebView webView;
protected static Boolean isInForeground = true;
protected static Boolean isDeviceReady = false;
private GeoNotificationStore geoNotificationStore;

/**
* @param cordova
* The context of the main Activity.
* @param webView
* The associated CordovaWebView.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
GeofencePlugin.webView = webView;
context = this.cordova.getActivity().getApplicationContext();
isInForeground = true;
Logger.setLogger(new Logger(TAG, context, false));
context = this.cordova.getActivity().getApplicationContext();
geoNotificationManager = new GeoNotificationManager(context);
geoNotificationStore = new GeoNotificationStore(context);
}

@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "GeofencePlugin execute action: " + action + " args: "
+ args.toString());
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Log.v(TAG, "Executing action=" + action);

if (action.equals("addOrUpdate")) {
List<GeoNotification> geoNotifications = new ArrayList<GeoNotification>();
for (int i = 0; i < args.length(); i++) {
GeoNotification not = parseFromJSONObject(args.getJSONObject(i));
if (not != null) {
geoNotifications.add(not);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
List<GeoNotification> geoNotifications = new ArrayList<GeoNotification>();

for (int i = 0; i < args.length(); i++) {
GeoNotification notification = null;

try{
notification = parseFromJSONObject(args.getJSONObject(i));
}catch(JSONException ex){

}

if (notification != null) {
geoNotifications.add(notification);
}
}

geoNotificationManager.addGeoNotifications(geoNotifications, callbackContext);
}
}
geoNotificationManager.addGeoNotifications(geoNotifications,
callbackContext);
});
} else if (action.equals("remove")) {
List<String> ids = new ArrayList<String>();

for (int i = 0; i < args.length(); i++) {
ids.add(args.getString(i));
}

geoNotificationManager.removeGeoNotifications(ids, callbackContext);
} else if (action.equals("removeAll")) {
geoNotificationManager.removeAllGeoNotifications(callbackContext);
;
} else if (action.equals("getWatched")) {
List<GeoNotification> geoNotifications = geoNotificationManager
.getWatched();
List<GeoNotification> geoNotifications = geoNotificationManager.getWatched();
callbackContext.success(Gson.get().toJson(geoNotifications));
} else if (action.equals("initialize")) {
callbackContext.success();
} else if (action.equals("deviceReady")) {
deviceReady();
isDeviceReady = true;
callbackContext.success();
} else {
return false;
}
return true;
}

private GeoNotification parseFromJSONObject(JSONObject object) {
GeoNotification geo = null;
geo = GeoNotification.fromJson(object.toString());
return geo;
/**
* Called when the activity is paused.
*
* @param multitasking Flag indicating if multitasking is turned on for app
*/
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
isInForeground = false;
}

/**
* Called when the activity will start interacting with the user.
*
* @param multitasking Flag indicating if multitasking is turned on for app
*/
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
isInForeground = true;
isDeviceReady = true;
}

/**
* Called when the activity receives a new intent.
*/
@Override
public void onNewIntent(Intent intent) {
isInForeground = true;
Log.d(TAG, "New Intent Found!");
wasNotificationClicked(intent);
}

/**
* The final call you receive before your activity is destroyed.
*/
@Override
public void onDestroy() {
super.onDestroy();
isDeviceReady = false;
isInForeground = false;
webView = null;
}

public static void onTransitionReceived(List<GeoNotification> notifications) {
Expand All @@ -93,16 +143,37 @@ public static void onTransitionReceived(List<GeoNotification> notifications) {
}
}

private void deviceReady() {
Intent intent = cordova.getActivity().getIntent();
private GeoNotification parseFromJSONObject(JSONObject object) {
GeoNotification geo = null;
geo = GeoNotification.fromJson(object.toString());
return geo;
}

protected void wasNotificationClicked(Intent intent) {
Log.d(TAG, "Notification Clicked");

String data = intent.getStringExtra("geofence.notification.data");
String js = "setTimeout('geofence.onNotificationClicked("
+ data + ")',0)";

if (data == null) {
Log.d(TAG, "No notifications clicked.");
} else {
webView.sendJavascript(js);
if(data != null && !data.isEmpty()) {
Log.d(TAG, "Data found for notification click");

String js = "setTimeout('geofence.onNotificationClicked("
+ data + ")',0)";

Log.d(TAG, String.valueOf(isInForeground));

if(isInForeground) {
Log.d(TAG, "Firing JS");
webView.sendJavascript(js);
}
}
}
}

public static boolean isInForeground() {
return isInForeground;
}

public static boolean isActive() {
return webView != null;
}
}
9 changes: 9 additions & 0 deletions src/android/Notification.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ public class Notification {
@Expose public String smallIcon = "";
@Expose public Object data;
@Expose public boolean openAppOnClick;
@Expose public boolean autoCancel = true;

public void setContext(Context context) {
this.context = context;
this.assets = AssetUtil.getInstance(context);
}

public int getId() {
return this.id;
}

public String getText() {
return this.text;
}
Expand All @@ -42,6 +47,10 @@ public int getSmallIcon() {
return resId;
}

public boolean getAutoCancel() {
return this.autoCancel;
}

public Bitmap getLargeIcon() {
Bitmap bmp;

Expand Down
Loading