android location updates fused client playe services

How to get user location in Android

Android Play Services SDK offers Location API that is used to get gps location. Location updates is one of the most crucial feature of Android apps. We have seen in one of the earlier post on how to use Places API to auto complete address.  In this post we will see how to automatically track user location and how to get user consent to get location updates programatically.

Setup Location API

The first step before using location api is to add permission in AndroidManifest.xml and Location dependency in build.gradle.

Add location dependency in app’s build.gradle file and sync the project.

Add uses-permission in AndroidManifest.xml file to request location.

Last Known Location

Location API can be requested to get the last known location of the user. The accuracy of the location is based on the permission set in the app. For instance ACCESS_FINE_LOCATION gives a better accuracy than ACCESS_COARSE_LOCATION but requires users consent to allow app permission.

Let’s see how to use Fused Location Client to get last location.

Create Fused Location Provider instance as shown in the code below.

To get the last known location call getLastLocation() method that returns a task that can be used to retrieve location data as shown in the code method below. Before we request location updates we need to check if we have the permission to request location. It is essential to ask user to grant permission if the app is targeting SDK  Marshmallow 23 or above or if the device running is Android (6.0) or above.

Get User Location Changes Update

If the purpose of the app is to track user location changes continuously then we can request fused location client to provide location changes. Location updates are received in a callback that we define in LocationRequest.

Let’s create location request with parameters for location provider client.

Check location settings

In the above snippet we call checkLocationSettings method to check if the location settings are correct. If the user needs to turn on the gps then it resolves the activity to turn on location. The result is received in onActivityResult. If the result is ok then we can we can start location request update.

Location Update Callback

Define location callback which will be called by the fused client with location data based on the timer set in location settings parameters.

You can add this code to start receiving location updates.

Add ACCESS_FINE_LOCATION in AndroidManifest.xml since we are expecting high accuracy data in location.

Check if we have the permission to request location updates. If we have the permission call Fused Location Client requestLocationUpdates method with callback as the parameter to start receiving updated. Remember to remove the callback when updates are no more required. The optimal place to call removeLocationUpdates is onPause.



Leave a Reply