Android利用自帶的位置服務,獲取當前位置資訊
- 2019 年 11 月 4 日
- 筆記
筆者項目里,需要獲取用戶的當前位置資訊,因為沒有接地圖SDK,打算用原生自帶的位置服務去做。操作了一下,踩了幾個大坑,總算是幸不辱命。這裡做個記錄,順便分享給大家。
程式碼與講解:
/** * 初始化地理位置 */ @SuppressLint("MissingPermission") fun initLocation() { Thread(Runnable { val serviceString = Context.LOCATION_SERVICE// 獲取的是位置服務 val locationManager = getSystemService(serviceString) as LocationManager val provider = LocationManager.NETWORK_PROVIDER// 指定LocationManager的定位方法 val location = locationManager.getLastKnownLocation(provider) var address = getAddress(location) runOnUiThread { tvLocation.text = address } }).start() } /** * 通過經緯度獲取位置資訊 */ private fun getAddress(location: Location?): String {//一定要非同步,否則獲取不到 //用來接收位置的詳細資訊 var result: List<Address>? = null var addressLine = "" try { if (location != null) { val gc = Geocoder(this, Locale.getDefault()) result = gc.getFromLocation(location.latitude, location.longitude, 1) if (result.isNotEmpty()) { try { addressLine = result[0].getAddressLine(0) + result[0].getAddressLine(1) } catch (e: java.lang.Exception) { addressLine = result[0].getAddressLine(0) } } } addressLine=addressLine.replace("null","") } catch (e: Exception) { e.printStackTrace() } return addressLine }
上面兩個方法,就可以實現這個功能了,筆者通過tvLocation.text = address
直接將位置資訊渲染在介面上。朋友們如果只是想實現功能,程式碼copy進項目就OK,想要了解細節可以繼續往下看。
爬坑指南:
1.initLocation()這個方法,可以看到筆者是放在執行緒里跑的,一定要這樣做,否則拿到經緯度之後,無法通過經緯度獲取到位置資訊。筆者在這裡糾結了許久。 2.在通過經緯度獲取位置資訊時,獲取到的result是個集合,他對你的當前位置做了不同維度的描述,越後面的,描述得越精確。