如果有人知道这件事发生了什么,请帮忙。
我有注册到ForegroundService的BroadcastReceiver。此BroadcastReceiver将侦听Intent.ACTION_SCREEN_ON并调用startLocationUpdates() (如果它接收到任何)。
fun startLocationUpdates(context: Context, entity: LockEntityDB?) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
mSettingsClient = LocationServices.getSettingsClient(context)
mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
super.onLocationResult(locationResult)
val location = locationResult?.lastLocation
locationResult?.let {
saveLocation(context, it.lastLocation)
locationUpdatesCount(context)
}
//something will do with entityDb
}
}
mOneTimeLocationRequest = LocationRequest().apply {
interval = 5 * 1000
fastestInterval = 1000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
numUpdates = 1
}
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(mOneTimeLocationRequest!!)
mLocationSettingsRequest = builder.build()
mSettingsClient
?.checkLocationSettings(mLocationSettingsRequest)
?.addOnSuccessListener {
mFusedLocationClient?.requestLocationUpdates(mOneTimeLocationRequest, mLocationCallback, null)
}
?.addOnFailureListener { e ->
kTimberLog(context, "loc " + e.toString())
}
}因此,如果用户打开手机,它将发送Intent.ACTION_SCREEN_ON,FusedLocationProviderClient将更新实际用户位置。
问题是,当用户在5-6倍FusedLocationProviderClient后尝试打开手机时,再也不会给任何locationResult了。
更奇怪的是,当用户打开MainActivity时,所有这些locationResult会重复出现6次,以此类推。
附加信息:我正在3个模拟器上测试此代码: Nexus 5 API 23,PIXEL 3 API 29,Galaxy Nexus API 29。它在Nexus 5 API 23上工作得很好。
有谁知道这种行为的原因是什么?非常感谢
发布于 2020-05-15 01:01:47
经过几天的努力,我在这里找到了解决方案:https://developer.android.com/training/location/request-updates#continue-user-initiated-action
将这一行添加到我的清单中之后,一切看起来都很正常
<service
android:name="MyBackgroundService"
android:foregroundServiceType="location" ... >
...
我希望能帮助那些陷入同样问题的人。
https://stackoverflow.com/questions/61797168
复制相似问题