Android Location & GPS Explained
One of the most useful features of mobile apps is location awareness because users carry their phones with them almost everywhere! You’ll learn how to leverage this feature and use it in your apps.
If you want to jump straight to the example code:
1. Declare permissions
In your AndroidManifest.xml add the following permissions depending on your needs. The user can see these permissions in the Google Play store and settings.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Include only if you need precise location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />2. Request permission
Declaring permissions doesn’t mean that they’re granted. On Android, you’ll need to ask the user for location permission.
Precise
Additionally, from Android 12+, you’ll need to ask for both permissions, so they can choose whether they trust the app with coarse or precise location.
val preciseLocationLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions(),
) { permissions ->
when {
permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) -> {
// Precise location granted
}
permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false) -> {
// Coarse location granted
}
else -> {
// Declined
}
}
}Then you need to use the launcher as a callback, for example to a button:
Button(onClick = {
preciseLocationLauncher.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
)
)
}) {
Text(text = "Get PRECISE location")
}Upgrade to precise
If your app won’t work without a precise location and the user granted a coarse location you can request an upgrade by launching the permissions again because the user already granted coarse permission it’ll only show precise permission. You should also explain why your app needs that permission for good UX.
// No need to change the code, we already have COARSE
// so the app will ask for FINE only
preciseLocationLauncher.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
)
)Coarse
Here, you’re good to go with just coarse permission.
val coarseLocationLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { granted ->
if (granted) {
// Granted continue with the app
} else {
// Declined
}
}Similar to a precise location now you need a callback asking for permission:
Button(onClick = {
coarseLocationLauncher.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
}) {
Text(text = "Get COARSE location")
}3. Access the location
Once you’ve obtained location permission, you can access the location in a couple of ways:
a) One-time location request
Here you can get either:
getLastLocation()— gets location quickly and minimizes battery usage. However, it can be out of date if none of the apps used it recently.getCurrentLocation()—gets a fresh and more accurate location. However, it can lead to active location computation to occur, meaning you’ll get it after a delay.
Firstly, you’ll need to declare Google Play Location Service in your build.gradle.kts(:app). You can get the most recent version here.
dependencies {
implementation("com.google.android.gms:play-services-location:21.1.0")
}After syncing the project it’s time to get the location with FusedLocationClient
// Always check whether you've permission before asking for location
if (
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
// Ask for permission
return
}
val client = LocationServices.getFusedLocationProviderClient(context)
// Current location
client.lastLocation.addOnSuccessListener { location: Location? ->
// Handle location
}
// Last known location
client.getCurrentLocation(
Priority.PRIORITY_HIGH_ACCURACY,
// You can replace it with your required behaviour
object : CancellationToken() {
override fun onCanceledRequested(p0: OnTokenCanceledListener) =
CancellationTokenSource().token
override fun isCancellationRequested() = false
},
).addOnSuccessListener { location: Location? ->
// Handle location
}b) Periodical location requests
If your app helps the user find their way by driving, walking etc. or maybe track something such as a package you’ll need to update its location periodically.
Create request
Here you’ll need to build a request:
val request = LocationRequest.Builder(
/* Priority */ Priority.PRIORITY_HIGH_ACCURACY,
/* intervalMillis */ 100
).build()If you need more advanced settings then the interval and priority you need to set them before calling build method
Create callback
You’ll also need a LocationCallback that will return the necessary location information:
val callback = object : LocationCallback() {
override fun onLocationAvailability(availability: LocationAvailability) {
if (availability.isLocationAvailable) {
// Location available
} else {
// Handle location being unavailable
}
}
override fun onLocationResult(result: LocationResult) {
result.locations.forEach { location ->
// Update data using location
}
}
}Start location updates
Now use the configured LocationRequest and LocationCallback to get the necessary data:
client.requestLocationUpdates(
request,
callback,
Looper.getMainLooper(),
)Consider writing custom Looper , here Main Thread Looper is used for simplicity of the guide.
Stop updates
If you need to stop requesting the updates at some point you can use:
client.removeLocationUpdates(callback)Stop & Start updates based on lifecycle
Because we’re receiving the location information in Foreground you should stop and start it depending on Lifecycle. In the example below we’ll stop updates when the user leaves our screen.
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_STOP) {
client.removeLocationUpdates(callback)
}
if (event == Lifecycle.Event.ON_START) {
// resume location updates if necessary
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}Depending on your use case you might want to stop it when the user dismisses Notification etc.
Get Michal Ankiersztajn’s stories in your inbox
Join Medium for free to get updates from this writer.
Thanks for reading! Please clap and follow me for more Android tutorials.
If something is missing or you need deeper understanding check out this repo:
Based on:
Stackademic 🎓
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord
- Visit our other platforms: In Plain English | CoFeed | Venture | Cubed
- More content at Stackademic.com










