В настоящее время согласно Согласно коду, обновления местоположения поступают с интервалом каждые 10 секунд, но это потенциально может разрядить батарею пользователя. Поэтому мне нужно решение, позволяющее получать обновления местоположения с интервалом в 1 минуту или при обновлении расстояния в 10 метров, что наступит раньше!
Current LocationRequest строитель:
Код: Выделить всё
private const val LOCATION_UPDATE_INTERVAL = 10000L
private fun createRequest(): LocationRequest =
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, LOCATION_UPDATE_INTERVAL)
.apply {
setGranularity(Granularity.GRANULARITY_PERMISSION_LEVEL)
setMinUpdateIntervalMillis(LOCATION_UPDATE_INTERVAL)
setWaitForAccurateLocation(true)
}.build()
Вот общий код класса LocationManager.kt:
Код: Выделить всё
private const val LOCATION_UPDATE_INTERVAL = 10000L
@Singleton
class LocationManager @Inject constructor(@ApplicationContext private val context: Context) {
private var request: LocationRequest
private var locationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
init {
request = createRequest()
}
suspend fun getLastLocation(): Location? {
if (!context.hasCoarseLocationPermission) return null
return locationClient.lastLocation.await()
}
private val locationUpdatePendingIntent: PendingIntent by lazy {
val intent = Intent(context, LocationUpdateReceiver::class.java)
intent.action = ACTION_LOCATION_UPDATE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
} else {
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
private fun createRequest(): LocationRequest =
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, LOCATION_UPDATE_INTERVAL)
.apply {
setGranularity(Granularity.GRANULARITY_PERMISSION_LEVEL)
setMinUpdateIntervalMillis(LOCATION_UPDATE_INTERVAL)
setWaitForAccurateLocation(true)
}.build()
internal fun startLocationTracking() {
if (context.hasFineLocationPermission) {
locationClient.requestLocationUpdates(request, locationUpdatePendingIntent)
}
}
internal fun stopLocationTracking() {
if (!context.isBackgroundLocationPermissionGranted) {
locationClient.flushLocations()
locationClient.removeLocationUpdates(locationUpdatePendingIntent)
}
}
fun startService() {
context.startService(Intent(context, BackgroundLocationService::class.java))
}
fun stopService() {
context.stopService(Intent(context, BackgroundLocationService::class.java))
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... dwhichever