Geofencing

Prev Next

Overview

Geofencing in Android allows developers to trigger actions or send notifications when a user enters or exits a defined geographical area. This feature is ideal for location-based marketing, alerts, or contextual app behaviors.

Use Case

  1. Purpose:

    • Send location-specific notifications or perform actions based on user proximity to a geographical area.

    • Enhance user engagement with relevant, location-based content.

  2. Benefits:

    • Drive foot traffic to physical locations (e.g., stores, events).

    • Improve user experience by providing context-aware content or actions.

Implementation Details

  1. Permissions:

    • Add the required permissions to your AndroidManifest.xml:

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    • For Android 10 (API level 29) and above, ACCESS_BACKGROUND_LOCATION is mandatory.

  2. Setup Geofencing:

    • Define a Geofence object with required parameters:

      Geofence geofence = new Geofence.Builder()
          .setRequestId("GeofenceID")  // Unique ID for the geofence
          .setCircularRegion(latitude, longitude, radius)  // Location and radius
          .setExpirationDuration(Geofence.NEVER_EXPIRE)  // Duration the geofence is active
          .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
          .build();
  3. Add Geofence to the GeofencingClient:

    • Use the GeofencingClient to manage geofences:

      GeofencingClient geofencingClient = LocationServices.getGeofencingClient(this);
      
      geofencingClient.addGeofences(getGeofencingRequest(geofence), getGeofencePendingIntent())
          .addOnSuccessListener(() -> Log.d("Geofencing", "Geofence added successfully"))
          .addOnFailureListener(e -> Log.e("Geofencing", "Error adding geofence", e));
  4. Handle Geofence Events:

    • Create a BroadcastReceiver to handle geofence transitions:

      public class GeofenceBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
              if (geofencingEvent.hasError()) {
                  Log.e("Geofencing", "Error code: " + geofencingEvent.getErrorCode());
                  return;
              }
      
              int geofenceTransition = geofencingEvent.getGeofenceTransition();
              if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
                  Log.d("Geofencing", "Entered geofence");
              } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
                  Log.d("Geofencing", "Exited geofence");
              }
          }
      }

Keep in mind:

  • Ensure the app requests runtime permissions for location services, especially for Android 10+.

  • Test geofence transitions under various conditions to verify accuracy.

  • Avoid overlapping geofences to minimize conflicts and improve performance.