我拼命地尝试检索我自己的 GPS 位置的坐标,但我的函数总是返回一个 Pair Null,如果你有我感兴趣的解决方案
我在下面尝试这段代码,他只是 Pair Null 返回给我 :( :
此代码获取我的位置并像这样返回纬度和经度 Pair(0.00,0.00) 我在我的清单中拥有所有访问权限。
private fun getLocation(): Pair<Double, Double>? {
try {
val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// Affiche un message d'erreur et retourne null.
val builder = AlertDialog.Builder(this)
builder.setMessage("Please activate your GPS.")
.setCancelable(false)
.setPositiveButton("Paramètres") { _, _ ->
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.cancel()
}
val alert = builder.create()
alert.show()
return null
}
// Verification if GPS is active.
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// show error
val builder = AlertDialog.Builder(this)
builder.setMessage("Please activate your GPS for this fonctionality")
.setCancelable(false)
.setPositiveButton("Paramètres") { _, _ ->
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
.setNegativeButton("Annuler") { dialog, _ ->
dialog.cancel()
}
val alert = builder.create()
alert.show()
return null
}
// Verification if the app have all permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// Ask the authorization for the local position of the user.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
1
)
return null
}
val lastKnownLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
?: return null
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0f
) { location ->
println("Location: ${location.latitude}, ${location.longitude}")
}
val lat = lastKnownLocation.latitude
val long = lastKnownLocation.longitude
println("Location getlocation: $lat, $long")
return Pair(lat, long)
} catch (ex: SecurityException) {
// Gérer l'exception SecurityException levée si la permission ACCESS_FINE_LOCATION n'est pas accordée
println("Security error : ${ex.message}")
return null
} catch (ex: Exception) {
// Gérer les autres exceptions levées par le LocationManager
println("Cant get location : ${ex.message}")
return null
}
}