【发布时间】:2023-03-04 21:18:02
【问题描述】:
如果使用前台服务获取用户位置,我的应用可以正常工作,但是在后台我只需要每 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 没有更新。
【问题讨论】:
标签: android background location android-workmanager