Android-通过GPS或者网络获取当前位置 kotlin

时间:2021-10-11 18:50:47

 

在AndroidManifest中添加

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

kotlin代码

 1  private fun getLocation(context: Context): Location {
 2         val locMan = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
 3         val checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
 4         val checkCallPhonePermission =
 5             ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
 6         if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
 7             ActivityCompat.requestPermissions(this, permission, 2)
 8         }
 9         way.text = "通过GPS定位"
10         val location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)
11         if (location == null) {
12             way.text = "通过网络定位"
13             locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
14         }
15         return location
16     }
17 
18     private fun getGeoByLocation(location:Location){
19         longitude.text ="longitude:${location.longitude}"
20         latitude.text = "latitude:${location.latitude}"
21         val ge =Geocoder(this)
22         var addressList =ArrayList<Address>()
23         try {
24             addressList = ge.getFromLocation(location.latitude,location.longitude,1) as ArrayList<Address>
25             detail.text = addressList.toString()
26         }catch (e:IOException){
27             e.printStackTrace()
28         }
29         if (addressList.size>0){
30             address.text = "${addressList[0].getAddressLine(0)}"
31         }
32     }

最后直接在onCreate中调用就行了。

 

这种获取定位方式不适合需要实时监听位置变化的需求,只适合获取一次。