6

With FusedLocationProviderApi being deprecated, I'm having a hard time using FusedLocationProviderClient to get location of a user just once after a button click.

Onik
  • 19,396
  • 14
  • 68
  • 91
Spotz
  • 113
  • 3
  • 8

2 Answers2

9

I'm having a hard time using FusedLocationProviderClient to get location of the user just once...

FusedLocationProviderClient has the following methods

where LocationRequest, in its turn, has the setNumUpdates (int numUpdates) method. By passing numUpdates = 1 you'll "get location of the user just once".

Onik
  • 19,396
  • 14
  • 68
  • 91
1

New version of play-services-location added the method getCurrentLocation()

This is how I am getting location

AndroidManifest.xml

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

In my Fragment

private lateinit var fusedLocationClient: FusedLocationProviderClient

Then After getting location permission code this is how I am getting location

  fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)
  fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        textView.setText(getLocationNameFromLatLon(location.latitude, location.longitude))
                    }
                }
Zohab Ali
  • 8,426
  • 4
  • 55
  • 63