With Google Play services' FusedLocationProviderClient, when do you use getCurrentLocation instead of requestLocationUpdates, and what does a LocationRequest's Priority change?
answer
- cached, fresh, or a stream
- lastLocation can be null
- remove what you request
- Priority hints which sources to use
basics
~20 sUse getCurrentLocation for one fresh fix and requestLocationUpdates only for a continuous stream, which you must stop with removeLocationUpdates. The LocationRequest's Priority tells the fused provider how much accuracy to trade for battery, from PRIORITY_HIGH_ACCURACY down to PRIORITY_PASSIVE.
solid answer
~40 s`FusedLocationProviderClient` gives three options. `lastLocation` is cached and cheap but can be stale or `null`. `getCurrentLocation()` computes one fresh fix and is Google's recommended way to get a current location. `requestLocationUpdates(request, callback, looper)` streams results to a `LocationCallback` until `removeLocationUpdates`, so it suits live tracking and wastes power if you forget to stop it. The `LocationRequest`, built with `LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10_000)`, sets the interval, the minimum update interval and the priority: high accuracy is more likely to use GPS, balanced aims for about 100 m, low power for about 10 km, and passive only receives fixes other apps caused. The one-shot calls return a `Task` whose listeners run on the main thread unless you pass an `Executor`.
code
kotlin · 33 linesclass CourierTracker(context: Context) {
private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
private val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10_000L)
.setMinUpdateIntervalMillis(5_000L)
.build()
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
result.lastLocation?.let(::showCourierPosition)
}
}
@SuppressLint("MissingPermission") // fine location is granted before this is called
fun startTracking() {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
}
fun stopTracking() {
fusedLocationClient.removeLocationUpdates(locationCallback)
}
@SuppressLint("MissingPermission")
fun locateCustomerOnce(cancellation: CancellationTokenSource) {
fusedLocationClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, cancellation.token)
.addOnSuccessListener { location -> location?.let(::showCustomerPin) }
.addOnFailureListener { error -> showLocationError(error) }
}
private fun showCourierPosition(location: Location) { /* move the courier marker */ }
private fun showCustomerPin(location: Location) { /* drop the customer pin */ }
private fun showLocationError(error: Exception) { /* explain and offer retry */ }
}go deeper
Recall the three calls, lastLocation, getCurrentLocation and requestLocationUpdates, and that the last one must be stopped with removeLocationUpdates.
Explain why lastLocation can be null, what each Priority constant trades, and how the interval and minimum update interval shape delivery.
Show production habits: one-shot fixes for one-shot needs, settings resolution through ResolvableApiException, listeners off the main thread, and tracking tied to the screen's lifecycle.
Weigh accuracy against battery per feature and set the team's default priorities, so live tracking is the exception and not the template.
## The client and the Task it returns `FusedLocationProviderClient` is the location entry point of Google Play services, obtained with `LocationServices.getFusedLocationProviderClient(context)` from `com.google.android.gms:play-services-location` (21.4.0 at the time of writing). The **fused** provider decides which sources to use, such as GPS, Wi-Fi or cell towers, from the high-level requirements you give it, and it manages battery use for you. Since 21.0.0 the client is an interface, which makes it easier to fake in tests. Its one-shot methods return a Play services **`Task`**: - `addOnSuccessListener`, `addOnFailureListener` and `addOnCompleteListener` attach callbacks. By default they run on the **main thread**, so keep them short or pass an `Executor`. - Passing an `Activity` as the first argument gives an **activity-scoped** listener, removed automatically in `onStop`. - In coroutines, `kotlinx-coroutines-play-services` adds `Task.await()`. - `Tasks.await(task)` blocks the calling thread; use it only on a background thread you manage. ## Three ways to get a location 1. **`getLastLocation()`** (the `lastLocation` property in Kotlin) returns the cached last known location. It is quick and cheap but can be stale if no app has asked for location recently. It can also be `null`: when location is turned off in settings (which clears the cache), when the device never recorded a location, or when Play services restarted and no client has requested location since. 2. **`getCurrentLocation()`** computes a **fresh fix** once. It can trigger active location computation on the device. Google calls it the recommended way to get a fresh location and safer than starting and managing updates yourself. 3. **`requestLocationUpdates(locationRequest, locationCallback, looper)`** delivers a stream of results to `LocationCallback.onLocationResult()` (or to a `PendingIntent`) until you call `removeLocationUpdates(locationCallback)`. Google warns that it can use a lot of power if location isn't available or the request isn't stopped correctly. | Need in the delivery app | Call | |---|---| | Pre-fill the customer's address field | `getLastLocation()`, then refine | | "Use my current location" button | `getCurrentLocation()` | | Courier's live position on the map | `requestLocationUpdates()` with a `LocationRequest` | ## What the LocationRequest and its Priority control Build the request with `LocationRequest.Builder(priority, intervalMillis)`. The builder became the preferred way to construct requests in 21.0.0, and the `Priority.PRIORITY_*` constants replaced the deprecated `LocationRequest.PRIORITY_*` ones in 20.0.0. - **Interval** (`setIntervalMillis`, or the builder argument): the rate you would like updates. Actual delivery can be faster or slower, or stop when nothing is available. - **Minimum update interval** (`setMinUpdateIntervalMillis`): the fastest rate you can handle; Google says you don't need it unless you benefit from updates faster than the interval. The library's `IMPLICIT_MIN_UPDATE_INTERVAL`, which derives the minimum from the interval, represents half of the requested interval since play-services-location 21.4.0. - **Priority**, a strong hint about which sources to use: - `PRIORITY_HIGH_ACCURACY`: the most precise location, more likely to use GPS. - `PRIORITY_BALANCED_POWER_ACCURACY`: about city-block accuracy (~100 m), likely Wi-Fi and cell positioning. - `PRIORITY_LOW_POWER`: about city-level accuracy (~10 km). - `PRIORITY_PASSIVE`: triggers no location work of its own and only receives locations other apps caused. Priority asks for accuracy; the **permission** you hold caps it. With only coarse location granted, high accuracy will not return a precise fix. Requesting that permission is a separate subject, covered with manifest permissions. ## When device settings block the request A request can be correct and still return nothing, because location is turned off in system settings. `LocationServices.getSettingsClient(context).checkLocationSettings(LocationSettingsRequest.Builder().addLocationRequest(request).build())` returns a `Task<LocationSettingsResponse>`. If it fails with a **`ResolvableApiException`**, call `startResolutionForResult` (or launch its resolution through an activity-result launcher) to show the one-tap dialog that turns the needed settings on. ## Lifecycle and background use - Tie a stream to the screen that shows it: Google's sample starts updates in `onResume` and calls `removeLocationUpdates` in `onPause`, saving a `requestingLocationUpdates` flag in `onSaveInstanceState` so a rotation restores the user's choice. - The `PendingIntent` form of `requestLocationUpdates` delivers results to a component instead of a callback, which suits work that outlives a screen. - Location used while the app is in the background should be critical to the app's core function and disclosed to the user; Google's guide calls this out explicitly. ## Mistakes to avoid - Treating `lastLocation` as "where the user is now" and never handling `null`. - Starting updates for a one-time need, then forgetting `removeLocationUpdates`. - Choosing `PRIORITY_HIGH_ACCURACY` for everything and draining the battery. - Doing network or disk work inside a main-thread `Task` listener.
- Your request is correct but no locations arrive because location is switched off on the phone; how do you let the user fix that in one tap?Build a `LocationSettingsRequest` containing your `LocationRequest` and pass it to `SettingsClient.checkLocationSettings()`. If the returned `Task` fails with a `ResolvableApiException`, call `startResolutionForResult` or launch its resolution through an activity-result launcher. That shows Google's dialog that turns on the required settings, and the result tells you whether the user accepted.
- Why can lastLocation be null even on a phone that had a fix yesterday?Turning location off in settings clears the cache, so the last known location disappears. It is also null on a device that never recorded a location, and after Google Play services restarts when no client has requested location since. Treat `lastLocation` as a hint and fall back to `getCurrentLocation()`.
- lastLocation always returns the user's current position and is never null.
- requestLocationUpdates is the right call for a single one-time location.
- PRIORITY_HIGH_ACCURACY guarantees a precise fix even when only coarse location is granted.
- PRIORITY_PASSIVE starts its own low-power location requests in the background.
- Task listeners from the fused provider run on a background thread by default.
Assumes play-services-location 21.4.0: Priority.PRIORITY_* replaced LocationRequest.PRIORITY_* in 20.0.0, LocationRequest.Builder became preferred in 21.0.0, and 21.4.0 changed IMPLICIT_MIN_UPDATE_INTERVAL to represent half of the requested interval.