<!--定位权限-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// 请求结果,返回一个map ,其中 key 为权限名称,value 为是否权限是否赋予
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { it ->
//通过的权限
val grantedList = it.filterValues { it }.mapNotNull { it.key } //是否所有权限都通过
val allGranted = grantedList.size == it.size
if(!allGranted) "请同意所需权限!".showShortToast() else location()
}.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION))
/**
* 定位获取当前城市
*/
private fun location() {
val locationManager = context?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
var providerName = ""
val providerList = locationManager.getProviders(true)
providerName = when {
providerList.contains(LocationManager.NETWORK_PROVIDER) -> {
LocationManager.NETWORK_PROVIDER
}
providerList.contains(LocationManager.GPS_PROVIDER) -> {
LocationManager.GPS_PROVIDER
}else -> {
"provider 获取失败".showShortToast()
return
}
}
val location = if(context?.let { ActivityCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION) } == PackageManager.PERMISSION_GRANTED && context?.let { ActivityCompat.checkSelfPermission(it, Manifest.permission.ACCESS_COARSE_LOCATION) } == PackageManager.PERMISSION_GRANTED) {
locationManager.getLastKnownLocation(providerName)
} else null
if(location != null) {
val longitude : Double = location.longitude // 经度
val latitude : Double = location.latitude // 纬度
// 因为这里 Geocoder对象的 getFromLocation 方法,源码说明中建议在工作线程执行 getFromLocation方法
Thread {
try {
val geocoder = Geocoder(context, Locale.getDefault())
val result = geocoder.getFromLocation(latitude, longitude, 1)[0].locality
//result="北京市"
activity?.runOnUiThread {
viewModel.tvAddress.set(result)
}
} catch(e : Exception) {
e.printStackTrace()
}
}.start()
} else "定位失败".loge()
}