Android-通过GPS或者网络获取当前位置 kotlin
private fun getLocation(context: Context): Location {
val locMan = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
val checkCallPhonePermission =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permission, 2)
}
way.text = "通过GPS定位"
val location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null) {
way.text = "通过网络定位"
locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
return location
}
private fun getGeoByLocation(location:Location){
longitude.text ="longitude:${location.longitude}"
latitude.text = "latitude:${location.latitude}"
val ge =Geocoder(this)
var addressList =ArrayList()
try {
addressList = ge.getFromLocation(location.latitude,location.longitude,1) as ArrayList detail.text = addressList.toString()
}catch (e:IOException){
e.printStackTrace()
}
if (addressList.size>0){
address.text = "${addressList[0].getAddressLine(0)}"
}
}来源:https://www.cnblogs.com/lyj348990/p/11537410.html
另外还可以使用: