Fast & Simple Android Location Updates with Google Play services

James Montemagno

Starting an Android application that relies on device location can be overwhelming. The classic way of getting location is with Android’s core APIs, which have been around for a very long time and can be confusing to use. To simplify this process, we developed the Geolocator plugin, which enables developers to get the location from shared code on iOS, Android, and Windows from a single API. There are times when you may want or need full control over the API, however, and that’s where the new Google Play services location APIs come in. These APIs simplify location awareness with multiple sensors on the device to help determine the location of the user. This means that, when using these new APIs, querying for location updates is faster and more accurate and, with the most recent update (11.0.4), it’s never been easier to get started.

Getting Started

The first thing we need to do is ensure that our project is targeting Android 7.0 and has the latest Android Support Libraries installed.

The APIs we’ll be using are part of the brand new Google Play services Location 11.0.4 NuGet release, currently in pre-release. Simply check the pre-release option in NuGet, search for Xamarin.GooglePlayServices.Location, and install the package in your Android application:

In addition to the NuGet, we’ll also need to ensure that we have the location permission set in our AndroidManifest.

Gathering Location

Developers previously had to create a Google API Client, specify which APIs they wanted to use, connect to the service, and then make the API calls that they wanted to. This all changes in version 11 of the Location APIs, which have the ability to query for the current FusedLocationProviderClient and then start making calls. This client requires two parameters to get started:

  • LocationRequest: Settings for the location updates
  • LocationCallback: A class that will receive the callback when the location has been updated

Creating a Location Callback

Inside of our MainActivity, we can create an implementation of LocationCallback and create an event that can be subscribed to when a location result is published:

class MyLocationCallback : LocationCallback
{
	public EventHandler LocationUpdated;
	public override void OnLocationResult(LocationResult result)
	{
		base.OnLocationResult(result);
		LocationUpdated?.Invoke(this, result.LastLocation);
	}
}

We can also create an event handler inside of our MainActivity that we can subscribe and unsubscribe to when we want to receive events:

void OnLocationResult(object sender, Location location)
{
    //location.Latitude;
    //location.Longitude;
}

Requesting Location

With our location callback in place, it's time to get the current FusedLocationClient and create our request:

MyLocationCallback locationCallback;
FusedLocationProviderClient client;

async Task StartLocationUpdatesAsync()
{
    // Create a callback that will get the location updates
    if(locationCallback == null)
    {
        locationCallback = new MyLocationCallback();
        locationCallback.LocationUpdated += OnLocationResult;
    }

    // Get the current client
    if(client== null)
        client = LocationServices.GetFusedLocationProviderClient(this);
			
    try
    {
	//Create request and set intervals:
        //Interval: Desired interval for active location updates, it is inexact and you may not receive upates at all if no location servers are available
        //Fastest: Interval is exact and app will never receive updates faster than this value
        var locationRequest = new LocationRequest()
                                  .SetInterval(10000)
                                  .SetFastestInterval(5000)
                                  .SetPriority(LocationRequest.PriorityHighAccuracy);

        await client.RequestLocationUpdatesAsync(locationRequest, locationCallback);			
    }
    catch(Exception ex)
    {
        //Handle exception here if failed to register
    }
}

That's it! With these few lines of code, location updates will continue to stream in while your user has your application open.

Learn More

There are additional considerations to think about when using location services, such as handling situations where the user has turned off location, entering background states, and, of course, turning off location updates when they aren't needed. You can find a full sample addressing all of these factors, including handling permission, on my GitHub.

0 comments

Discussion is closed.

Feedback usabilla icon