Android- get the current position via GPS or network kotlin

 

Add in the AndroidManifest

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

kotlin Code

 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     }

The last call onCreate directly on the line.

 

Obtain this way is not suitable for real-time monitoring position needs changing needs, obtaining only for once.

Guess you like

Origin www.cnblogs.com/lyj348990/p/11537410.html