feat: add FusedLocationProvider for GPS location acquisition
This commit is contained in:
parent
1d6aad599c
commit
0f969afbd5
1 changed files with 69 additions and 0 deletions
|
|
@ -0,0 +1,69 @@
|
|||
package com.traccar.traccar_client.location
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import android.os.Looper
|
||||
import com.google.android.gms.location.FusedLocationProviderClient
|
||||
import com.google.android.gms.location.LocationCallback
|
||||
import com.google.android.gms.location.LocationRequest
|
||||
import com.google.android.gms.location.LocationResult
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
|
||||
class FusedLocationProvider(context: Context) {
|
||||
|
||||
private val fusedLocationClient: FusedLocationProviderClient =
|
||||
LocationServices.getFusedLocationProviderClient(context)
|
||||
|
||||
private var locationCallback: LocationCallback? = null
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun startLocationUpdates(
|
||||
interval: Long,
|
||||
fastestInterval: Long,
|
||||
accuracy: Int,
|
||||
callback: (Location) -> Unit
|
||||
) {
|
||||
val locationRequest = LocationRequest.Builder(interval)
|
||||
.setMinUpdateIntervalMillis(fastestInterval)
|
||||
.setPriority(mapAccuracy(accuracy))
|
||||
.build()
|
||||
|
||||
locationCallback = object : LocationCallback() {
|
||||
override fun onLocationResult(result: LocationResult) {
|
||||
result.lastLocation?.let { callback(it) }
|
||||
}
|
||||
}
|
||||
|
||||
fusedLocationClient.requestLocationUpdates(
|
||||
locationRequest,
|
||||
locationCallback!!,
|
||||
Looper.getMainLooper()
|
||||
)
|
||||
}
|
||||
|
||||
fun stopLocationUpdates() {
|
||||
locationCallback?.let {
|
||||
fusedLocationClient.removeLocationUpdates(it)
|
||||
locationCallback = null
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun getLastLocation(callback: (Location?) -> Unit) {
|
||||
fusedLocationClient.lastLocation
|
||||
.addOnSuccessListener { location -> callback(location) }
|
||||
.addOnFailureListener { callback(null) }
|
||||
}
|
||||
|
||||
private fun mapAccuracy(accuracy: Int): Int {
|
||||
return when (accuracy) {
|
||||
0 -> Priority.PRIORITY_HIGH_ACCURACY
|
||||
1 -> Priority.PRIORITY_HIGH_ACCURACY
|
||||
2 -> Priority.PRIORITY_BALANCED_POWER_ACCURACY
|
||||
3 -> Priority.PRIORITY_LOW_POWER
|
||||
else -> Priority.PRIORITY_BALANCED_POWER_ACCURACY
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue