Android Kotlin : Getting location when app is in doze mode

1.5k views Asked by At

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.

1

There are 1 answers

3
Xid On BEST ANSWER

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:

location not delivered in doze mode is by design. When doze mode is active we do best effort location delivery, i.e, we deliver location if the phone wakes up anyways for some other reason, but otherwise we will not wake up the phone just to deliver location

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:

  1. LOCATION_MODE_FOREGROUND_ONLY
  2. LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF
  3. LOCATION_MODE_NO_CHANGE
  4. LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF

Also, certain phone vendors have created phones that do not comply with standard Android behaviour. Check this.