Search code examples
androidandroid-geofence

Why geoEvent returns a list instead of single GeoFence


I have implemented GeoFence in my project. When geoFence event occur. It returns a GeoEvent object which has a method name getTriggeringGeofences (Returns a list of geofences that triggered this geofence transition alert.).

Why it is returning a list instead of single geoFence?

GeofenceReceiver.java

    public class GeofenceReceiver extends BroadcastReceiver {

    public static final String TAG = GeofenceReceiver.class.getSimpleName();
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {

        mContext = context;
        GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);

        Location triggredLocation = geoEvent.getTriggeringLocation();

        if (geoEvent.hasError()) {
            Log.d(TAG, "Error GeofenceReceiver.onHandleIntent");
        } else {
            Log.d(TAG, "GeofenceReceiver : Transition -> "
                    + geoEvent.getGeofenceTransition());

            int transitionType = geoEvent.getGeofenceTransition();

            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER
                    || transitionType == Geofence.GEOFENCE_TRANSITION_DWELL
                    || transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
                //why it is a list of GeoFence
                List<Geofence> triggerList = geoEvent.getTriggeringGeofences();
            }
        }
    }
}

Solution

  • Typically geofences are used as a power efficient way of knowing when a device enters or leaves a region. On mobile devices, this is accomplished by polling for network locations occasionally, meaning you can travel a some distance into/away from the geofence before it triggers.

    With that in mind, consider this Venn diagram.

    Geofence

    Consider the top of the image as North. If you come in from the West into Geofence "A", you'll most likely trigger the ENTER only at that geofence. Same if you come from the East. However, if you were to come from the North or South between "A" and "B", you'll be inside of both geofences. At this point, you have triggered the ENTER event on both, so instead of calling your receiver twice in a row, it'll just give you the list of geofences that were triggered with this event, at which point you should iterate through them and perform whatever action is needed for the event on each geofence.

    Looking at the docs, it seems that the broadcasts are separated by triggering events, meaning each broadcast will either be ENTER, EXIT, or DWELL events, so if you EXIT "B" and ENTER "A", you should get two different broadcasts, each with a list of 1 geofence.