/**
* Created by luowenbin on 2021/9/15.
*/
class Locator(context: Context) {
private val locationManager: LocationManager =
context.applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
data class LocaleOptions(
val providerTimeout: Long = 2000L,
val preferCriteria: Criteria = defaultCriteria(),
val preferUpdateTime: Long = 1000L,
val preferUpdateDistance: Float = 1f
)
@RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
suspend fun locale(option: LocaleOptions = LocaleOptions()) =
locationManager.getPreferProviders(option.preferCriteria)
.firstNotNullOfOrNull {
withTimeoutOrNull(option.providerTimeout) {
localeByProvider(it, option.preferUpdateTime, option.preferUpdateDistance)
} ?: locationManager.getLastKnownLocation(it)
}
val TAG: String = this.javaClass.simpleName
private var locationUpdater: LocationListener? = null
@RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
suspend fun localeByProvider(
provider: String,
minTime: Long = 1000L,
minDistance: Float = 1f
): Location? {
Log.d(TAG, "localeByProvider: $provider")
locationUpdater?.let { locationManager.removeUpdates(it) }
return suspendCancellableCoroutine { c ->
locationUpdater = object : LocationListener {
override fun onLocationChanged(location: Location) {
c.resume(location)
}
override fun onProviderDisabled(provider: String) {
c.resume(null)
}
}.also {
locationManager.requestLocationUpdates(
provider, minTime, minDistance,
it
)
c.invokeOnCancellation { _ ->
locationManager.removeUpdates(it)
}
}
}
}
companion object {
fun LocationManager.getPreferProviders(criteria: Criteria = defaultCriteria()): List<String> {
val bestProvider = this.getBestProvider(criteria, true)
val enableProviders = this.getProviders(true).toMutableList()
if (bestProvider != null) {
//move prefer provider to first
enableProviders.remove(bestProvider)
enableProviders.add(0, bestProvider)
}
return enableProviders
}
private fun defaultCriteria() = Criteria().apply {
accuracy = Criteria.ACCURACY_FINE
isAltitudeRequired = false
isBearingRequired = false
isCostAllowed = false
powerRequirement = Criteria.NO_REQUIREMENT
}
}
}
网友评论