Android-通過GPS或者網絡獲取當前位置 kotlin


 

在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中調用就行了。

 

這種獲取定位方式不適合需要實時監聽位置變化的需求,只適合獲取一次。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM