Получить текущее местоположение GPS на Android при первой установке
У меня есть кнопка, которая получает текущее местоположение пользователя. При первой установке приложения, когда никакие другие приложения на устройстве никогда не пытались использовать какие-либо службы определения местоположения, я получаю нулевое значение в locationManager.
Как только один сервис Location используется в другом приложении, все работает как надо.
Это основной класс, который я сделал для установки и получения координат GPS:
class GPSLocator(private val mContext: Activity) : Service(), LocationListener {
internal var isGPSEnabled = false
internal var isNetworkEnabled = false
internal var canGetLocation = false
internal var location: Location? = null // location
internal var latitude: Double = 0.toDouble() // latitude
internal var longitude: Double = 0.toDouble() // longitude
var locationManager: LocationManager? = null
init {
getLocation()
}
fun getLocation(): Location? {
if (checkLocationPermission()) {
locationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (locationManager != null) {
isGPSEnabled = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)}
if (locationManager != null) {
isNetworkEnabled = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)}
if (!isGPSEnabled && !isNetworkEnabled) {
showSettingsAlert()
} else {
canGetLocation = true
if (isNetworkEnabled) {
locationManager!!.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this)
if (locationManager != null) {
location = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (location != null) {
latitude = location!!.latitude
longitude = location!!.longitude
}
}
}
if (location == null) {
if (locationManager != null) {
locationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this)
location = locationManager!!
.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location != null) {
latitude = location!!.latitude
longitude = location!!.longitude
}
}
}
}
} else {
ActivityCompat.requestPermissions(mContext, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
}
return location
}
fun getLatitude(): Double {
this.location = location
if (location != null) {
latitude = location!!.latitude
}
return latitude
}
fun getLongitude(): Double {
this.location = location
if (location != null) {
longitude = location!!.longitude
}
return longitude
}
fun canGetLocation(): Boolean = this.canGetLocation
fun checkLocationPermission(): Boolean {
val permission = "android.permission.ACCESS_FINE_LOCATION"
val res = mContext.checkCallingOrSelfPermission(permission)
return res == PackageManager.PERMISSION_GRANTED
}
override fun onLocationChanged(location: Location) {
this.location = location
getLatitude()
getLongitude()
}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onBind(arg0: Intent): IBinder? = null
companion object {
private val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 10 // 10 meters
private val MIN_TIME_BW_UPDATES = (1000 * 60).toLong() // 1 minute
}
}
И вот как я это называю из фрагмента:
val gps = GPSLocator(this.activity)
if(gps.canGetLocation()){
evLat!!.setText(gps.latitude.toString())
evLng!!.setText(gps.longitude.toString())
}
Как я уже говорил ранее, это работает хорошо, за исключением первого использования. Любая помощь или рекомендуемые рамки будут весьма признательны.