I have an Android App using the Geofence API
val intent = Intent(contextProvider.context, GeofenceReceiver::class.java)
val pendingIntent= PendingIntent.getBroadcast(contextProvider.context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
val builder = GeofencingRequest.Builder()
builder.setInitialTrigger(initialTrigger)
addGeofences(builder) // in this function I have the code to add one or more geofences
geofencingRequest = builder.build()
The code works fine and I get the method onReceive called in my broadcast receiver, if the device is not idle. During idle periods, the device doesn't react at all.
I tried to add in the manifest the permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
and in another place I call the code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val powerManager = context.getSystemService(POWER_SERVICE) as PowerManager
val packageName = context.applicationContext.packageName
val ignoringOptimizations = powerManager.isIgnoringBatteryOptimizations(packageName)
if (!ignoringOptimizations) {
val intent = Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
intent.setData(Uri.parse("package:$packageName"))
context.startActivity(intent)
}
}
and if I didn't already allowed to ignore the battery optimization I can see the dialog asking for that. I don't see any difference in the behaviour of the app. In order to check if the new permission works, I have a background thread logging every second the value of a counter:
Single.fromCallable {
var counter = 0
do {
Timber.i("#$counter")
Thread.sleep(1000)
} while (counter++ < 120)
}.subscribeOn(Schedulers.io()).subscribe({
Timber.i("onSuccess")
},
{
Timber.e("onError: $it")
})
This is the kind of logging that I get:
Mi. Apr. 17 2019 at 13:47:27:662 : - #1
Mi. Apr. 17 2019 at 13:47:28:674 : - #2
Mi. Apr. 17 2019 at 13:47:29:683 : - #3
Mi. Apr. 17 2019 at 13:47:30:693 : - #4
Mi. Apr. 17 2019 at 13:47:31:700 : - #5
Mi. Apr. 17 2019 at 13:47:32:707 : - #6
Mi. Apr. 17 2019 at 13:47:33:719 : - #7
Mi. Apr. 17 2019 at 13:47:40:008 : - #8
Mi. Apr. 17 2019 at 13:47:41:018 : - #9
Mi. Apr. 17 2019 at 13:47:42:036 : - #10
Mi. Apr. 17 2019 at 13:48:55:449 : - #11
Mi. Apr. 17 2019 at 13:48:56:457 : - #12
Mi. Apr. 17 2019 at 13:48:57:471 : - #13
You can notice, that at the beginning every second there is a new output, then there are some lags. I assume this lags are because of the idle mode. I get similar logs with and without battery optimization.
My app uses also a foreground service that should avoid the app going idle, but it doesn't seem to have any effect.
At the end I have two questions:
1- how should I use the permission to ignore the battery optimization, in order to see an effect on the app?
2- are there better approaches in order to manage geofences while the device is idle?
Thanks!