android - 后台位置更新 BroadcastReceiver 未触发
问题描述
尽管 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()
将日志发送到远程记录器(Bugfender)。当我的应用程序处于前台时,一切似乎都正常,我可以看到日志。但是当它在后台时,不再更新。
我仔细检查了许可,我确定当我注册BroadcastReceiver
,时ACCESS_BACKGROUND_LOCATION
被授予。
我在装有 Android 10 的三星 S9 上运行。
我是不是忘记了什么?在 Fragment 中执行所有这些操作有问题吗?
解决方案
推荐阅读
- php - 如何为 wordpress 制作 OG 图片
- mysql - 多个或查询中的顺序会影响相关性吗?
- haskell - 在构建中包含美味快速检查的问题
- reactjs - 垂直对齐 div 元素
- delphi - Delphi 10.3 中带有预览的文件打开对话框
- spring-boot - 添加执行器的依赖项后,Spring Boot 无法正常工作
- docker - 为 centos 8 容器设置 php-fpm
- flutter - 在 POST 请求后更新显示的数据
- email - smtp 错误:535 5.7.8 Go 中的 gmail 不接受用户名和密码
- java - 在 Java 中使用 ProcessBuilder 读取输出 git-bash