Commit 9593a6c4 authored by Chris Scott's avatar Chris Scott

Re-organize methods

parent 4b1df825
...@@ -182,6 +182,9 @@ var app = { ...@@ -182,6 +182,9 @@ var app = {
headers: { headers: {
"X-FOO": "bar" "X-FOO": "bar"
}, },
params: {
"auth_token": "bar"
},
forceReload: false, forceReload: false,
activityType: 'AutomotiveNavigation', activityType: 'AutomotiveNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle. debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
......
...@@ -41,6 +41,9 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -41,6 +41,9 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
private Location stationaryLocation; private Location stationaryLocation;
public static boolean isActive() {
return gWebView != null;
}
@Override @Override
protected void pluginInitialize() { protected void pluginInitialize() {
...@@ -52,19 +55,20 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -52,19 +55,20 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "execute / action : " + action); Log.d(TAG, "execute / action : " + action);
Boolean result = false;
Activity activity = this.cordova.getActivity();
Boolean result = false;
if (ACTION_START.equalsIgnoreCase(action) && !isEnabled) { if (ACTION_START.equalsIgnoreCase(action) && !isEnabled) {
result = true; result = true;
isEnabled = true; isEnabled = true;
if (!BackgroundGeolocationService.isInstanceCreated()) { if (!BackgroundGeolocationService.isInstanceCreated()) {
this.cordova.getActivity().startService(backgroundServiceIntent); activity.startService(backgroundServiceIntent);
} }
} else if (ACTION_STOP.equalsIgnoreCase(action)) { } else if (ACTION_STOP.equalsIgnoreCase(action)) {
result = true; result = true;
isEnabled = false; isEnabled = false;
this.cordova.getActivity().stopService(backgroundServiceIntent); activity.stopService(backgroundServiceIntent);
callbackContext.success(); callbackContext.success();
} else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) { } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) {
result = applyConfig(data); result = applyConfig(data);
...@@ -83,11 +87,11 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -83,11 +87,11 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
callbackContext.success(); callbackContext.success();
} }
} else if (ACTION_SET_CONFIG.equalsIgnoreCase(action)) { } else if (ACTION_SET_CONFIG.equalsIgnoreCase(action)) {
this.cordova.getActivity().stopService(backgroundServiceIntent); activity.stopService(backgroundServiceIntent);
result = applyConfig(data); result = applyConfig(data);
// TODO reconfigure Service // TODO reconfigure Service
if (result) { if (result) {
this.cordova.getActivity().stopService(backgroundServiceIntent); activity.stopService(backgroundServiceIntent);
callbackContext.success(); callbackContext.success();
} else { } else {
callbackContext.error("- Configuration error!"); callbackContext.error("- Configuration error!");
...@@ -96,9 +100,9 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -96,9 +100,9 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
result = true; result = true;
this.stationaryCallback = callbackContext; this.stationaryCallback = callbackContext;
} }
return result; return result;
} }
private boolean applyConfig(JSONArray data) { private boolean applyConfig(JSONArray data) {
// This is the IntentService we'll provide to google-play API. // This is the IntentService we'll provide to google-play API.
Activity activity = this.cordova.getActivity(); Activity activity = this.cordova.getActivity();
...@@ -149,10 +153,6 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -149,10 +153,6 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
} }
} }
public static boolean isActive() {
return gWebView != null;
}
public void onPause(boolean multitasking) { public void onPause(boolean multitasking) {
Log.i(TAG, "- onPause"); Log.i(TAG, "- onPause");
if (isEnabled) { if (isEnabled) {
...@@ -165,30 +165,26 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin { ...@@ -165,30 +165,26 @@ public class BackgroundGeolocationPlugin extends CordovaPlugin {
//removeLocationUpdates(); //removeLocationUpdates();
} }
} }
/**
* EventBus listener
* @param {Location} location
*/
public void onEventMainThread(Location location) { public void onEventMainThread(Location location) {
PluginResult result = new PluginResult(PluginResult.Status.OK, BackgroundGeolocationService.locationToJson(location));
result.setKeepCallback(true);
if (location instanceof StationaryLocation) { if (location instanceof StationaryLocation) {
stationaryLocation = location; stationaryLocation = location;
fireStationaryListener(); if (stationaryCallback != null) {
runInBackground(stationaryCallback, result);
}
} else { } else {
PluginResult result = new PluginResult(PluginResult.Status.OK, BackgroundGeolocationService.locationToJson(location));
result.setKeepCallback(true); result.setKeepCallback(true);
runInBackground(locationCallback, result); runInBackground(locationCallback, result);
} }
} }
/**
* Execute onStationary javascript callback when device is determined to have just stopped
*/
private void fireStationaryListener() {
Log.i(TAG, "- fire stationary listener");
if ( (stationaryCallback != null) && (stationaryLocation != null) ) {
final PluginResult result = new PluginResult(PluginResult.Status.OK, BackgroundGeolocationService.locationToJson(stationaryLocation));
result.setKeepCallback(true);
runInBackground(stationaryCallback, result);
}
}
/** /**
* Run a javascript callback in Background * Run a javascript callback in Background
* @param cb * @param cb
......
...@@ -40,67 +40,98 @@ import android.os.PowerManager.WakeLock; ...@@ -40,67 +40,98 @@ import android.os.PowerManager.WakeLock;
import android.util.Log; import android.util.Log;
public class BackgroundGeolocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public class BackgroundGeolocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BackgroundGeolocation";
private static BackgroundGeolocationService instance = null; private static BackgroundGeolocationService instance = null;
public static boolean isInstanceCreated() { public static boolean isInstanceCreated() {
return instance != null; return instance != null;
} }
private static final String TAG = "BackgroundGeolocation"; private GoogleApiClient googleApiClient;
private WakeLock wakeLock; private WakeLock wakeLock;
private ToneGenerator toneGenerator;
private PendingIntent activityRecognitionPI; private PendingIntent activityRecognitionPI;
private PendingIntent locationUpdatePI; private PendingIntent locationUpdatePI;
private LocationRequest locationRequest;
private Boolean isEnabled = false;
private Boolean isMoving = false;
// Common config // Common config
/**
* @config {Integer} desiredAccuracy
*/
private Integer desiredAccuracy = 10; private Integer desiredAccuracy = 10;
/**
* @config {Float} distanceFilter
*/
private Float distanceFilter = (float) 50; private Float distanceFilter = (float) 50;
/**
* @config {Boolean} isDebugging
*/
private Boolean isDebugging = false; private Boolean isDebugging = false;
/**
* @config {Boolean} stopOnTerminate
*/
private Boolean stopOnTerminate = false; private Boolean stopOnTerminate = false;
// Android-only config // Android-only config
/**
* @config {Integer} locationUpdateInterval (ms)
*/
private Integer locationUpdateInterval = 60000; private Integer locationUpdateInterval = 60000;
/**
* @config {Integer{ activityRecognitionInterval (ms)
*/
private Integer activityRecognitionInterval = 60000; private Integer activityRecognitionInterval = 60000;
/*
* @config {Boolean} forceReload Whether to reboot the Android Activity when detected to have closed
*/
private Boolean forceReload = false; private Boolean forceReload = false;
/**
* @config {Integer} stopTimeout The time to wait after ARS STILL to turn of GPS
*/
private long stopTimeout = 0;
// HTTP config
/**
* @config {String} url For sending location to your server
*/
private String url = null; private String url = null;
/**
* @config {JSONObject} params For sending location to your server
*/
private JSONObject params = new JSONObject(); private JSONObject params = new JSONObject();
private JSONObject headers = null;
/** /**
* @config {Integer} stopTimeout The time to wait after ARS STILL to turn of GPS * @config {JSONObject} headers For sending location to your server
*/ */
private long stopTimeout = 0; private JSONObject headers = null;
// The elapsed millis when the ARS detected STILL // Flags
private long stoppedAt = 0; private Boolean isEnabled = false;
private Boolean isMoving = false;
private long stoppedAt = 0;
private Location stationaryLocation; private Location stationaryLocation;
private GoogleApiClient googleApiClient;
private DetectedActivity currentActivity; private DetectedActivity currentActivity;
private ToneGenerator toneGenerator;
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "- Start BackgroundGeolocationService");
instance = this; instance = this;
EventBus.getDefault().register(this); EventBus.getDefault().register(this);
isEnabled = true; isEnabled = true;
isDebugging = intent.getBooleanExtra("debug", false); stopOnTerminate = intent.getBooleanExtra("stopOnTerminate", true);
distanceFilter = intent.getFloatExtra("distanceFilter", 50); isDebugging = intent.getBooleanExtra("debug", false);
desiredAccuracy = intent.getIntExtra("desiredAccuracy", 10); distanceFilter = intent.getFloatExtra("distanceFilter", 50);
locationUpdateInterval = intent.getIntExtra("locationUpdateInterval", 30000); desiredAccuracy = intent.getIntExtra("desiredAccuracy", 10);
locationUpdateInterval = intent.getIntExtra("locationUpdateInterval", 30000);
activityRecognitionInterval = intent.getIntExtra("activityRecognitionInterval", 10000); activityRecognitionInterval = intent.getIntExtra("activityRecognitionInterval", 10000);
stopTimeout = intent.getLongExtra("stopTimeout", 0); stopTimeout = intent.getLongExtra("stopTimeout", 0);
forceReload = intent.getBooleanExtra("forceReload", false); forceReload = intent.getBooleanExtra("forceReload", false);
// HTTP Configuration
url = intent.getStringExtra("url"); url = intent.getStringExtra("url");
try { try {
if (intent.hasExtra("params")) { if (intent.hasExtra("params")) {
...@@ -113,25 +144,22 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -113,25 +144,22 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
e.printStackTrace(); e.printStackTrace();
} }
Log.i(TAG, "----------------------------------------"); // For debug sounds, turn on ToneGenerator.
Log.i(TAG, "- Start BackgroundGeolocationService");
Log.i(TAG, " debug: " + isDebugging);
Log.i(TAG, " distanceFilter: " + distanceFilter);
Log.i(TAG, " desiredAccuracy: " + desiredAccuracy);
Log.i(TAG, " locationUpdateInterval: " + locationUpdateInterval);
Log.i(TAG, " activityRecognitionInterval: " + activityRecognitionInterval);
Log.i(TAG, " stopTimeout: " + stopTimeout);
Log.i(TAG, "----------------------------------------");
if (isDebugging) { if (isDebugging) {
toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
} }
// Configure FusedLocationProvider
locationRequest = LocationRequest.create()
.setPriority(translateDesiredAccuracy(desiredAccuracy))
.setInterval(this.locationUpdateInterval)
.setFastestInterval(30000)
.setSmallestDisplacement(distanceFilter);
// Connect to google-play services. // Connect to google-play services.
if (ConnectionResult.SUCCESS == GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)) { if (ConnectionResult.SUCCESS == GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)) {
Log.i(TAG, "- Connecting to GooglePlayServices..."); Log.i(TAG, "- Connecting to GooglePlayServices...");
googleApiClient = new GoogleApiClient.Builder(this) googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API) .addApi(LocationServices.API)
.addApi(ActivityRecognition.API) .addApi(ActivityRecognition.API)
...@@ -144,9 +172,11 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -144,9 +172,11 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
Log.e(TAG, "- GooglePlayServices unavailable"); Log.e(TAG, "- GooglePlayServices unavailable");
} }
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); /*
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire(); wakeLock.acquire();
*/
return Service.START_REDELIVER_INTENT; return Service.START_REDELIVER_INTENT;
} }
...@@ -160,26 +190,28 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -160,26 +190,28 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
@Override @Override
public void onConnectionFailed(ConnectionResult arg0) { public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void onConnected(Bundle arg0) { public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub Log.i(TAG, "- GooglePlayServices connected");
Intent arsIntent = new Intent(this, ActivityRecognitionService.class); Intent arsIntent = new Intent(this, ActivityRecognitionService.class);
activityRecognitionPI = PendingIntent.getService(this, 0, arsIntent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionPI = PendingIntent.getService(this, 0, arsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.i(TAG, "- GooglePlayServices connected");
Intent locationIntent = new Intent(this, LocationService.class); Intent locationIntent = new Intent(this, LocationService.class);
locationUpdatePI = PendingIntent.getService(this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT); locationUpdatePI = PendingIntent.getService(this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Start monitoring ARS
if (googleApiClient.isConnected()) { if (googleApiClient.isConnected()) {
requestActivityUpdates(); requestActivityUpdates();
} }
} }
/**
* EventBus listener for ARS
* @param {ActivityRecognitionResult} result
*/
public void onEventMainThread(ActivityRecognitionResult result) { public void onEventMainThread(ActivityRecognitionResult result) {
currentActivity = result.getMostProbableActivity(); currentActivity = result.getMostProbableActivity();
String probableActivityName = getActivityName(currentActivity.getType()); String probableActivityName = getActivityName(currentActivity.getType());
...@@ -201,7 +233,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -201,7 +233,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
break; break;
case DetectedActivity.UNKNOWN: case DetectedActivity.UNKNOWN:
case DetectedActivity.TILTING: case DetectedActivity.TILTING:
nowMoving = isMoving; // We're not interested in these modes.
return; return;
} }
...@@ -220,7 +252,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -220,7 +252,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
long elapsedMillis = result.getElapsedRealtimeMillis() - stoppedAt; long elapsedMillis = result.getElapsedRealtimeMillis() - stoppedAt;
long elapsedMinutes = TimeUnit.MILLISECONDS.toMinutes(elapsedMillis); long elapsedMinutes = TimeUnit.MILLISECONDS.toMinutes(elapsedMillis);
Log.i(TAG, "- Waiting for stopTimeout (" + stopTimeout + " min): elapsed min: " + elapsedMinutes); Log.i(TAG, "- Waiting for stopTimeout (" + stopTimeout + " min): elapsed min: " + elapsedMinutes);
if (elapsedMinutes == stopTimeout) { if (elapsedMinutes >= stopTimeout) {
justStopped = true; justStopped = true;
} else { } else {
return; return;
...@@ -239,11 +271,10 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -239,11 +271,10 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
Log.i(TAG, "BUS Rx:" + location.toString()); Log.i(TAG, "BUS Rx:" + location.toString());
startTone("beep"); startTone("beep");
Log.i(TAG, "- forceReload: " + BackgroundGeolocationPlugin.forceReload);
// Force main-activity reload (if not running) if we're detected to be moving. // Force main-activity reload (if not running) if we're detected to be moving.
boolean isPluginActive = BackgroundGeolocationPlugin.isActive(); boolean isPluginActive = BackgroundGeolocationPlugin.isActive();
if (forceReload && !isPluginActive) { if (!isPluginActive && forceReload) {
forceMainActivityReload(); forceMainActivityReload();
} }
if (url != null) { if (url != null) {
...@@ -255,38 +286,25 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -255,38 +286,25 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
} }
} }
} }
private void setPace(Boolean moving) { private void setPace(Boolean moving) {
Log.i(TAG, "- setPace: " + moving); Log.i(TAG, "- setPace: " + moving);
boolean wasMoving = isMoving; boolean wasMoving = isMoving;
isMoving = moving; isMoving = moving;
if (moving && isEnabled) { if (moving && isEnabled) {
if (!wasMoving) { if (!wasMoving) {
startTone("doodly_doo"); startTone("doodly_doo");
} }
stationaryLocation = null; stationaryLocation = null;
requestLocationUpdates();
// Here's where the FusedLocationProvider is controlled.
LocationRequest request = LocationRequest.create()
.setPriority(translateDesiredAccuracy(desiredAccuracy))
.setInterval(this.locationUpdateInterval)
.setFastestInterval(30000)
.setSmallestDisplacement(distanceFilter);
requestLocationUpdates(request);
} else { } else {
removeLocationUpdates(); removeLocationUpdates();
if (stationaryLocation == null) { if (stationaryLocation == null) {
startTone("long_beep"); startTone("long_beep");
// set our stationaryLocation
// Re-set our stationaryLocation
stationaryLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); stationaryLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
stationaryLocation.removeSpeed(); EventBus.getDefault().post(new BackgroundGeolocationService.StationaryLocation(stationaryLocation));
// Inform Javascript of our stationaryLocation
StationaryLocation l = new BackgroundGeolocationService.StationaryLocation(stationaryLocation);
EventBus.getDefault().post(l);
//fireStationaryListener();
} }
} }
} }
...@@ -314,6 +332,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -314,6 +332,7 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
} }
return accuracy; return accuracy;
} }
private String getActivityName(int activityType) { private String getActivityName(int activityType) {
switch (activityType) { switch (activityType) {
case DetectedActivity.IN_VEHICLE: case DetectedActivity.IN_VEHICLE:
...@@ -416,8 +435,8 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl ...@@ -416,8 +435,8 @@ public class BackgroundGeolocationService extends Service implements GoogleApiCl
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient, activityRecognitionPI); ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient, activityRecognitionPI);
} }
private void requestLocationUpdates(LocationRequest request) { private void requestLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, locationUpdatePI); LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationUpdatePI);
} }
private void removeLocationUpdates() { private void removeLocationUpdates() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment