Search code examples
androidgeolocationlocationcoordinates

How to get user location only once without tracking?


In my android app, I need to gt the user location when he clicks a button. I do not need to receive continuous updates on his location however.

I searched through a few questions on stackoverflow, but the answers are 2-3 years old, so I was wondering, as on the Android SDK now, what is the best way to do it.

Also, I would like not to get null in the location if possible.

Thanks in advance.


Solution

  • UPDATE September 23, 2020

    Change log of version 17.1.0 mentions a new way to get current location:

    FusedLocationProviderClient.getCurrentLocation()

    A single fresh location will be returned if the device location can be determined within reasonable time (tens of seconds), otherwise null will be returned. This method may return locations that are a few seconds old, but never returns much older locations. This is suitable for foreground applications that need a single fresh current location.

    Documentation: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken)

    Example of usage:

    val cancellationTokenSource = CancellationTokenSource()
    fusedLocationProviderClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, cancellationTokenSource.token)
    
    // onStop or whenever you want to cancel the request
    cancellationTokenSource.cancel()
    

    Old Answer

    You can use setNumUpdates method and pass the value 1. example:

    mLocationRequest = new LocationRequest();
    mLocationRequest.setNumUpdates(1);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    

    By default locations are continuously updated until the request is explicitly removed, however you can optionally request a set number of updates. For example, if your application only needs a single fresh location, then call this method with a value of 1 before passing the request to the location client.

    https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.html#setNumUpdates(int)