I use Geofences in my app, everything works fine except the removal of triggered geofences. I red the guide from the official documentation of Android but they don't explain how to remove a geofence inside of the IntentService.
Here is the code of the event handler of the service:
@Override
protected void onHandleIntent(Intent intent) 
{
    Log.e("GeofenceIntentService", "Location handled");
    if (LocationClient.hasError(intent)) 
    {
        int errorCode = LocationClient.getErrorCode(intent);
        Log.e("GeofenceIntentService", "Location Services error: " + Integer.toString(errorCode));
    } 
    else 
    {
        int transitionType = LocationClient.getGeofenceTransition(intent);
        if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER)
        {
            List <Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
            String[] triggerIds = new String[triggerList.size()];
            for (int i = 0; i < triggerIds.length; i++) 
            {
                // Store the Id of each geofence
                triggerIds[i] = triggerList.get(i).getRequestId();
                Picture p = PicturesManager.getById(triggerIds[i], getApplicationContext());
                   /* ... do a lot of work here ... */
            }
        } 
        else 
            Log.e("ReceiveTransitionsIntentService", "Geofence transition error: " + Integer.toString(transitionType));
    }
}
How can I delete the geofence after he got triggered ?
You can do something like this:
LocationServices.GeofencingApi.removeGeofences(
           mGoogleApiClient,
           // This is the same pending intent that was used in addGeofences().
           getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
And your getGeofencePendingIntent() method can look like this:
/**
 * 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() {
    Log.d(TAG, "getGeofencePendingIntent()");
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(mContext, GeofenceIntentServiceStub.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    mGeofencePendingIntent = PendingIntent.getService(mContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With