I want to monitor location changes using FusedLocationProviderApi
and phone activity changes using ActivityRecognitionApi
in the background, even if I close my app.
IntentService
handles PendingIntent
s and does some long running operations (around 10 seconds). Code below is requesting location and activity recognition updates, every change calls SenseDataIntentService
.
I am calling methods requestLocationUpdates()
and requestActivityUpdates()
on every app start and never stop them as I want updates constantly in background. The problem occurs when I start the app too many times and the IntentService
queue gets big (I get same location and phone activities multiple times). I thought that PendingIntent.FLAG_CANCEL_CURRENT
or PendingIntent.FLAG_UPDATE_CURRENT
would solve the issue but this is not the case.
Any solutions to this problem? Like how to stop all previously requested location updates by this app and only then starting new request. Any help will be much appreciated!
Please find the relevant code pieces below.
private void requestLocationUpdates() {
if (!PermissionsHelper.hasPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d(TAG, "No location permissions provided.");
mPendingAction = true;
return;
}
stopAllUpdates();
Log.d(TAG, "Firing requested location updates.");
LocationRequest myLocationRequest = new LocationRequest();
myLocationRequest.setInterval(Constants.APPROXIMATE_INTERVAL_MILLIS);
myLocationRequest.setPriority(LocationRequest.PRIORITY_NO_POWER);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, myLocationRequest, getSensingServicePendingIntent());
}
Method to build PendingIntent
:
private PendingIntent getSensingServicePendingIntent(Integer userLabel) {
Intent i = new Intent(mContext, SenseDataIntentService.class);
return PendingIntent
.getService(mContext, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
Code for requesting phone activity changes:
private void requestActivityUpdates() {
Log.d(TAG, "Starting requested activity recognition updates.");
stopAllUpdates();
ActivityRecognition
.ActivityRecognitionApi
.requestActivityUpdates(mGoogleApiClient, Constants.APPROXIMATE_INTERVAL_MILLIS, getSensingServicePendingIntent())
.setResultCallback(this);
}