Search code examples
androidlocationandroid-geofencelocation-clientlocation-services

getTriggeringGeofences and getGeofenceTransition from LocationServices


I noticed that the LocationClient class has currently been deprecated. I was using it for a travel app. and I changed the logic to use LocationServices instead of LocationClient: https://developer.android.com/reference/com/google/android/gms/location/LocationServices.html

Now the problem is I can't get getTriggeringGeofences and getGeofenceTransition from LocationServices.Geofence, or the GoogleApiClient. How do I do that?

This is the code from my old BroadcastReceiver:

 int transitionType = LocationClient.getGeofenceTransition(intent);
    if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
        for (Geofence geofence : triggerList) {
            Log.i("", "geof: " + transitionType + " GPS zone " + geofence.getRequestId());
            if(geofence.getRequestId().contentEquals("1")) {
                Utils.appendLog("GEOFENCE: exited current position GPS Zone");
                MyApp.getInstance().disableGeofence();
                addLoc();
            }
        }
    }else if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER){
        List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
        for (Geofence geofence : triggerList) {
            Log.i("", "geof: " + transitionType + " GPS zone " + geofence.getRequestId());
            if(geofence.getRequestId().contentEquals("2")) {
                Utils.appendLog("GEOFENCE: entered destination position GPS Zone");
                MyApp.getInstance().disableGeofence();
            }
        }
    }else{
        Log.e("", "Geofence transition error: " + transitionType);
    }

Solution

  • GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);  
    

    And then you can use those methods to retrieve the transition and the triggering geofences:

    int transition = geofencingEvent.getGeofenceTransition();
    List<Geofence> geofenceList = geofencingEvent.getTriggeringGeofences();