问题描述
我正在尝试仅使用 GPS 提供商获取用户的位置。我不希望我的应用程序在特定时间段或位置更改后获取最后一个已知位置或请求位置更新。有什么方法可以在按下按钮时为我提供当前位置??? ...我是一个初学者,我尝试过 android studio 的 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,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 AddCustomer : AppCompatActivity(),LocationListener ”中添加了位置侦听器
在覆盖功能中:
override fun onLocationChanged(location: Location) {
locationx.text = location.latitude.toString() +","+ location.longitude.toString()
}
我应该使用“LocationManager”中的“getcurrentlocation()”方法吗?
解决方法
我不知道你是否得到了最后的位置。当您根本没有从 GPS 提供商那里得到任何东西时,这就是答案。
像这样制作这个块只会让你通过 GPS 获取你的位置。
$ ./bin/getline_ss_sum
1 2 3
Sum is: 6
当您设备的 GPS 芯片组感觉它正在从 GPS 接收信号时,上述内容会返回,因此在建筑物内时,它可能不会收到任何响应。 出去试试吧。
在您的用例中,按下按钮以获取准确位置,以防用户无法接收到任何信号,您应该提供超时回调。
$ ./bin/getline_ss_sum
1
2
3
Sum is: 6