Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Android: Use FusedLocationProviderClient to get location once?

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

like image 397
Spotz Avatar asked Dec 28 '17 06:12


2 Answers

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

FusedLocationProviderClient has the following methods

  • getLastLocation() that returns a location "just once"
  • requestLocationUpdates (LocationRequest request, LocationCallback callback, Looper looper)
  • requestLocationUpdates (LocationRequest request, PendingIntent callbackIntent)

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

like image 127
Onik Avatar answered Sep 21 '22 11:09


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

This is how I am getting location


<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)
                .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))
like image 37
Zohab Ali Avatar answered Sep 19 '22 11:09

Zohab Ali