首页 > 解决方案 > 如何在 Android 中正确使用 REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 权限以允许 GeofenceAPI 在打瞌睡期间也能正常工作?

问题描述

我有一个使用 Geofence API 的 Android 应用程序

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()

代码工作正常,如果设备不空闲,我会在广播接收器中调用 onReceive 方法。在空闲期间,设备根本没有反应。

我试图在清单中添加权限REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,并在另一个地方调用代码

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)
    } 
}

如果我还没有允许忽略电池优化,我可以看到对话框要求这样做。我看不出应用程序的行为有什么不同。为了检查新权限是否有效,我有一个后台线程每秒记录一个计数器的值:

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")

    })

这是我得到的日志记录:

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

你可以注意到,在一开始每秒都有一个新的输出,然后有一些滞后。我认为这种滞后是由于空闲模式。无论有没有电池优化,我都会得到类似的日志。

我的应用程序还使用了一个前台服务,该服务应该避免应用程序空闲,但它似乎没有任何效果。

最后我有两个问题:

1-我应该如何使用权限忽略电池优化,以查看对应用程序的影响?

2-有没有更好的方法可以在设备空闲时管理地理围栏?

谢谢!

标签: androidkotlinandroid-geofencedoze

解决方案


推荐阅读