1 回答

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
我為什么會(huì)看到您的gps無法獲得您的位置,并且總是收到null指針,
這是我想獲取地理位置時(shí)使用的類
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")
}
}
以及你會(huì)怎樣的方式
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中,但是修改很簡單,請(qǐng)記住在清單中設(shè)置所需的權(quán)限:
<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" />
添加回答
舉報(bào)