Skip to content

Commit

Permalink
small refactor, catching no permission exceptions, fixes #196
Browse files Browse the repository at this point in the history
  • Loading branch information
tsubik committed Feb 19, 2017
1 parent 815b659 commit abd518e
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 226 deletions.
18 changes: 4 additions & 14 deletions src/android/AbstractGoogleServiceCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public abstract class AbstractGoogleServiceCommand implements
protected List<IGoogleServiceCommandListener> listeners;
protected Context context;
protected GoogleApiClient mGoogleApiClient;

public AbstractGoogleServiceCommand(Context context) {
this.context = context;
mGoogleApiClient = new GoogleApiClient.Builder(context)
Expand Down Expand Up @@ -72,17 +73,9 @@ public void onConnected(Bundle arg0) {
ExecuteCustomCode();
}

//@Override
public void onDisconnected() {
// Turn off the request flag
connectionInProgress = false;
// Destroy the current location client
locationClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new
// Date()) + ": Disconnected. Please re-connect.",
// Toast.LENGTH_SHORT).show();
logger.log(Log.DEBUG, "Google play services Disconnected");
@Override
public void onConnectionSuspended(int arg) {

}

public void addListener(IGoogleServiceCommandListener listener) {
Expand All @@ -102,8 +95,5 @@ protected void CommandExecuted() {
}
}

abstract void onAddGeofencesResult(int statusCode, String[] arg1);

protected abstract void ExecuteCustomCode();

}
73 changes: 19 additions & 54 deletions src/android/AddGeofenceCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
//import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationStatusCodes;

import java.util.List;

Expand All @@ -18,67 +16,34 @@ public class AddGeofenceCommand extends AbstractGoogleServiceCommand{
private PendingIntent pendingIntent;

public AddGeofenceCommand(Context context, PendingIntent pendingIntent,
List<Geofence> geofencesToAdd) {
List<Geofence> geofencesToAdd) {
super(context);
this.geofencesToAdd = geofencesToAdd;
this.pendingIntent = pendingIntent;
}

@Override
public void onAddGeofencesResult(int statusCode, String[] arg1) {
// If adding the geofences was successful
if (LocationStatusCodes.SUCCESS == statusCode) {
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
/*
* Report errors here. You can log the error using Log.e() or update
* the UI.
*/
}
CommandExecuted();
}

@Override
public void ExecuteCustomCode() {
// TODO Auto-generated method stub
logger.log(Log.DEBUG, "Adding new geofences");
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
/*
* Report errors here. You can log the error using Log.e() or update
* the UI.
*/
if (geofencesToAdd != null && geofencesToAdd.size() > 0) {
try {
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");
} else {
logger.log(Log.DEBUG, "Adding geofences failed");
}
CommandExecuted();
}
CommandExecuted();
}
});
});
} catch (Exception exception) {
logger.log("Adding geofence failed", exception);
CommandExecuted();
}
}
}

@Override
public void onConnectionSuspended(int i) {

}

}
3 changes: 1 addition & 2 deletions src/android/GeoNotification.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ public String toJson() {
}

public static GeoNotification fromJson(String json) {
if (json == null)
return null;
if (json == null) return null;
return Gson.get().fromJson(json, GeoNotification.class);
}
}
27 changes: 5 additions & 22 deletions src/android/GeoNotificationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationRequest;

import org.apache.cordova.CallbackContext;

Expand All @@ -19,9 +17,7 @@
public class GeoNotificationManager {
private Context context;
private GeoNotificationStore geoNotificationStore;
//private LocationClient locationClient;
private Logger logger;
private boolean connectionInProgress = false;
private List<Geofence> geoFences;
private PendingIntent pendingIntent;
private GoogleServiceCommandExecutor googleServiceCommandExecutor;
Expand Down Expand Up @@ -57,10 +53,9 @@ public List<GeoNotification> getWatched() {
}

private boolean areGoogleServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int resultCode = api.isGooglePlayServicesAvailable(context);

// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Expand All @@ -69,7 +64,7 @@ private boolean areGoogleServicesAvailable() {
}

