I'm using HandlerThread to listen for location updates.
private fun onCreate() {
...
locationClient = LocationServices.getFusedLocationProviderClient(this)
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
locationResult.lastLocation?.let { location ->
Log.d(TAG, "Location: ${location.latitude}, ${location.longitude}")
lat = location.latitude.toFloat()
lng = location.longitude.toFloat()
}
}
}
...
locationHandlerThread = HandlerThread("locationHandlerThread")
locationHandlerThread.start()
}
override fun onResume() {
super.onResume()
requestLocationUpdates()
}
private fun requestLocationUpdates() {
if (ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST_CODE
)
} else {
val locationRequest = LocationRequest.create().apply {
interval = INTERVAL // Set the interval to 5000 milliseconds (5 seconds)
fastestInterval = INTERVAL // Set the fastest interval to 5000 milliseconds (5 seconds)
priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
}
locationClient.requestLocationUpdates(locationRequest, locationCallback, locationHandlerThread.looper)
}
}
override fun onDestroy() {
super.onDestroy()
locationHandlerThread.quit()
}
The code works as expected while on foreground but when the app is switched to background the locationHandlerThread is in running status(from debugger) but doesn't seem to execute the locationCallback.
If I understand correctly, the locationCallback should execute even while the app is in background, right?