kotlin 未触发后台位置更新BroadcastReceiver

tvz2xvvm  于 2023-03-24  发布在  Kotlin
关注(0)|答案(1)|浏览(117)

尽管Android文档坚持不使用后台位置更新,但我的应用确实需要它们,所以我更新了所有内容以正确请求权限并遵守新规则。现在,一旦我获得了ACCESS_BACKGROUND_LOCATION权限,我就可以在初始片段中请求后台位置更新:

private fun configureBackgroundLocationTracking() {
    fusedLocationClient.requestLocationUpdates(createLocationRequest(), getPendingIntent())
}

private fun createLocationRequest(): LocationRequest {
    return LocationRequest.create().apply {
        interval = 20000
        fastestInterval = 10000
        priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
    }
}

private fun getPendingIntent(): PendingIntent {
    val intent = Intent(requireContext(), LocationUpdatesBroadcastReceiver::class.java)
    return PendingIntent.getBroadcast(
        requireContext(),
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
}

在我的AndroidManifest中,我这样声明BroadcastReceiver:

<receiver android:name=".LocationUpdatesBroadcastReceiver"
            android:exported="true"
            android:permission="android.permission.ACCESS_BACKGROUND_LOCATION">
    <intent-filter>
        <action android:name="com.herontrack.LOCATION_UPDATE" />
    </intent-filter>
</receiver>

下面是我的LocationUpdatesBroadcastReceiver的代码:

class LocationUpdatesBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val result = LocationResult.extractResult(intent)
        if (result != null) {
            val location = result.lastLocation
            if (location != null) {
                Log.d(TAG, "Received location update: $location")
            }
        }
    }

    companion object {
        private const val TAG = "LUBroadcastReceiver"
    }
}

onReceive()中的log指令将日志发送到远程日志记录器(Bugfender)。当我的应用程序在前台时,一切似乎都正常,我可以看到日志。但是当它在后台时,没有更多的更新。
我仔细检查了权限,我确信当我注册BroadcastReceiver时,ACCESS_BACKGROUND_LOCATION被授予。
我在三星S9上运行Android 10。
我是不是忘了什么?在一个碎片内做所有这些有问题吗?

相关问题