I have an app which requests activity updates via the ActivityRecognition API. When I load it on a device with Android For Work, the work version of the app never gets activity updates, but the personal version works fine.
I'm checking the result from requestActivityUpdates() as shown below, and I get success, but never actually get any activity intents.
Intent intent = new Intent(context, BreakTimeMonitor.class);
intent.setAction(ACTION_DETECT_ACTIVITY);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Register for activity updates
PendingResult<Status> pendingResult = ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
googleApiClient,
DETECTION_INTERVAL,
pendingIntent);
pendingResult.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (!status.isSuccess()) {
Log.e(TAG, "Error requesting activity updates: " + status.getStatusCode() + "," + status.getStatusMessage());
} else {
Log.d(TAG, "Request for activity updates successful: " + status.getStatusCode() + "," + status.getStatusMessage());
}
}
});
EDIT: The manifest does have an entry for the BreakTimeMonitor service, so that's not the issue. I've also tried adding a different user account to see if that worked, and it did - so it's just the work account that doesn't work.
Related
I'm trying to use the Google GeofencingClient (replacement of GeofencingApi) on Android. After setting up and adding the geofence, I do get a callback from the success listener and also receive the initial geofence entered/exited event in my IntentService. However, I do not receive any subsequent geofence events as I move in and out of the area. I have my radius set to 200 meters. Here's the code I'm using to add the geofence:
Geofence.Builder geoBuilder = new Geofence.Builder();
geoBuilder.setRequestId(Constants.GEOFENCE_ID);
geoBuilder.setNotificationResponsiveness(5 * 60 * 1000);
geoBuilder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT);
geoBuilder.setCircularRegion(latitude, longitude, 200f);
geoBuilder.setExpirationDuration(Geofence.NEVER_EXPIRE);
GeofencingRequest.Builder reqBuilder = new GeofencingRequest.Builder();
reqBuilder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT);
reqBuilder.addGeofence(geoBuilder.build());
PendingIntent pi = PendingIntent.getService(context, 0,
new Intent(context, GService.class), PendingIntent.FLAG_UPDATE_CURRENT);
GeofencingClient client = LocationServices.getGeofencingClient(context);
Task task = client.addGeofences(reqBuilder.build(), pi);
task.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(context, "SUCCESS", Toast.LENGTH_SHORT).show();
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "FAIL", Toast.LENGTH_SHORT).show();
}
});
In my IntentService, I log an entry when geofencingEvent.hasError() returns true. I have however not seen any error log entries, so no geofencing event has been posted to the service at all after the initial event.
Any help would be appreciated!
I am having the opposite issue, after switching from LocationServices.GeofencingApi.addGeofences to geofencingClient.addGeofences I no longer get the initial "enter" intent fired when I put the geofence just around my current location.
Before (did print "success" and fire the intent):
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
request,
createGeofencePendingIntent()
).setResultCallback(status -> {
Log.i(TAG, "onResult: " + status);
if (status.isSuccess()) {
mapsActivity.message("Adding geo-fence... Success");
drawGeofence(position, radius);
} else {
mapsActivity.message("Adding geo-fence... FAILED!");
}
});
After (does print "success" but does not fire initial "Enter"):
geofencingClient.addGeofences(request, createGeofencePendingIntent())
.addOnSuccessListener((Void)->{
mapsActivity.message("Adding geo-fence... Success");
drawGeofence(position, radius);
}).addOnFailureListener((Void)->{
// TODO: inform about fail
mapsActivity.message("Adding geo-fence... FAILED!");
})
;
Update: After writing this, it just started working (no code change). The only difference is that in the meanwhile the app "Google" updated to version 7.18.50.21.arm64
This is how I add my geofences:
public void setGeofenceRequest(Location location) {
if (geofences == null) {
geofences = new ArrayList<Geofence>();
}
geofences.add(new Geofence.Builder()
.setRequestId("3")
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
location.getLatitude(), location.getLongitude(), PSLocationService.getInstance(context).kPSGeofencingDistanceMedium)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build());
Intent intent = new Intent(context, ReceiveTransitionsBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (geofences.size() > 0) {
LocationServices.GeofencingApi.addGeofences(mLocationClient, geofences, pi);
Log.i("", "geof autopilot2 will set geofence for autopilot-3");
}
}
And this is my BroadcastReceiver. Where I should receive them:
public class ReceiveTransitionsBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.i("","autopilot valid geof on receive transisionts broadcast receiver");
PSMotionService.getInstance(ctx).buildGoogleApiClient();
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
int transitionType = geofencingEvent.getGeofenceTransition();
Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(ctx);
if(geofencingEvent.getTriggeringLocation() != null) {
if (geofenceCenter != null) {
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
} else
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
}else Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence : triggerList) {
Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
if(geofence.getRequestId().contentEquals("3")) {
Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
PSLocationService.getInstance(ctx).fastGPS = -1;
PSLocationService.getInstance(ctx).RequestLocationUpdates();
if(PSTrip.getActiveTrip() != null) {
PSLocationService.getInstance(ctx).removeAutoPilotGeofence();
}else PSMotionService.getInstance(ctx).checkinTime = System.currentTimeMillis() / 1000;
}
}
}
}
}
Now usually it works, but not always. I would say that only about 75% of the time it should work, the geofence events are actually called. I feel like the more time since I've set the geofence, the less likely it will be to be called.
Why is this happening? Is the triggering event also being dismissed, when the app is cleaned by the garbage collector?
How can I make it so that my geofence is always being called, when the case?
EDIT:
This is my defaultConfig:
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
ndk {
moduleName "ndkVidyoSample"
}
}
I changed from a Broadcast Receiver to a IntentService:
public class PSGeofenceTransitionsIntentService extends IntentService {
private static ActivityManager manager;
private static PSGeofenceTransitionsIntentService instance;
private GeofencingClient mGeofencingClient;
Context context;
private PendingIntent mGeofencePendingIntent;
public static boolean isMyServiceRunning(Class<?> serviceClass) {
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public static PSGeofenceTransitionsIntentService getInstance(Context context) {
if (instance == null) {
// Create the instance
instance = new PSGeofenceTransitionsIntentService(context);
}
if (!isMyServiceRunning(PSGeofenceTransitionsIntentService.class)) {
Intent bindIntent = new Intent(context, PSGeofenceTransitionsIntentService.class);
context.startService(bindIntent);
}
// Return the instance
return instance;
}
public PSGeofenceTransitionsIntentService() {
super("GeofenceTransitionsIntentService");
}
public PSGeofenceTransitionsIntentService(Context context) {
super("GeofenceTransitionsIntentService");
mGeofencingClient = LocationServices.getGeofencingClient(context);
manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
instance = this;
this.context = context;
}
protected void onHandleIntent(Intent intent) {
Log.i("", "autopilot valid geof on receive transisionts broadcast receiver");
PSMotionService.getInstance(context).buildGoogleApiClient();
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
int transitionType = geofencingEvent.getGeofenceTransition();
Location geofenceCenter = PSApplicationClass.getInstance().pref.getGeoCenter(context);
if (geofencingEvent.getTriggeringLocation() != null) {
if (geofenceCenter != null) {
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString() + " / GEOFENCE CENTER: " + geofenceCenter.getLatitude() + ", " + geofenceCenter.getLongitude(), "D", Constants.TRACKER);
} else
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver TRIGGERING LOCATION: " + geofencingEvent.getTriggeringLocation().toString(), "D", Constants.TRACKER);
} else
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver ERROR => TRIGGERING LOCATION NULL", "D", Constants.TRACKER);
if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggerList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence : triggerList) {
Log.i("", "geof is s receive transition broadcast receiver " + transitionType + " GPS zone " + geofence.getRequestId());
if (geofence.getRequestId().contentEquals("3")) {
Log.i("", "geof autopilot2 ENTERED GEOFENCE will start pilot with first location");
Utils.appendLog("GEOFENCE ENTERED ReceiveTransitionsBroadcastReceiver check to see if should start pilot", "T", Constants.TRACKER);
PSLocationService.getInstance(context).isLocationRequestsOn = -1;
PSLocationService.getInstance(context).RequestLocationUpdates();
if (PSTrip.getActiveTrip() != null) {
removeAutoPilotGeofence();
} else
PSMotionService.getInstance(context).checkinTime = System.currentTimeMillis() / 1000;
}
}
}
}
public void removeAutoPilotGeofence() {
try {
Log.i("", "autopilot remove autopilot geofence");
List<String> list = new ArrayList<String>();
list.add("3");
if(mGeofencingClient == null)
mGeofencingClient = LocationServices.getGeofencingClient(context);
mGeofencingClient.removeGeofences(list).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Utils.appendLog("GEOFENCE removeAutoPilotGeofence Success removing geofences!", "I", Constants.TRACKER);
Log.i("", "GEOFENCE removeAutoPilotGeofence Success removing geofences!");
PSApplicationClass.getInstance().pref.setGeoCenterString(context, "-1");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Utils.appendLog("GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage(), "I", Constants.TRACKER);
Log.i("", "GEOFENCE removeAutoPilotGeofence FAILURE removing geofences!" + e.getMessage());
}
});
Utils.appendLog("GEOFENCE: Disabling geofence done removeAutoPilotGeofence", "E", Constants.TRACKER);
} catch (final Exception e) {
if (e.getMessage().contains("GoogleApiClient") && e.getMessage().contains("not connected")) {
PSLocationService.getInstance(context).startLocationClient();
Handler han = new Handler();
han.postDelayed(new Runnable() {
#Override
public void run() {
Utils.appendLog("autopilot2 error will try again", "E", Constants.TRACKER);
removeAutoPilotGeofence();
}
}, 1000);
}
Log.i("", "autopilot2 error replaceFragment autopilot geofence:" + e.getMessage());
Utils.appendLog("autopilot2 error replaceFragment autopilot geofence:" + e.getMessage(), "E", Constants.TRACKER);
}
}
public void setGeofenceRequest(final Location location) {
ArrayList geofences = new ArrayList<>();
geofences.add(new Geofence.Builder()
.setRequestId("3")
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
location.getLatitude(), location.getLongitude(), PSLocationService.kPSGeofencingDistanceMedium)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build());
//ADDING GEOFENCES
if (geofences.size() > 0) {
if(mGeofencingClient == null)
mGeofencingClient = LocationServices.getGeofencingClient(context);
mGeofencingClient.addGeofences(getGeofencingRequest(location, geofences), getGeofencePendingIntent()).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
RealmLocation realmLocation = new RealmLocation(location.getLatitude(), location.getLongitude(), location.getTime() / 1000, null, true);
realmLocation.setAccuracy(location.getAccuracy());
realmLocation.setSpeed(location.getSpeed());
PSApplicationClass.getInstance().pref.setGeoCenter(realmLocation, context);
Utils.appendLog("GEOFENCE setGeofenceRequest Success adding geofences!" + location.getLatitude() + " / " + location.getLongitude(), "I", Constants.TRACKER);
Log.i("", "GEOFENCE setGeofenceRequest Success adding geofences! " + location.getLatitude() + " / " + location.getLongitude());
PSLocationService.getInstance(context).stopLocationClient();
PSMotionService.getInstance(context).buildGoogleApiClient();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Utils.appendLog("GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage(), "I", Constants.TRACKER);
Log.i("", "GEOFENCE setGeofenceRequest FAILURE adding geofences!" + e.getMessage());
}
});
Log.i("", "geof autopilot2 will set geofence for autopilot-3");
}
}
/**
* Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
* issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
* current list of geofences.
*
* #return A PendingIntent for the IntentService that handles geofence transitions.
*/
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(context, PSGeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
/**
* Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored.
* Also specifies how the geofence notifications are initially triggered.
*/
private GeofencingRequest getGeofencingRequest(Location location, ArrayList<Geofence> geofences) {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
// The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
// GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
// is already inside that geofence.
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_EXIT);
// Add the geofences to be monitored by geofencing service.
builder.addGeofences(geofences);
// Return a GeofencingRequest.
return builder.build();
}
}
I have in it also the code to remove and add the geofences, and the listener always goes into onSuccess regarding adding them.
For starters, I would not put this code inside a BroadcastReceiver.
Besides being bad practice, the component might be shutdown before the code has finished executing.
Please consider starting a Service from your Receiver, if you need to run code that might take some time.
Otherwise for a short execution time, you may use an IntentService.
By looking at your code, I'm aware of two reasons your Geofences are not working as expected:
1) The nature of Geofences
Geofences API retrieves your location mostly from WiFi / Cellular Data, which is often unavailable.
I tried to use Geofences once, and I found them very inaccurate. I switched to LocationManager making it use pure GPS location and it met my expectations.
Please see this answer, which advises to
Poll the GPS hardware on an interval without doing anything with the result and you'll start getting more accurate geofences.
I have never tried Google's FusedLocation API, but I have heard people saying it worked very well for them.
If you use LocationManager, you will have to implement your 'Geofencing logic' yourself; you can easily do it with Location.distanceTo(Location).
Example:
final float distanceFromCenter = currentLocation.distanceTo(this.destination);
if (distanceFromCenter <= YOUR_RADIUS_IN_METERS) {
// you are inside your geofence
}
2) CPU is not active
The fact that the Geofences are active, does not necessarily mean that your phone is awake and computing location checks.
To fix that, you can start a ForegroundService from your BroacastReceiver. The Service should hold a partial WakeLock as well.
This guarantees that:
The OS does not kill the service (or better: less chance to be killed...)
The user is aware of the service and can dismiss it if necessary
The CPU is running. Therefore you can be sure that the code that retrieves the location is running (please remember to to release the WakeLock when the service stops).
Please note that Android may still kill your service if necessary.
You can find plenty of examples on the web on how to start a ForegroundService from a BroadcastReceiver, how to hold a WakeLock and so on...
Also, check out to the new Android O API, that brought some minor changes to the ForegroundService and other components.
PS: I have developed and application that uses all the components mentioned above (except for the FusedLocation) and I was extremely satisfied.
EDIT: Answering OP's questions
Okey, let's try to make some order here, otherwise future readers may easily get confused. I'll start by answering what written in the original question and the 'bounty banner', then the OP edits, and finally the questions the OP placed in the comments.
1) Original question
Is the triggering event also being dismissed, when the app is cleaned by the garbage collector?
Most probably yes. See this answer where OP implemented a service that runs in a separate process, in order to make geofence be triggered even when the app is killed.
I need to understand what causes the geofences not to get called, if enough time has passed
Plenty of reasons. See my original answer.
I saw an implementation of the geofence logic with an Service instead of a broadcast receiver, will that work better?
A Receiver and a Service are two different things. Please read Android's documentation. You can start a Service from a BroadcastReceiver, which is usually the preferred way to 'receive' PendingIntents and do something with them.
2) Edits
Please note that I did not tell you to replace the BroadcastReceiver with a Service, but that it might be a good idea to start a Service from your Receiver and handle all your logic there.
Making your IntentService a Singleton class is not necessary as (from IntentService documentation)
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
Do not store Context into a Singleton class or some static references. I'm impressed Android Studio did not warn you.
3) Comments
I need this to work 24/7 hence I cannot use the location all the time, cause of obvious battery issues.
Please read Android Oreo Background Execution Limits. This might be an issue for you.
Also now that I changed to a intentService, is that enough to ensure it should stay awake?
No, as I said, you probably need a partial WakeLock in order to turn on the CPU.
Do I need to initiate it another way, in order to keep it in the foreground?
Yes. In order to start a Foreground Service, you need to call startForeground(int, Notification)
Please note: IntentServices lifespan is limited to the end of the onHandleIntent() function. They are not supposed to live for more than a few seconds, typically. Use the Service class if you want to start a Foreground.
Moreover, as said in the original answer, a new Foreground API is available and preferred for Android Oreo.
Not a question, just a notice: I need to use here Geofencing. (Geofencing will start if necessary the gps
Ok perfect. See what works best for you.
I'm fighting against the NotificationListenerService without much luck.
I tried a lot of recipes found here and there, especially on so... But it works quite inconsistently.
A first look at the code :
Manifest :
<service
android:name=".services.NLService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
Then the service itself :
public class NLService extends NotificationListenerService {
private String TAG = "NLService";
// bind and unbind seems to make it work with Android 6...
// but is never called with Android 4.4...
#Override
public IBinder onBind(Intent mIntent) {
IBinder mIBinder = super.onBind(mIntent);
Log.i(TAG, "onBind");
return mIBinder;
}
#Override
public boolean onUnbind(Intent mIntent) {
boolean mOnUnbind = super.onUnbind(mIntent);
Log.i(TAG, "onUnbind");
isNotificationAccessEnabled = false;
try {
} catch (Exception e) {
Log.e(TAG, "Error during unbind", e);
}
return mOnUnbind;
}
// onCreate is called with Android 4.4
// because the service is explicitly started from the MainActivity.
// Not on Android 6 where the system binds this service itself...
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "********** onCreate");
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i(TAG, "********** onNotificationPosted");
Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i(TAG, "********** onNOtificationRemoved");
Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
}
}
And in the main Activity the service is started or we ask the user to enable the setting if needed :
if (!Utilities.hasNotificationAccess(this))
{
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
Log.i(TAG,"hasNotificationAccess NO");
}
else
{
Log.i(TAG,"hasNotificationAccess YES");
// without this startService, it never works with Android 4.4...
// but this is not needed in Android 6...
Intent mServiceIntent = new Intent(this, NLService.class);
startService(mServiceIntent);
}
Obviously, the secure setting access for notifications is enabled...
On Android 6 :
On the NLService itself, the addition of the onBind and onUnbind methods make it work, I can se the onBind log, and the onNotificationPosted is triggered nicely. But it lasts until the next launch of the app, then no more binding, no more onNotificationPosted, just nothing happens until I go back to security settings to uncheck-recheck the notifications access: repeating this each time the App is started is not something possible in a production environment.
On Android 4.4 :
In contrast to Android 6, in the MainActivity I need to explicitly start the NLService otherwise it never stats by itself. But once again it works for the first launch and never works again until uncheck-recheck the security setting...
Did I miss something obvious ?
There is a problem with Android caching. When you upload app on the device, OS connects your service to Notification Manager. If you ran your app before, Android founds this service in cache so it's not reconnected.
Workaround: before pushing the app on your device, rename your service (refactor option in Android Studio works well) - Android will recognize this service as new one and connect to Notification Manager.
https://developer.android.com/reference/android/service/notification/NotificationListenerService.html#onListenerConnected() - this method will be invoked after connecting to Notification Manager so you can check if your service is connected or not.
I am trying to subscribe to location updates via Google's FusedLocationProviderApi. I want to receive updates in the background, so that I will receive updates even if the app is killed. Following the online documentation as best as I can, I've written the following code. Note: this is being done in an intent service, not on the UI thread, which is why I'm using blocking connect/result methods.
private void startLocationServices(String deviceId, int pollingInterval) {
Log.i(TAG, "Starting location services with interval: " + pollingInterval + "ms");
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
final PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire();
final GoogleApiClient googleApiClient =
new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.build();
ConnectionResult result = googleApiClient.blockingConnect();
if (!result.isSuccess() || !googleApiClient.isConnected()) {
Log.e(TAG, "Failed to connect to Google Api");
wakeLock.release();
return;
}
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(pollingInterval);
locationRequest.setFastestInterval(10000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
Intent locationIntent = new Intent(this, GeoBroadcastReceiver.class);
locationIntent.putExtra(EXTRA_LOCATION_UPDATE_DEVICE_ID, deviceId);
locationIntent.setAction(GeoBroadcastReceiver.ACTION_LOCATION_UPDATE);
PendingIntent locationPendingIntent = PendingIntent.getBroadcast(
this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingResult pendingResult = LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, locationPendingIntent);
Result requestResult = pendingResult.await();
Status requestStatus = requestResult.getStatus();
if (requestStatus.isSuccess()) {
Log.i(TAG, "Successfully subscribed to location updates.");
} else {
Log.e(TAG, String.format(
"Failed subscribe to location updates. Error code: %d, Message: %s.",
requestStatus.getStatusCode(),
requestStatus.getStatusMessage()));
}
googleApiClient.disconnect();
wakeLock.release();
}
When I run this, I see that requestStatus.isSuccess() returns true, indicating that I've successfully subscribed to the location updates. Additionally, The GeoBroadcastReciever, which extends WakefulBroadcastReceiver, receives an intent at the correct polling interval, with the correct action. Good so far, it would seem. Here is what I'm doing in the onReceive method for the GeoBroadcastReceiver:
if (LocationResult.hasResult(intent)) {
LocationResult locationResult = LocationResult.extractResult(intent);
Location location = locationResult.getLastLocation();
if (location != null) {
GeoMonitoringService.wakefulLocationUpdate(context, location);
} else {
Log.e(TAG, "LocationResult does not contain a LastLocation.");
}
} else {
Log.e(TAG, "Intent does not contain a LocationResult.");
}
The problem is, whenever the intent comes in, it does not contain the LocationResult, nor does it contain the LocationAvailabilityResult. I inspected the incoming intent in the debugger, and the only item in the intent's extras is the extra I added when setting up the intent (the device id). As such, LocationResult.hasResult() returns false. Every single time.
I've tried this on a Galaxy Note 4 running 4.0.1, and a Nexus 4 running 5.1.1, with the same result.
If I disable location on the phone, I stop receiving intents altogether, as expected.
Remove the extras from the pending intent, otherwise the location result is not delivered. I can't find where in the documentation this is explained but I found out after lot of trial and error.
A workaround (Christophe Beyls suggested that only Intent Data should be used)
So, since I only need to send a few parameters, so I do something like this:
while building the Intent before the requestLocationUpdates:
intent.setData(Uri.parse("http://a.com/a?"+ Param1+ "?" + Param2+ "?" + Param3);
and in the BroadcastReceiver:
String[] parameters = intent.getDataString().split("[?]");
This works fine, and intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED)
does return the location.
You can use:
int id = 7;
String name = "myName";
uriBuilder.scheme("http")
.authority("workaround.com")
.appendPath("extra")
.appendQueryParameter("id", String.valueOf(id))
.appendQueryParameter("name", name);
intent.setData(uriBuilder.build());
and
#Override
protected void onHandleIntent(Intent intent) {
if (LocationResult.hasResult(intent)) {
int id = Integer.valueOf(uri.getQueryParameter("id"));
String name = uri.getQueryParameter("name");
....
}
}
I have a main activity and a service where i update some data taken from facebook in background every x hours.
In these days i'm finally moving to the new SDK 3.0.1 (from 2.x) and i have a problem with passing the facebook Session to the service:
If the service runs when the main activity is still running everything works fine, otherwise my session is null and so it crashes at if (session.isOpened()) { ...} because session==null.
here's my code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ServiceUpdate", "Received start id " + startId + ": " + intent);
session = Session.getActiveSession();
startservice();
return START_STICKY;
}
private void startservice() {
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (session.isOpened()) {
if (isOnline()) {
Log.i("ServiceUpdate", "start timer");
update();
Log.i("ServiceUpdate", "end timer");
}
}
}, 600000, 6 * 3600000);
}
Do i have to initialize the session with saved acces_token and expire_time as I used to do with SDK 2.x ?
Thank you!
The default behavior for Session is to save the token information in Android's SharedPreferences, so you should be able to just call Session.openActiveSessionFromCache in your service. If that returns null, then that means your user hasn't connected with Facebook yet.