如何解决使用 WorkManager 检索后台位置始终返回相同的最后已知位置
如果使用前台服务获取用户位置,我的应用运行良好,但是在后台我只需要每 15 分钟定位一次,Google
也需要新的 Policy for getting background location,因此,前台服务超出了我的预期。
我正在尝试使用 WorkManager
从后台获取位置,它可以每(大约)15 分钟正常运行一次。请求了我的位置,但它总是返回以前的地址,即使过去了 1、2... 小时。
这是我的代码:
class LocationWorker(private val context: Context,params: WorkerParameters) :
CoroutineWorker(context,params) {
private var fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
override suspend fun doWork() = withContext(Dispatchers.IO) {
val location = getLocation()
if (location == null) {
if (runAttemptCount < MAX_ATTEMPT) { // max_attempt = 3
Result.retry()
} else {
Result.failure()
}
} else {
Log.d(TAG,"doWork success $location")
Result.success()
}
}
private suspend fun getLocation(): Location? = withTimeoutOrNull(TIMEOUT) {
suspendCancellableCoroutine<Location?> { continuation ->
val intent = PendingIntent.getBroadcast(context,REQUEST_CODE,Intent(ACTION),0)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?,data: Intent?) {
if (data?.action != ACTION) return
val lastLocation = LocationResult.extractResult(data)?.lastLocation
Log.e(TAG,"Get lastLocation success $lastLocation")
fusedLocationClient.removeLocationUpdates(intent)
context?.unregisterReceiver(this)
continuation.resume(lastLocation)
}
}
context.registerReceiver(receiver,IntentFilter(ACTION))
val request = LocationRequest().apply { priority = LocationRequest.PRIORITY_HIGH_ACCURACY }
fusedLocationClient.requestLocationUpdates(request,intent)
continuation.invokeOnCancellation {
fusedLocationClient.removeLocationUpdates(intent)
context.unregisterReceiver(receiver)
}
}
companion object {
val TAG = LocationWorker::class.java.simpleName
const val LOCATION_WORKER_TAG = "LOCATION_WORKER_TAG"
const val MAX_ATTEMPT = 3
private const val ACTION = "my.background.location"
private const val TIMEOUT = 60_000L
private const val REQUEST_CODE = 888
}
}
前置条件:
- 经过测试的设备:模拟器 android 27 (O_MR1)
- 路由正常播放
- GPS 已启用
- 允许位置权限(允许所有时间)
为什么 lastknown location
没有更新?
我也试过这个演示 https://github.com/pratikbutani/LocationTracker-WorkManager/ 。但是,问题是一样的,lastknown location
没有更新。
解决方法
先前的位置被缓存。
在将新位置存储在 lastknown location
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。