Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65602766/how-to-get-location-just-once-in-android-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...