Location / Uncategorized

LocationServices

Many apps offer functionality based upon the location of the device running the app. The tools for obtaining device location have been around since API 1, but they have evolved a little over the years – one big change was moving them in to Play Services. However, this change came with a cost: Establishing a GoogleApiClient instance is a potentially blocking operation which you really do not want to be doing on the main thread. This usually requires some kind of asynchronous operation to obtain that instance and initialise the connection. This requires a chunk of extra code and introduces complexity which can easily introduce bugs. But things have become a whole lot easier, and in this article we’ll look at the new LocationServices APIs to see how to use them, but also check out the performance impact we can expect.

The process of obtaining device location really has been vastly simplified. For those already familiar with the APIs they are pretty much the same as before, only with much of the boilerplate removed. To use the new APIs requires Play Services V11.0.0 or later.

For our example, we’re going to register for location updates from the Fused Location Provider within an Activity. If you can understand this example then hopefully doing the same for other location types (such as Geofencing) will be easy to work out. Also, you may need to approach things slightly differently if you’re doing this within a Service.

I won’t bother covering the Activity class which is mainly concerned with obtaining the necessary location permissions – it is the LocationFragment where all of the interesting stuff is happening (in the context of this article, at least). LocationFragment will not be created until all of the necessary permissions have been obtained, so we do not have any need for permission checks in the Fragment itself.

The majority of LocationFragment is concerned with initialising the UI, and updating the values of the TextView instances in the layout:

The bit that is actually concerned with the location is actually pretty small:

There’s not actually that much to explain here, but we’ll go through it in detail nonetheless. The major change in the API is what’s done in registerForLocationUpdates(). Previously we would have had to obtain a GoogleApiClient instance which would have involved implementing a callback interface to handle the asynchronous connection to Play Services. That is a thing of the past, as the new mechanism is just much cleaner and easier to implement.

First we need to obtain a FusedLocationProviderClient instance which we do using LocationServices.getFusedLocationProviderClient(getActivity()). We can then register for location updates from this instance.

The big difference here is that previously we would have to establish a connection to Play Services before we could register for updates. Now we can get a FusedLocationProviderClient instance quite cheaply, without having to first connect to Play Services. When we register for updates, fusedLocationProviderClient will make the connection to Play Services in the background, and we’ll start receiving location updates once that connection has been established, and we’ll start receiving callbacks to onLocationResult() once that has all been done.

So that certainly makes life easier for us as developers, but what is the cost? To benchmark things I have used Hugo, Jake Wharton’s method call logging library. By wrapping all of the calls in simple methods, and annotating those methods with @DebugLog we can see the time take to execute each:

So we can see that the getFusedLocationProviderClient is taking 30ms, and registerForLocationUpdates is taking another 23ms. We wouldn’t want to be making these calls during an animation because we would start dropping frames, but doing this on the main thread during Fragment initialisation is giving us no danger of ANRs.

It takes another 288ms before we receive a location update, but we are not waiting on the main thread for this – we get an async callback with the location update, so this is not going to impact us.

For completeness in production code I would add some additional checking to verify that things are all working correctly, and report an error if they’re not, but I’ve omitted that in order to keep the example code clean and easy to understand. To do this I would also implement the onLocationAvailability() method of LocationCallback which will provide updates when the availability of location data changes.

There will be some developers cringing at this example code because they use different location providers for different build variants (for example, for builds which cannot use Play Services). LocationFragment is tightly coupled to Play Services in order to demonstrate these new Play Services API changes. However, a future article will look at ways of abstracting our code so that we can easily plug in different location providers.

The source code for this article is available here.

© 2017, Mark Allison. All rights reserved.

CC BY-NC-SA 4.0 LocationServices by Styling Android is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Permissions beyond the scope of this license may be available at http://blog.stylingandroid.com/license-information.

5 Comments

  1. Hey, Mark – great work – can you share your approach on real services, like background services using Location services? There will be huge changes to policy for such a services, so it would be good to share some thoughts on that…

    1. It will be pretty much the same in those cases. For example FusedLocationProviderClient has two variants of the getFusedProviderClient() method. The first takes an Activity as an argument, but the second takes a Context. Just use the second form in your Service implementation (Service extends Context). Then use it in exactly the same way.

  2. Hey, Mark. I have implemented Location service using new Location APIs. It seems that there is no method that takes LocationListener, so I use LocationCallback (like in your example). But it only triggers 2 times after launching. I have even tried using PendingIntent approach, but get the same.

  3. fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
    I have called this in onCreate(), but it returns null? Is there anything I need to call before this?
    Or some other code is required if this returns null?

    1. Are you sure that it isn’t getActivity() which is returning null? In my code I do this in onStart() because the Fragment is fully attached to the Activity by that point in its lifecycle.

Leave a Reply

Your email address will not be published. Required fields are marked *