1

Google уже сто раз меняет способ получения местоположения, прошариф весь SO и попробовав миллион кода, все без результатно.

даже getLast из Сервисов не помогает. Не могу понять почему так трудно сделать пару строчек кода для получения местоположения....

Что делать? как сейчас получают местоположение, Можете рабочий пример скинуть

1 ответ 1

1

В "пару строк" кода можно попробовать реактивно получить местоположение. Подключаем зависимости в модуле приложения:

implementation 'com.patloew.rxlocation:rxlocation:1.0.3'
implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.8.2@aar'

С помощью Dagger 2, к примеру, провайдим RxLocation и RxPermission (или создаем объекты ручками по месту, где они нужны):

@Module class LocationModule(val context: Context) {

@Provides
@Singleton
fun provideRxLocation(): RxLocation = RxLocation(context)

@Provides
@Singleton
fun provideRxPermissions(): RxPermissions = RxPermissions.getInstance(context)}

Определяем класс LocationProvider:

@Singleton class LocationProvider @Inject constructor(
    val rxLocation: RxLocation,
    val rxPermissions: RxPermissions) {

@SuppressLint("MissingPermission")
fun lastKnownLocation(): Single<Location> =
        requestLocationPermission()
                .andThen(rxLocation.location().lastLocation())
                .toSingle()

private fun requestLocationPermission(): Completable =
        rxPermissions.request(android.Manifest.permission.ACCESS_FINE_LOCATION)
                .flatMapCompletable { permissionGranted ->
                    if (permissionGranted) Completable.complete()
                    else Completable.error(Exception())
                }
                .doOnError { t -> Log.d("Error", "Fine location permission was not granted: " + t.message) } }

И в классе LocationPresenter, например, инжектим LocationProvider и дергаем локацию:

class LocationPresenter : MvpPresenter<LocationView>() { //или какая-то Ваша реализация MVP и пр.

@Inject lateinit var locationProvider: LocationProvider
@Inject lateinit var repository: LocationRepository
private val subscriptions = CompositeDisposable()

fun lastKnownLocation(isFrom: Boolean) {
    locationProvider.lastKnownLocation()
            .flatMap { location -> repository.getCurrentLocationAddress(location) }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    { address ->
                        //И из объекта типа Address уже получаем всю нужную информацию
                        address.getAddressLine(0)
                        address.longitude
                        address.latitude
                    },
                    { t -> Log.getStackTraceString(t) }
            ).addTo(subscriptions)
}

И, собственно, класс LocationRepository:

class LocationRepository @Inject constructor(val rxLocation: RxLocation) {

fun getCurrentLocationAddress(location: Location): Single<Address> =
        rxLocation.geocoding()
                .fromLocation(location)
                .toSingle() }

В манифесте не забываем:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.