[英]How can i get current GPS location ? (not lastknown)
我正在嘗試僅使用 GPS 提供程序來獲取用戶的位置。 我不希望我的應用程序在特定時間段后或位置更改后獲取最后一個已知位置或請求位置更新。有什么方法可以在按鈕按下時為我提供當前位置??? ...我是初學者,我已經嘗試過 android 工作室的 LocationManager API,它返回網絡提供的位置很好,但在使用 GPS 時可以正常工作。 這是我的代碼:
fun getlocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION), locationPermissionCode)
}
else
{
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
// val listener = locationListener()
val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
//if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N)
if (gps || network) {
if (network) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 5F, this)
}
if (gps) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 5F, this)
}
}
else {
val AlertDialog = AlertDialog.Builder(this)
AlertDialog.setTitle("GPS is Disabled")
AlertDialog.setMessage("Do you want enable GPS ?")
AlertDialog.setPositiveButton("Yes") { dialougeInterface: DialogInterface, i: Int ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
dialougeInterface.dismiss()
}
AlertDialog.setNegativeButton("No") { dialouge: DialogInterface, i: Int ->
dialouge.dismiss()
}
AlertDialog.show()
}
}
}
我在父 class “class AddCustomer: AppCompatActivity(), LocationListener”中添加了位置監聽器
在覆蓋 function 中:
override fun onLocationChanged(location: Location) {
locationx.text = location.latitude.toString() +" , "+ location.longitude.toString()
}
我應該使用“LocationManager”中的“getcurrentlocation()”方法嗎?
我不知道你是否得到了你的最后一個位置。 當您從 gps 提供商處得不到任何東西時,這就是答案。
像這樣制作這個塊只會讓你通過 gps 獲得你的位置。
if (gps) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 5F, this)
}
當您的設備的 GPS 芯片組感覺像是從 GPS 獲得信號時,上述內容可能會返回,因此在建築物內時,它可能不會收到任何響應。 Go 在外面試一試。
在您的用例中,按下按鈕以獲得准確的位置,以防用戶無法接收到任何信號,您應該提供超時回調。
private val mHandler = Handler(Looper.getMainLooper())
private val mTimeoutRunnable = Runnable {
//stopLoading
//Toast the user to try it somewhere else
}
fun askGsp() {
mHandler.postDelayed(mTimeoutRunnable, 5 * 1000) //time out in 5 seconds
//ask for gps update like the code above
//...
override fun onLocationChanged(location: Location) {
mHandler.removeCallbacks(mTimeoutRunnable) //remove timeout action
locationx.text = location.latitude.toString() +" , "+
location.longitude.toString()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.