Android Geofencing

Geofencing combines awareness of the user’s current location with awareness of the user’s proximity to locations that may be of interest. To mark a location of interest, you specify its latitude and longitude. To adjust the proximity for the location, you add a radius. The latitude, longitude, and radius define a geofence, creating a circular area, or fence, around the location of interest.

You can have multiple active geofences, with a limit of 100 per device user across all apps. For each geofence, you can ask Location Services to send you entrance and exit events, or you can specify a duration within the geofence area to wait, or dwell, before triggering an event. You can limit the duration of any geofence by specifying an expiration duration in milliseconds. After the geofence expires, Location Services automatically removes it.

Getting Started with GeoFencing :

Step 1: Add the permission.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Step 2: Setup GeoFencing in your activity. (here i used Dexter Library for permissions)

 private GeofencingClient geofencingClient;

    private void setupGioFencing() {

        geofencingClient = LocationServices.getGeofencingClient(this);


        Dexter.withActivity(this)
                .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        if (ActivityCompat.checkSelfPermission(DashboardActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        geofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
                                .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        showToast("GeoFence Added");
                                     

                                    }
                                })
                                .addOnFailureListener(DashboardActivity.this, new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        showToast("GeoFence Failed to add");
                                        e.printStackTrace();
                                       
                                    }
                                });
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {

                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

    }
    PendingIntent geofencePendingIntent;
    private PendingIntent getGeofencePendingIntent() {
        // Reuse the PendingIntent if we already have it.
        if (geofencePendingIntent != null) {
            return geofencePendingIntent;
        }
        Intent intent = new Intent(this, GeofenceReceiver.class);
        geofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.
                FLAG_UPDATE_CURRENT);
        return geofencePendingIntent;
    }

    private GeofencingRequest getGeofencingRequest() {

        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofence(new Geofence.Builder()
                // Set the request ID of the geofence. This is a string to identify this
                // geofence.
                .setRequestId(VARIABLE_REQUEST_ID)

                .setCircularRegion(
                        VARIABLE_LATITUDE,
                        VARIABLE_LONGITUDE,
VARIABLE_RADIUS)
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                        Geofence.GEOFENCE_TRANSITION_EXIT)
                .build());
        return builder.build();
    }

VARIABLE_REQUEST_ID (String), VARIABLE_LATITUDE (Float), VARIABLE_LONGITUDE (Float), VARIABLE_RADIUS (Float) are the values you must change as per your requirement

Step 3. Create broadcast receiver name ( GeofenceReceiver ) that calls when user enter/exit in particular area, that you defined

public class GeofenceReceiver extends BroadcastReceiver {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("GeofenceTag","reciever");

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            Log.d("GeofenceTag","error");

        } else {
            int transition = geofencingEvent.getGeofenceTransition();
            if (transition == Geofence.GEOFENCE_TRANSITION_ENTER){
                Log.d("GeofenceTag","User enter");
            }else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT){
                Log.d("GeofenceTag","exited");
            
            }
        }
    }
}

Step 4. Add broadcast receiver to Manifest.xml.

 <receiver android:name="com.testing.GeofenceReceiver" />

We are done!

Leave a Reply