Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Everything you wanted to know about Geofences in Google App Development

4.27/5 (7 votes)
16 Nov 2014CPOL5 min read 20.7K  
Geofences in Google App Development

No pretence, developing out-of-the-box apps for Google's Android is most definitely a sweat-soaked exercise. The novice as well as the more seasoned app developers have invested considerable number of hours to build apps that can cater to the diverse needs of Google Play Service users. If you happen to be a Google app developer looking to developing a brilliant navigation app, Geofencing is a concept that can help you with the same on an immediate basis. Let's dig deeper into the concept.

Geofences- What are they exactly?

Well, Geofences are basically virtual regions that are considered around geo point with a specific radius. The term 'geo point' refers to a real place like a restaurant, a store, a school etc. and the circular area of that particular place represents the radius of the geo fence. With location-based mobile apps becoming the focal point in the realm of mobile app development, Geofences/geo regions have served as an icing on the cake.

Geofencing-based Android app- How to use it?

Since geofencing combines the awareness of user's current location with all the nearly locations of interest, Android apps built on this concept serve as best tools for finding locations that can cater to varied needs of someone who loves exploring destinations. For using a Geofencing app, all you need to do is simply mark a location of interest by specifying its latitude and longitude. Further, choose to adjust the proximity for the marked location by adding a radius. All the three parameters viz: latitude, longitude and radius define a geofence. You are free to have multiple geofences simultaneously, thereby expanding your search for best locations that suit your travel taste.

You Need to be Sure if Google Play Service is Available

And there is a simple enough code to check it:

Java
private boolean servicesConnected() {
  // Verifying the availability of Google Play services
  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

  // If Google Play services is available
  if (ConnectionResult.SUCCESS == resultCode) {
    // In debug mode, log the status
    Log.d("Geofence Detection", "You can Use Google Play services.");
    
    // Continue
    return true;
  
    //Google Play services isn't available
  } else {
  // Fetch the error code
  int errorCode = connectionResult.getErrorCode();
  
  // Get the error dialog from Google Play services
  Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST);

  // If Google Play services can provide an error dialog
  if (errorDialog != null) {
    ErrorDialogFragment errorFragment = new ErrorDialogFragment();
     errorFragment.setDialog(errorDialog);
     errorFragment.show( getSupportFragmentManager(),"Geofence Detection");
  }

Geofence object- What all does it include?

As a Google app developer, once you're done with requesting or checking the Google Play Services, you can start off with creating the geo fences. Each Geo fence object includes the following parameters:

  • Latitude, longitude and radius

While the latitude and longitude is used for marking a location of interest, radius is utilized for adjusting the distance as to how close the user needs to approach the location prior to detection of the geofence. Greater the value of this radius, greater are the chances for the user to trigger a geofence transition alert while reaching the geofence.

  • Transition Type

Location services built into the Android apps can easily detect when a user steps in within the radius of the geofence(“entry”) and when the user steps outside the radius of the geofence(“exit”) or both.

  • Geofence ID

This is a unique string that's stored with the geofence and used for removing a geofence from the Location Services tracking.

  • Expiration Time

This is the time duration for which the geofence would remain active. Once this duration has expired, the Location Services will automatically delete the geofence. As a developer, usually, you must specify geofence expiration time but you may even opt for maintaining permanent geofences that would serve useful for the customer's home or work place.

Defining Geofence Storage

It is mandatory for a geofencing app to read and write geofence data to persistent storage. As the app developer, you shouldn't use the Geofence objects for this, instead you must opt for effective storage techniques such as databases that would allow you to store groups of related data in a convenient way. You need to use a specific code snippet that defines two classes that use the app's SharedPreferences instance for seamless storage. While the class SimpleGeofence is analogous to a database record and stores the data for a single Geofence object, the class SimpleGeofenceStore reads and writes SimpleGeofence data to the SharedPreferences instance.

Creating Geofence objects

A different type of code snippet uses the SimpleGeofence and SimpleGeofenceStore classes to fetch geofence data from the UI. This code stores the geofence data in SimpleGeofence objects, followed by storing these objects in a SimpleGeofenceStore object and finally creating the Geofence objects.

Sending the Geofence monitoring request

In order to send a geofence monitoring request, you require two asynchronous operations. While the first operation fetches a location client for the request, the second one makes the request using the client. Under both the situations, the Location Services invokes a callback method after the operations have finished.

One of the finest methods of handling these operations is chaining the method calls. To implement the required callback interfaces, you need to modify the activity's class definition and for this you need to add the following interfaces:

  • ConnectionCallbacks - It specifies the methods that the Location Services calls as and when a location client is connected or disconnected
  • OnConnectionFailedListener - It specifies a method that the Location Services calls in case an error occurs while attempting to connect the location client.
  • OnAddGeofencesResultListener - It specifies a method that Location Services calls once it has added the geofences.

How Do We Monitor Using Geofences

Let's look at a piece of code that depict how app can monitor the geofences. We use getTansitionPendingIntent here and the pending intents you see here are defined with onConnect method. Here is the code for it:

Java
private void onConnected(Bundle dataBundle) {
  …

  switch (mRequestType) {
    case ADD :
      // Get the PendingIntent for the request
      mTransitionPendingIntent = getTransitionPendingIntent();
      mLocationClient.addGeofences(mCurrentGeofences, pendingIntent, this);

     …
  }
}

And when you decide to no longer monitor them, you simply got to remove them from the GeoFence storage:

Java
public void removeGeofences(PendingIntent requestIntent) {
  // Here we define the removal request
  mRequestType = REMOVE_INTENT;
  
  if (!servicesConnected()) {
    return;
  }

  // Store the PendingIntent
  mGeofenceRequestIntent = requestIntent;
  mLocationClient = new LocationClient(this, this, this);

  // If a request is not already underway
  if (!mInProgress) {
    // Indicate that a request is underway
    mInProgress = true;
    
    // Request a connection from the client to Location Services
    mLocationClient.connect();
  }
}

If experimentation is on your agenda, you can even choose to combine the geofencing with a variety of other location-based features including periodic updates etc. Doing this allows you to further your skills and your reach for delivering an Android app that truly stands out from the crowd.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)