androidkotlinandroid-locationandroid-maps

How to get location just once in android (kotlin)


I just want to get location for one time in android app. This is how I am trying to get 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


// in onCreateView
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())

// in function after checking permission
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    if (location != null) {

                    }
                }

Now location is returning null everytime EXCEPT if I open google maps & run my app then it returns location correctly

Now I know that I need to call requestLocationUpdates before calling lastLocation but I am unable to find any solution in kotlin that explains how to use it for just one time. Every solution suggests getting location again and again.

Is there anyway that I can use requestLocationUpdates just to get location once?


Solution

  • the latest version of play-services-location add the method getCurrentLocation()

    fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)