Search code examples
androidtransitionandroid-geofence

remove triggered geofence after transition


I'm trying to remove a geofence after it has been entered in order to stop it re-triggering the enter transition. From a similar question I got this line which works well

LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient,getGeofencePendingIntent()).setResultCallback(this);

However it removes all of the geofences rather than just the one that has been triggered.

What do I need to do in order to select the proper ID to be removed?


Solution

  • You need to pass the same String used to build the Geofence.

    String geofenceId = "randomId";
    Geofence geofence = new Geofence.Builder()
        .setRequestId(geofenceId)
        ....
        .build();
    
    GeofencingRequest request = new GeofencingRequest.Builder()
        .addGeofence(geofence)
        ....
        .build();
    
    LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, request, pendingIntent);
    

    To remove the geofence, you can use

    List<String> geofencesToRemove = new ArrayList<>();
    geofencesToRemove.add(geofenceId);
    LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, geofencesToRemove);
    

    Or you can get the Geofence from the Intent you've received.

    GeofencingEvent event = GeofencingEvent.fromIntent( intent_you_got_from_geofence );
    List<Geofence> triggeredGeofences = event.getTriggeringGeofences();
    List<String> toRemove = new ArrayList<>();
    for (Geofence geofence : triggeredGeofences) {
        toRemove.add(geofence.getRequestId());
    }
    LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, toRemove);