I'm trying to get the current location of the user of the app every 2 seconds.
I already use a foreground service with notification (can record location when app is in background). But when the app enters doze mode it will continue to give 3 locations after the screen turns black. But will then stop giving me locations updates.
I'm using FusedLocationProviderClient
to get my current location.
I have a WakeLock
to keep the service running and this works. To test this I have a corourtine running and I can do println("test")
but when i want my location i get nothing.
fusedLocationProviderClient?.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, cancellationSource?.token)?
.addOnSuccessListener {
val loc = it
println("${loc.latitude},${loc.longitude}")
postNewLocation(loc)
}?.addOnCanceledListener {
println("cancel")
}
Just after I get my last location update I get this LocationEngineResult == null
.
Does anyone know what I'm doing wrong? Any help or tips would be great.
For context I'm using Android 11 with targetsdkversion 30.
I'm a beginner in kotlin and this is for a schoolproject i have to complete.
You cannot receive locations when the device is in doze mode. Quoting a comment by a Google representative on an issue on the Google issue tracker:
Reference
Note:
You may say that the Foreground Service should not be affected by doze mode. It is not. It is the location provider that is.
Update:
Doze mode is only activated "if a user leaves a device unplugged and stationary for a period of time, with the screen off". Thus if a device is stationary in one location there is no need to track location for that time period.
Don't know if Doze mode is your issue. Battery optimization is another issue. For certain phones, the location providers are disabled when battery optimization is turned on and the screen is turned off. You can check this behavior using
PowerManager.getLocationPowerSaveMode()
. The modes are:Also, certain phone vendors have created phones that do not comply with standard Android behaviour. Check this.