Android development
user location
Android location services
location tracking
mobile app development

Good way of getting the user's location in Android

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The best general-purpose way to get a user's location on Android is to use FusedLocationProviderClient from Google Play services. It combines GPS, Wi-Fi, cell data, and sensors behind one API, which gives better results and better battery behavior than managing providers yourself with the older LocationManager API.

The first design question is not "How do I start constant updates?" It is "Do I need one fresh location, a cached location, or continuous tracking?" Most apps only need a single location on demand, and Android now provides direct methods for that.

Choose the Right Location Call

Android's fused provider exposes a few different ways to retrieve location:

  • 'lastLocation is fast and power-efficient, but it may be stale or null.'
  • 'getCurrentLocation() requests a fresh location estimate and is the recommended choice when you need current data.'
  • 'requestLocationUpdates() is for ongoing tracking and should be used only when the product really needs continuous updates.'

If your app needs the user's position when they tap a button such as "Find nearby stores," getCurrentLocation() is usually the right call. If you only need a quick best-effort estimate and can tolerate older data, lastLocation is cheaper.

Request Permission First

Before calling the location API, request runtime permission. Start with the least precise permission your use case allows. Many apps only need approximate location.

kotlin
1private val requestPermissionLauncher =
2    registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
3        if (granted) {
4            fetchCurrentLocation()
5        } else {
6            println("Location permission denied")
7        }
8    }
9
10private fun ensureLocationPermission() {
11    val permission = Manifest.permission.ACCESS_FINE_LOCATION
12
13    if (ContextCompat.checkSelfPermission(this, permission) ==
14        PackageManager.PERMISSION_GRANTED
15    ) {
16        fetchCurrentLocation()
17    } else {
18        requestPermissionLauncher.launch(permission)
19    }
20}

That snippet is short, but it captures the important rule: never call the fused provider until permission is granted.

Get a Fresh Location with the Fused Provider

This example fetches a single fresh location:

kotlin
1import android.Manifest
2import android.content.pm.PackageManager
3import androidx.activity.result.contract.ActivityResultContracts
4import androidx.core.content.ContextCompat
5import com.google.android.gms.location.LocationServices
6import com.google.android.gms.location.Priority
7import com.google.android.gms.tasks.CancellationTokenSource
8
9private fun fetchCurrentLocation() {
10    val fusedClient = LocationServices.getFusedLocationProviderClient(this)
11    val cancellationTokenSource = CancellationTokenSource()
12
13    fusedClient.getCurrentLocation(
14        Priority.PRIORITY_HIGH_ACCURACY,
15        cancellationTokenSource.token
16    ).addOnSuccessListener { location ->
17        if (location != null) {
18            println("Lat: ${location.latitude}, Lng: ${location.longitude}")
19        } else {
20            println("Location unavailable")
21        }
22    }.addOnFailureListener { error ->
23        println("Failed to get location: ${error.message}")
24    }
25}

This is usually better than starting location updates and then trying to stop them manually after the first callback. It keeps the API surface smaller and reduces the chance of leaving a long-running request active by mistake.

Use lastLocation When Stale Data Is Acceptable

If you only need a quick estimate, you can check lastLocation first:

kotlin
1private fun fetchLastKnownLocation() {
2    val fusedClient = LocationServices.getFusedLocationProviderClient(this)
3
4    fusedClient.lastLocation.addOnSuccessListener { location ->
5        if (location != null) {
6            println("Cached location: ${location.latitude}, ${location.longitude}")
7        } else {
8            println("No cached location available")
9        }
10    }
11}

This is valuable for startup screens or non-critical map defaults, but do not assume it is always fresh. If accuracy matters for a real action, request the current location instead.

When Continuous Updates Make Sense

Use requestLocationUpdates() only for navigation, workout tracking, or other experiences that truly need continuous movement. Repeated updates consume more power, add lifecycle complexity, and require careful cleanup in onPause, onStop, or a foreground service depending on the use case.

For most apps, one-shot location retrieval is the correct default. Treat continuous tracking as a special case, not the baseline.

Common Pitfalls

  • Using LocationManager by default for new code. The fused provider is usually the better first choice.
  • Requesting precise location when approximate location would satisfy the feature.
  • Using lastLocation as if it were guaranteed to be fresh. It may be old or missing.
  • Starting continuous updates for a one-time lookup. That wastes battery and increases lifecycle bugs.
  • Ignoring null results. A location request can fail or return no estimate, especially indoors or on a cold start.

Summary

  • 'FusedLocationProviderClient is the standard choice for most Android location features.'
  • Use getCurrentLocation() for one fresh fix and lastLocation for a fast cached estimate.
  • Request runtime permission before touching the location APIs.
  • Prefer one-shot location requests over continuous updates unless tracking is truly required.
  • Good location code is as much about privacy and battery usage as it is about coordinates.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.