Location services, geofencing, and activity recognition with modern APIs.
Location Overview
# Dependencies
implementation("com.google.android.gms:play-services-location:21.0.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")Permissions
<!-- Manifest -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- For geofencing -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />// Runtime permissions
class LocationPermissionHandler(
private val activity: ComponentActivity
) {
private val locationPermissionLauncher = activity.registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
val fineGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true
val coarseGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true
val backgroundGranted = permissions[Manifest.permission.ACCESS_BACKGROUND_LOCATION] == true
if (fineGranted || coarseGranted) {
startLocationUpdates()
if (backgroundGranted) startGeofencing()
}
}
fun requestPermissions() {
val permissions = mutableListOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}
locationPermissionLauncher.launch(permissions.toTypedArray())
}
}FusedLocationProviderClient
class LocationRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
private val settingsClient = LocationServices.getSettingsClient(context)
// Get last known location
suspend fun getLastLocation(): Result<Location> {
return try {
val location = fusedLocationClient.lastLocation.await()
location?.let { Result.Success(it) }
?: Result.Failure(Exception("No last location"))
} catch (e: Exception) {
Result.Failure(e)
}
}
// Request location updates
fun requestLocationUpdates(
callback: (Location) -> Unit,
interval: Long = 10000,
priority: Int = Priority.PRIORITY_HIGH_ACCURACY
): LocationCallback {
val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, interval)
.setWaitForAccurateLocation(true)
.setMinUpdateIntervalMillis(5000)
.setMaxUpdateDelayMillis(30000)
.build()
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult.lastLocation?.let(callback)
}
}
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
return locationCallback
}
fun removeLocationUpdates(callback: LocationCallback) {
fusedLocationClient.removeLocationUpdates(callback)
}
// Get current location with timeout
suspend fun getCurrentLocation(timeoutMs: Long = 10000): Result<Location> {
return try {
val locationRequest = LocationRequest.Builder(
Priority.PRIORITY_HIGH_ACCURACY, 0
).build()
val location = withTimeout(timeoutMs) {
fusedLocationClient.getCurrentLocation(
Priority.PRIORITY_HIGH_ACCURACY,
CancellationTokenSource().token
).await()
}
location?.let { Result.Success(it) }
?: Result.Failure(Exception("Location unavailable"))
} catch (e: Exception) {
Result.Failure(e)
}
}
// Location settings check
suspend fun checkLocationSettings(): Result<LocationSettingsResponse> {
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10000).build()
)
.setAlwaysShow(true)
return try {
val response = settingsClient.checkLocationSettings(builder.build()).await()
Result.Success(response)
} catch (e: ResolvableApiException) {
// Show dialog to enable location
Result.Failure(e)
} catch (e: Exception) {
Result.Failure(e)
}
}
}Geofencing
class GeofenceRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
private val geofencingClient = LocationServices.getGeofencingClient(context)
// Create geofence
fun createGeofence(
id: String,
latitude: Double,
longitude: Double,
radius: Float,
expiration: Long = Geofence.NEVER_EXPIRE,
transitionTypes: Int = Geofence.GEOFENCE_TRANSITION_ENTER or
Geofence.GEOFENCE_TRANSITION_EXIT or
Geofence.GEOFENCE_TRANSITION_DWELL
): Geofence {
return Geofence.Builder()
.setRequestId(id)
.setCircularRegion(latitude, longitude, radius)
.setExpirationDuration(expiration)
.setTransitionTypes(transitionTypes)
.setLoiteringDelay(30000) // 30 seconds for DWELL
.build()
}
// Add geofences
suspend fun addGeofences(geofences: List<Geofence>, pendingIntent: PendingIntent): Result<Unit> {
val request = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofences(geofences)
.build()
return try {
geofencingClient.addGeofences(request, pendingIntent).await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
// Remove geofences
suspend fun removeGeofences(ids: List<String>): Result<Unit> {
return try {
geofencingClient.removeGeofences(ids).await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
suspend fun removeGeofences(pendingIntent: PendingIntent): Result<Unit> {
return try {
geofencingClient.removeGeofences(pendingIntent).await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
}
// Geofence BroadcastReceiver
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
?: return
if (geofencingEvent.hasError()) {
Log.e("Geofence", "Error: ${geofencingEvent.errorCode}")
return
}
val transition = geofencingEvent.geofenceTransition
val geofences = geofencingEvent.triggeringGeofences
for (geofence in geofences) {
val requestId = geofence.requestId
when (transition) {
Geofence.GEOFENCE_TRANSITION_ENTER -> {
handleEnter(context, requestId)
}
Geofence.GEOFENCE_TRANSITION_EXIT -> {
handleExit(context, requestId)
}
Geofence.GEOFENCE_TRANSITION_DWELL -> {
handleDwell(context, requestId)
}
}
}
}
private fun handleEnter(context: Context, placeId: String) {
// Show notification, log analytics, etc.
NotificationManagerCompat.from(context).notify(
placeId.hashCode(),
createNotification(context, "Entered $placeId", "Welcome!")
)
}
private fun handleExit(context: Context, placeId: String) {
NotificationManagerCompat.from(context).notify(
placeId.hashCode(),
createNotification(context, "Exited $placeId", "Goodbye!")
)
}
private fun handleDwell(context: Context, placeId: String) {
// User stayed in area
}
private fun createNotification(context: Context, title: String, body: String): Notification {
return NotificationCompat.Builder(context, "geofence_channel")
.setSmallIcon(R.drawable.ic_location)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.build()
}
}
// PendingIntent for geofence transitions
fun getGeofencePendingIntent(context: Context): PendingIntent {
val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
return PendingIntent.getBroadcast(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}Geofencing with WorkManager (Background)
class GeofenceWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val geofenceRepository: GeofenceRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val geofenceIds = inputData.getStringArray("geofence_ids")?.toList() ?: emptyList()
val action = inputData.getString("action") ?: "add"
return try {
val pendingIntent = getGeofencePendingIntent(applicationContext)
when (action) {
"add" -> {
val geofences = geofenceIds.map { id ->
// Fetch geofence details from DB
getGeofenceDetails(id)
}.filterNotNull()
geofenceRepository.addGeofences(geofences, pendingIntent)
}
"remove" -> {
geofenceRepository.removeGeofences(geofenceIds)
}
}
Result.success()
} catch (e: Exception) {
Result.retry()
}
}
}Activity Recognition
class ActivityRecognitionRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
private val activityRecognitionClient = ActivityRecognition.getClient(context)
// Request activity updates
suspend fun requestActivityUpdates(
pendingIntent: PendingIntent,
interval: Long = 10000
): Result<Unit> {
return try {
val task = activityRecognitionClient.requestActivityUpdates(
interval, pendingIntent
)
task.await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
// Remove activity updates
suspend fun removeActivityUpdates(pendingIntent: PendingIntent): Result<Unit> {
return try {
activityRecognitionClient.removeActivityUpdates(pendingIntent).await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
// Get current activity (deprecated, use updates)
@Suppress("DEPRECATION")
suspend fun getCurrentActivity(): Result<DetectedActivity> {
return try {
val task = activityRecognitionClient.activityRecognitionResult
val result = task.await()
result?.probableActivities?.maxByOrNull { it.confidence }?.let {
Result.Success(it)
} ?: Result.Failure(Exception("No activity detected"))
} catch (e: Exception) {
Result.Failure(e)
}
}
}
// Activity transition detection (enter/exit vehicle, start/stop walking)
class ActivityTransitionRepository @Inject constructor(
@ApplicationContext private val context: Context
) {
private val activityRecognitionClient = ActivityRecognition.getClient(context)
suspend fun requestActivityTransitions(
transitions: List<ActivityTransition>,
pendingIntent: PendingIntent
): Result<Unit> {
val request = ActivityTransitionRequest(transitions)
return try {
activityRecognitionClient.requestActivityTransitionUpdates(request, pendingIntent).await()
Result.Success(Unit)
} catch (e: Exception) {
Result.Failure(e)
}
}
fun createTransitions(): List<ActivityTransition> {
return listOf(
// Vehicle transitions
ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build(),
ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build(),
// Walking transitions
ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build(),
ActivityTransition.Builder()
.setActivityType(DetectedActivity.WALKING)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build(),
// Still
ActivityTransition.Builder()
.setActivityType(DetectedActivity.STILL)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build(),
)
}
}
// BroadcastReceiver for activity updates
class ActivityRecognitionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
val result = ActivityRecognitionResult.extractResult(intent)
val probableActivities = result.probableActivities
for (activity in probableActivities) {
Log.d("Activity", "${activity.type} - ${activity.confidence}%")
if (activity.confidence >= 75) {
handleActivity(activity.type)
}
}
}
}
private fun handleActivity(type: Int) {
when (type) {
DetectedActivity.IN_VEHICLE -> { /* Driving mode */ }
DetectedActivity.WALKING -> { /* Step counting */ }
DetectedActivity.RUNNING -> { /* Fitness tracking */ }
DetectedActivity.STILL -> { /* Idle */ }
DetectedActivity.ON_BICYCLE -> { /* Cycling */ }
DetectedActivity.TILTING -> { /* Phone movement */ }
}
}
}Location in Compose
@Composable
fun LocationMapScreen(
viewModel: LocationViewModel = hiltViewModel()
) {
val location by viewModel.currentLocation.collectAsStateWithLifecycle()
val permissionState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
LaunchedEffect(permissionState) {
if (permissionState.isGranted) {
viewModel.startLocationUpdates()
}
}
Column(modifier = Modifier.fillMaxSize()) {
// Permission button
if (!permissionState.isGranted) {
Button(
onClick = { permissionState.launchPermissionRequest() },
modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
Text("Grant Location Permission")
}
}
// Map or location display
location?.let { loc ->
Text(
text = "Lat: ${loc.latitude}, Lng: ${loc.longitude}",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(16.dp)
)
// Google Maps Compose
GoogleMap(
modifier = Modifier.fillMaxSize(),
cameraPositionState = rememberCameraPositionState {
position = CameraPosition.fromLatLngZoom(
LatLng(loc.latitude, loc.longitude), 15f
)
}
) {
Marker(
state = rememberMarkerState(
position = LatLng(loc.latitude, loc.longitude),
title = "Current Location"
)
)
}
}
}
}Battery Optimization
// Request location efficiently
fun createEfficientLocationRequest(): LocationRequest {
return LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY, 30000)
.setMinUpdateIntervalMillis(15000)
.setMaxUpdateDelayMillis(60000)
.setWaitForAccurateLocation(false)
.build()
}
// Use passive location updates (from other apps)
fun requestPassiveUpdates(callback: LocationCallback) {
val request = LocationRequest.Builder(Priority.PRIORITY_PASSIVE, 0).build()
fusedLocationClient.requestLocationUpdates(request, callback, Looper.getMainLooper())
}
// Batch location updates (for background)
fun requestBatchedUpdates(callback: LocationCallback) {
val request = LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY, 60000)
.setMaxUpdateDelayMillis(300000) // Batch every 5 minutes
.build()
fusedLocationClient.requestLocationUpdates(request, callback, Looper.getMainLooper())
}Try It
Add Play Services Location. Request permissions. Get last location. Start location updates. Create geofences. Handle geofence transitions. Detect activities.
# Add to build.gradle.kts:
# implementation("com.google.android.gms:play-services-location:21.0.1")Location mastery
- Request fine/coarse/background location permissions
- Get last known location and current location
- Start location updates with custom interval/priority
- Create and monitor geofences (enter/exit/dwell)
- Handle geofence transitions in BroadcastReceiver
- Request activity recognition updates
- Detect activity transitions (vehicle, walking, still)
- Optimize for battery with passive/batched updates
- Integrate with WorkManager for background geofencing
FusedLocationProviderClient for location. GeofencingClient for geofences (max 100). ActivityRecognition for activity detection. Request permissions at runtime. Use appropriate priority for battery efficiency. Handle background location on Android 10+.
Resources
- Location: https://developer.android.com/training/location
- Geofencing: https://developer.android.com/training/location/geofencing
- Activity Recognition: https://developer.android.com/training/location/activity-recognition
- Battery Optimization: https://developer.android.com/training/monitoring-device-state/location-battery