[英]How to get location just once in android (kotlin)
我只想在 android 應用程序中獲得一次位置。 這就是我試圖獲取位置的方式
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在我的片段中
private lateinit var fusedLocationClient: FusedLocationProviderClient
// in onCreateView
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
// in function after checking permission
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
}
}
現在位置每次都返回null
除非我打開谷歌地圖並運行我的應用程序然后它會正確返回位置
現在我知道我需要在調用lastLocation
之前調用requestLocationUpdates
但我無法在kotlin
中找到任何解決方案來解釋如何只使用just one time
。 每個解決方案都建議一次又一次地獲取位置。
無論如何,我可以使用requestLocationUpdates
來獲取一次位置嗎?
最新版play-services-location
添加方法getCurrentLocation()
fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.