Android Core

Android: location based services

Introduction

Developing applications for mobile devices gives us a lot more opportunities for context based information than a traditional web application. One of the inputs for context sensitive information is the users current location. This post describes several ways an Android application can obtain the users current location.

Location API’s

In previous versions of the Android SDK you had to manually implement a location service which abstracts away the underlying location providers (GPS or cellular based). This was not ideal since as a developer of an application, you probably are not concerned about the implementation details of obtaining a users location.

Fortunately Google’s Location API’s provide a much better way for working with location data. The Location API’s provide the following functionality:

  • Fused location provider which abstracts away the underlying location providers.
  • Geofencing. Lets your application setup geographic boundaries around specific locations and then receive notifications when the user enters or leaves those areas.
  • Activity recognition. Is the user walking or in a car.

Check for Google play services

Working with the Location API’s require the presence of the Google Play Services application on the device. It is good practice to test for the presence of Google play services before using the API. This can be done with the following code:

protected boolean testPlayServices() {
        int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
            // google play services is missing!!!!
            /*
             * Returns status code indicating whether there was an error.
             * Can be one of following in ConnectionResult: SUCCESS, SERVICE_MISSING,
             * SERVICE_VERSION_UPDATE_REQUIRED, SERVICE_DISABLED, SERVICE_INVALID.
             */
            GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, getActivity(), 1122).show();
            return false;
        }
        return true;
    }

Code listing 1

Code listing 1 shows how to check for the presence of Google play services. If the Google play services are not present a dialog is displayed giving the user the opportunity to download and install the Google play services application. This method returns false if the services are not found and can be placed around any code requiring Play services.

Obtaining the users location

The primary class for using the Location API’s is the LocationClient. The first thing to do is instantiating the LocationClient and passing the required listeners. See the following code which is usually called from the onCreate from within an activity or onActivityCreated if the LocationClient is instantiated within a fragment.

locationClient = new LocationClient(getActivity(), this, this);

The parameters are:

  1. The Context
  2. ConnectionCallbacks. Defines the onConnected() and onDisconnected() methods.
  3. OnConnectionFailedListener. Defines the onConnectionFailed() method.

When the LocationClient is instantiated, the next thing to do is calling the connect() method of the LocationClient. This is typically done in the onResume method. In the inPause method the disconnect() method is called of the LocationClient. This ensures the LocationClient is only active when the activity is running. Should you need constant tracking of the users location when the app is in the background, it is better to create a background service for this.

When the connect() method is successful, the onConnected() callback is called. In this method you can obtain the users last known location using the following method:

locationClient.getLasLocation();

Periodic location updates

Registering for periodic location updates involves slightly more work. The first thing to do is creating a new LocationRequest object. This object specifies the quality of service for receiving location updates. The following code demonstrates this:

private static LocationRequest createLocationRequest() {
        final LocationRequest locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // The rate at which the application actively requests location updates.
        locationRequest.setInterval(60 * MILLISECONDS_IN_SECOND);
        // The fastest rate at which the application receives location updates, for example when another
        // application has requested a location update, this application also receives that event.
        locationRequest.setFastestInterval(10 * MILLISECONDS_IN_SECOND);
        return locationRequest;
    }

After the LocationRequest is created and the connect() method of the LocationClient is successful, the onConnected method is called. In this method the LocationClient is instructed to send periodic location updates to the application using the following code:

locationClient.requestLocationUpdates(locationRequest, this);

The parameters are:

  • locationRequest. Specifies the quality of services of the location updates.
  • LocationListener. Defines several callback methods including the onLocationChanged which is called when a new location is available.

Required dependencies

To use the Google play services in your application you have to define the correct dependencies in the build.gradle. There are two versions of the API: one for Android 2.3. and higher and one for Android 2.2.

Use the SDK manager to install the required packages. For Android 2.3 these are:

  • Google play services
  • Google repository

For Android 2.2 these are:

  • Google play services for Froyo
  • Google repository

So if your applications targets Android 2.2 you must use the Google play services for Froyo library. In your build.gradle specify the following dependency:

For Android 2.3:

dependencies {
    compile 'com.google.android.gms:play-services:4.0.30'
}

For Android 2.2:

dependencies {
    compile 'com.google.android.gms:play-services:3.2.65'
}

Testing with mock locations

To test with mock locations you have to do the following:

  1. Enable mock locations in the developer options.
  2. Download the sample LocationProvider example app: http://developer.android.com/training/location/location-testing.html
  3. Modify the LocationUtils class with an array of locations you want to test with.
  4. Install the LocationProvider sample app on your device.
  5. Start the LocationProvider sample app.
  6. Start the application you want to test the location functionality for.

A handy website to get the latitude and longitude of an address for testing purposes is: http://www.itouchmap.com/latlong.html

Conclusion

Working with location data in your mobile application can add a new dimension to the user experience. This article explains the steps needed to use the Google Location API’s for obtaining the users current location.
 

Reference: Android: location based services from our JCG partner Jamie Craane at the Jamie Craane’s Blog blog.

Jamie Craane

Jamie develops software professionally since 2001 for a variety of small and large organizations. Assignments vary from the development of mobile and web applications to software architecture. He watches and studies new technology closely to find out how this can be applied in software solutions. The ultimate goal is to realize a solution that really matters. Besides developing software, Jamie gives presentations and training on a regular basis on various subjects and technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button