public void addGeoNotifications(List<GeoNotification> geoNotifications,
final CallbackContext callback) {
final CallbackContext callback) {
List<Geofence> newGeofences = new ArrayList<Geofence>();
for (GeoNotification geo : geoNotifications) {
geoNotificationStore.setGeoNotification(geo);
Expand All @@ -88,14 +83,7 @@ public void onCommandExecuted() {
googleServiceCommandExecutor.QueueToExecute(geoFenceCmd);
}

public void removeGeoNotification(String id, final CallbackContext callback) {
List<String> ids = new ArrayList<String>();
ids.add(id);
removeGeoNotifications(ids, callback);
}

public void removeGeoNotifications(List<String> ids,
final CallbackContext callback) {
public void removeGeoNotifications(List<String> ids, final CallbackContext callback) {
RemoveGeofenceCommand cmd = new RemoveGeofenceCommand(context, ids);
if (callback != null) {
cmd.addListener(new IGoogleServiceCommandListener() {
Expand Down Expand Up @@ -125,13 +113,8 @@ public void removeAllGeoNotifications(final CallbackContext callback) {
* geofence transition occurs.
*/
private PendingIntent getTransitionPendingIntent() {
// Create an explicit Intent

Intent intent = new Intent(context,
ReceiveTransitionsIntentService.class);
/*
* Return the PendingIntent
*/
logger.log(Log.DEBUG, "Geofence Intent created!");
return PendingIntent.getService(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Expand Down
28 changes: 10 additions & 18 deletions src/android/GeoNotificationNotifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public class GeoNotificationNotifier {
private BeepHelper beepHelper;
private Logger logger;

public GeoNotificationNotifier(NotificationManager notificationManager,
Context context) {
public GeoNotificationNotifier(NotificationManager notificationManager, Context context) {
this.notificationManager = notificationManager;
this.context = context;
this.beepHelper = new BeepHelper();
Expand All @@ -28,33 +27,26 @@ public GeoNotificationNotifier(NotificationManager notificationManager,
public void notify(Notification notification) {
notification.setContext(context);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setVibrate(notification.getVibrate())
.setSmallIcon(notification.getSmallIcon())
.setLargeIcon(notification.getLargeIcon())
.setAutoCancel(true)
.setContentTitle(notification.getTitle())
.setContentText(notification.getText());
.setVibrate(notification.getVibrate())
.setSmallIcon(notification.getSmallIcon())
.setLargeIcon(notification.getLargeIcon())
.setAutoCancel(true)
.setContentTitle(notification.getTitle())
.setContentText(notification.getText());

if (notification.openAppOnClick) {
String packageName = context.getPackageName();
Intent resultIntent = context.getPackageManager()
.getLaunchIntentForPackage(packageName);
.getLaunchIntentForPackage(packageName);

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(
notification.id, PendingIntent.FLAG_UPDATE_CURRENT);
notification.id, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
}
try {
Expand Down
33 changes: 11 additions & 22 deletions src/android/GeofencePlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import android.util.Log;
import android.Manifest;

import com.google.gson.annotations.Expose;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
Expand All @@ -33,13 +31,13 @@ private class Action {
public JSONArray args;
public CallbackContext callbackContext;

public Action(String action,JSONArray args,CallbackContext callbackContext) {
public Action(String action, JSONArray args, CallbackContext callbackContext) {
this.action = action;
this.args = args;
this.callbackContext = callbackContext;
}
}

//FIXME: what about many executedActions at once
private Action executedAction;

Expand All @@ -61,8 +59,7 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) {
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "GeofencePlugin execute action: " + action + " args: "
+ args.toString());
Log.d(TAG, "GeofencePlugin execute action: " + action + " args: " + args.toString());
executedAction = new Action(action, args, callbackContext);

if (action.equals("addOrUpdate")) {
Expand All @@ -73,8 +70,7 @@ public boolean execute(String action, JSONArray args,
geoNotifications.add(not);
}
}
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++) {
Expand All @@ -84,8 +80,7 @@ public boolean execute(String action, JSONArray args,
} 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")) {
initialize(callbackContext);
Expand All @@ -103,15 +98,14 @@ public boolean execute(Action action) throws JSONException {
}

private GeoNotification parseFromJSONObject(JSONObject object) {
GeoNotification geo = null;
geo = GeoNotification.fromJson(object.toString());
GeoNotification geo = GeoNotification.fromJson(object.toString());
return geo;
}

public static void onTransitionReceived(List<GeoNotification> notifications) {
Log.d(TAG, "Transition Event Received!");
String js = "setTimeout('geofence.onTransitionReceived("
+ Gson.get().toJson(notifications) + ")',0)";
+ Gson.get().toJson(notifications) + ")',0)";
if (webView == null) {
Log.d(TAG, "Webview is null");
} else {
Expand All @@ -122,8 +116,7 @@ public static void onTransitionReceived(List<GeoNotification> notifications) {
private void deviceReady() {
Intent intent = cordova.getActivity().getIntent();
String data = intent.getStringExtra("geofence.notification.data");
String js = "setTimeout('geofence.onNotificationClicked("
+ data + ")',0)";
String js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)";

if (data == null) {
Log.d(TAG, "No notifications clicked.");
Expand All @@ -134,8 +127,8 @@ private void deviceReady() {

private void initialize(CallbackContext callbackContext) throws JSONException {
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};

if (!hasPermissions(permissions)) {
Expand All @@ -147,9 +140,7 @@ private void initialize(CallbackContext callbackContext) throws JSONException {

private boolean hasPermissions(String[] permissions) {
for (String permission : permissions) {
if (!PermissionHelper.hasPermission(this, permission)) {
return false;
}
if (!PermissionHelper.hasPermission(this, permission)) return false;
}

return true;
Expand All @@ -170,8 +161,6 @@ public void onRequestPermissionResult(int requestCode, String[] permissions,
}
}
Log.d(TAG, "Permission Granted!");

//try to execute method once again
execute(executedAction);
executedAction = null;
}
Expand Down
Loading

0 comments on commit abd518e

Please sign in to comment.