Using the GPS in an Android App

August 14, 2014

Accessing and getting an Android device’s current location has a few important steps.

Include the Google Play Services library

The LocationClient class from the Google Play Services library takes care of a lot of the meticulous work of detecting and managing the many ways that an Android device can determine its GPS location. This simplifies the work of the developer.

If you’re using Gradle to manage your project’s dependencies, add this to the “dependencies” block:

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

Now you can import all the needed location classes with:

import android.location.Location;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

Implementing the Location Callbacks in your Activity

Implement the following classes in the Activity (or Fragment) that you want to use location services:

public class LocationExampleActivity extends Activity
 implements
 ConnectionCallbacks,
 OnConnectionFailedListener,
 LocationListener {

This requires you to implement the following methods:

// for ConnectionCallbacks
 @Override
 public void onConnected(Bundle bundle) { }

 // for ConnectionCallbacks
 @Override
 public void onDisconnected() { }

 // for OnConnectionFailedListener
 @Override
 public void onConnectionFailed(ConnectionResult connectionResult) { }

 // for LocationListener
 @Override
 public void onLocationChanged(Location location) { }

LocationClient

LocationClient is the main mechanism to retrieve the device’s GPS location. Add and create a LocationClient and a LocationRequest.

private LocationClient locationClient;
 private LocationRequest locationRequest;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

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

 locationRequest = LocationRequest.create()
 .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
 .setInterval(1000)
 .setFastestInterval(1000);
 }

The LocationClient now uses our LocationExampleActivity for its listeners

The LocationRequest is how you define settings like how much positional accuracy you need versus how much power you want the GPS to draw, and at what frequency you want to query the GPS for your location.

(You may experience problems with your location not being acquired if you use a priority other than LocationRequest.PRIORITY_HIGH_ACCURACY, due to a bug.)

Connecting and Disconnecting

Initiate the connection to location services with:

@Override
 public void onStart() {
 super.onStart();

 locationClient.connect();
 }

 @Override
 public void onConnected(Bundle bundle) {
 Log.i(TAG, "locationClient connected");

 if (locationClient != null) {
 locationClient.requestLocationUpdates(locationRequest, this);
 }
 }

 @Override
 public void onDisconnected() {
 Log.i(TAG, "locationClient disconnected");
 }

 @Override
 public void onStop() {
 if (locationClient != null) {
 if (locationClient.isConnected()) {
 locationClient.removeLocationUpdates(this);
 locationClient.disconnect();
 }
 }

 super.onStop();
 }

Initiate the connection (in this case, in the Activity’s onStart() call). When onConnected() is called, you are clear to begin requesting the device’s location.

When the Activity is stopped and onStop() is called, we perform the clean up of location services by removing location updates and disconnecting from location services.

If location services are not available for a device

If a device does not have location services available, Google provides a way to prompt the user to go out and download Google Play Services.

public final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

 @Override
 public void onConnectionFailed(ConnectionResult connectionResult) {
 Log.i(TAG, "locationClient connection failed");

 if (connectionResult.hasResolution()) {
 try {
 connectionResult.startResolutionForResult(
 this,
 CONNECTION_FAILURE_RESOLUTION_REQUEST);
 } catch (IntentSender.SendIntentException e) {
 Log.e(TAG, "IntentSender.SendIntentException", e);
 }
 } else {
 Log.e(TAG, "connectionResult has no resolution");
 }
 }

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
 switch (requestCode) {
 case CONNECTION_FAILURE_RESOLUTION_REQUEST:
 switch (resultCode) {
 case Activity.RESULT_OK:
 locationClient.connect();
 break;
 }
 }
 }

Getting the device’s location

Finally, after all that setup, we can start receiving location updates.

@Override
 public void onLocationChanged(Location location) {
 Log.i(TAG, "Location updated: " + location.getLatitude() + ", " + location.getLongitude());

 // do something with the Location
 }

Now you can get the GPS latitude and longitude of the device’s current location.

A Github gist of the complete LocationExampleActivity.java can be found here.

Joseph Kreiser
Joseph Kreiser
Software Developer

Looking for more like this?

Sign up for our monthly newsletter to receive helpful articles, case studies, and stories from our team.

Application Architecture with SwiftUI
Development iOS

Application Architecture with SwiftUI

June 15, 2022

An overview of mobile application system architecture using SwiftUI

Read more
How we designed, built, and ran our first community Hackathon
Development

How we designed, built, and ran our first community Hackathon

January 16, 2025

Michigan Software Labs hosted its first Hackathon, inviting college students and early-career developers to tackle a fun, challenging problem. The event, planned meticulously over several months, included a custom-built backend, frontend tools, and a Unity3D simulator. This blog shares our planning process, lessons learned, and open-source code to inspire others.

Read more
Quickly Prototyping a Ktor HTTP API
Development Web

Quickly Prototyping a Ktor HTTP API

August 18, 2022

Whether it’s needing a quick REST API for a personal project, or quickly prototyping a mockup for a client, I like to look for web server frameworks that help me get up and running with minimal configuration and are easy to use. I recently converted a personal project’s API from an Express web server to a Ktor web server and it felt like a breeze. I’ll share below an example of what I found and how easy it is to get a Ktor server up and running.

Read more
View more articles