尽管Android文档强烈建议不要使用后台位置更新,但我的应用确实需要它们,因此我已更新所有内容以正确请求权限并遵守新规则。现在,一旦我获得了“ACCESS_BACKGROUND_LOCATION”权限,我会在初始Fragment内执行以下操作来请求后台位置更新:
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
权限。
我正在Samsung S9上运行Android 10。
我有遗漏吗?从Fragment中执行所有这些是否存在问题?