Android geofence stop working when app is not running

Viewed 1140

I'm working on an Android app that uses Google Geofence API. My code seems to work fine while the app is on foreground, but as soon as the app move to Pause state the geofence broadcast receiver stop receiving events. I'm pretty sure that the geofence is getting removed when the app move to background but I don't know why this is happening.

Breafly, I create a list of geofences

Geofence geofence = new Geofence.Builder()
            .setRequestId(id)
            .setCircularRegion(lat, lng, GEOFENCE_RADIUS)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(1000)
            .build();
        geofences.add(geofence);

Then I create a request

geofenceRequest = new GeofencingRequest.Builder()
        .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL)
        .addGeofences(geofences)
        .build();

At this point I add the geofence

LocationServices.GeofencingApi.addGeofences(googleApiClient, request, createGeofencePendingIntent()).setResultCallback(this);

And finally I start the broadcast receiver

String GEOFENCE_ACTION = "gac.broadcast.geofence";
    if (geoFencePendingIntent != null)
    {
        GoogleApiClientManager.setGeofencePendingIntent(geoFencePendingIntent);
        return geoFencePendingIntent;
    }
    Intent intent = new Intent(GEOFENCE_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    GoogleApiClientManager.setGeofencePendingIntent(pendingIntent);
    return pendingIntent;

As I've already said, everything work perfectly while running in foreground, but as soon as the app moves to background the geofence event stop being sent to receiver.

ADDITIONAL INFOS (not related to broadcast receiver issue): I tried to do the following:

  • I start the map fragment and the geofence is working fine, so the app show a notification
  • I move to home screen so the app move to Pause state and no notification is no longer received
  • I move back to the app checking that location update and google api client are still working, and they actually work
  • Finally geofencing is not working anymore

Hope that everything is clear and that someone of you can help me. Thanks in advance

1 Answers
Related