1 回答
TA贡献1795条经验 获得超7个赞
我为什么会看到您的gps无法获得您的位置,并且总是收到null指针,
这是我想获取地理位置时使用的类
LocationDetector.kt
class LocationDetector(val context: Context) {
val fusedLocationClient: FusedLocationProviderClient = FusedLocationProviderClient(context)
var locationListener: LocationListener? = null
interface LocationListener {
fun locationFound(location: Location)
fun locationNotFound(reason: String)
}
fun detectLocation() {
//create request
val locationRequest = LocationRequest()
locationRequest.interval = 0L
// check for permission
val permissionResult = ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION)
// if have permission, try to get location within 10 seconds
if (permissionResult == android.content.pm.PackageManager.PERMISSION_GRANTED) {
val timer = Timer()
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
fusedLocationClient.removeLocationUpdates(this)
timer.cancel()
// return location
locationListener?.locationFound(locationResult.locations.first())
}
}
timer.schedule(timerTask {
fusedLocationClient.removeLocationUpdates(locationCallback)
locationListener?.locationNotFound("Timeout")
}, 10 * 1000) //10 seconds
// make request
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
} else {
// if no permission
locationListener?.locationNotFound("No permission given")
}
}
以及你会怎样的方式
class MainActivity : AppCompatActivity(), LocationDetector.LocationListener {
var isGPSRunning = false
override fun locationFound(location: Location) {
AppPreferencesSingleton(applicationContext).put(AppPreferencesSingleton.Key.latitude,location.latitude.toString())
AppPreferencesSingleton(applicationContext).put(AppPreferencesSingleton.Key.longitude,location.longitude.toString())
}
override fun locationNotFound(reason: String) {
when(isGPSEnabled()){
true -> {
println("Waiting for GPS fix")
}
false -> {
if (!isGPSRunning) {
isGPSRunning = true
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
}
}
}
fun isGPSEnabled() = (getSystemService(Context.LOCATION_SERVICE) as LocationManager).isProviderEnabled(LocationManager.GPS_PROVIDER)
这在KOTLIN中,但是修改很简单,请记住在清单中设置所需的权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
添加回答
举报