尽管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。
我是不是忘了什么?在一个碎片内做所有这些有问题吗?
1条答案
按热度按时间ulmd4ohb1#
PendingIntent.FLAG_MUTABLE或PendingIntent.FLAG_UPDATE_CURRENT i had the same issue. for background location updates latest android need to show notification