82

I'd like to simply retrieve device location in my Android project and in order to do so I use the play-services approach:

    protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder( MainSearchActivity.this )
        .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
            @Override
            public void onConnected( Bundle bundle ){
                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                if( location == null ){
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            lastLocation = location;
                        }
                    });
                }
            }
            @Override
            public void onConnectionSuspended( int i ){

            }

        })
        .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed( ConnectionResult connectionResult ){
                if( connectionResult.hasResolution() ){
                    try {
                        // Start an Activity that tries to resolve the error
                        connectionResult.startResolutionForResult(MainSearchActivity.this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    }catch( IntentSender.SendIntentException e ){
                        e.printStackTrace();
                    }
                }else{
                    Utils.logger("Location services connection failed with code " + connectionResult.getErrorCode(), Utils.LOG_DEBUG );
                }
            }
        })
        .addApi(LocationServices.API)
        .build();

    mGoogleApiClient.connect();
}

public Location retrieveLastLocation(){
    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if( loc == null)
    {

    }
    return loc; //TODO: What if loc is null?
}

but the loc variable is ALWAYS null. It's as such on different phones, every single time. Also lastLocation, that I try to assign in the onLocationChanged, never changes. Always null.

These are the permission I set for the app

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

I just don't get it: Why can't the LocationServices retrieve a position? I have all geolocation settings enabled on all three the devices I tested on.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Marco Zanetti
  • 4,051
  • 6
  • 32
  • 48
  • 2
    I request you please take a look at this answer http://stackoverflow.com/a/35833552/3278589 – Subho Feb 17 '17 at 13:52
  • 2
    Starting from `com.google.android.gms:play-services-location:17.1.0` there is now a `getCurrentLocation()` method which tries actively get user's current location. https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken) – Andre Romano Sep 06 '21 at 15:08

13 Answers13

72

The fused Location Provider will only maintain background location if at least one client is connected to it. Now just turning on the location service will not guarantee to store the last known location.

Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and getLastLocation() is invoked right away in onConnected(), that might not be enough time for the first location to arrive..

I suggest you to launch the Maps app first, so that there is at least some confirmed location, and then test your app.

Amit K. Saha
  • 5,871
  • 2
  • 27
  • 35
  • 74
    So what you are saying is that when user is in our app, and we need their location, we need to open the Google Maps app, and then hope that user will come back to our app? – Kaloyan Roussev May 15 '15 at 19:27
  • I am not saying that you need to open Google Maps. All I am saying that there needs to be some location data available already when you are calling fusion provider. After all thats the main benefit of using Fusion Provider, isn't it? – Amit K. Saha May 15 '15 at 19:35
  • 26
    so how do I force some location-obtaining event to happen in my own app – Kaloyan Roussev May 15 '15 at 21:37
  • 6
    In that case, you need to go through regular process of location retrieval. After all, fused location provider is a "power safe and for not so important" tasks. – Amit K. Saha May 16 '15 at 16:44
  • 1
    Thanks - i didn't have a first location set and maps on the emulator helped me set it. Can you however clarify what are the regular process of location retrieval so that if a user who hasn't received their first location yet will not result in the app crashing? Google hasn't said anything regarding this topic: https://developer.android.com/training/location/retrieve-current.html – Simon May 24 '15 at 16:40
  • 9
    I think this blog actually address the issue: http://blog.teamtreehouse.com/beginners-guide-location-android – Simon May 24 '15 at 17:18
  • privacy-wise, what would be the best-fitting solution while sharing at least information as possible with third parties? – kaiya Jun 22 '22 at 10:20
49

As in this post said, The fused Location Provider will only maintain background location if at least one client is connected to it.

But we can skip the process of launching the Google Maps app to get last location by following way.

What we need to do is

  1. We have to request location update from FusedLocationProviderClient
  2. Then we can get the last location from FusedLocationProviderClient, it wouldn't be null.

Request Location

LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            return;
        }
        for (Location location : locationResult.getLocations()) {
            if (location != null) {
                //TODO: UI updates.
            }
        }
    }
};
LocationServices.getFusedLocationProviderClient(context).requestLocationUpdates(mLocationRequest, mLocationCallback, null);

Get last location

LocationServices.getFusedLocationProviderClient(context).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            //TODO: UI updates.
        }
    });

For best result requestLocationUpdates in onStart() of the Activity, and then you can get last location.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128
  • 4
    This is the only solution that worked for me. I had to follow the steps exactly, including `PRIORITY_HIGH_ACCURACY` and setting an interval. Any interval seems to do the trick. I also added `setNumUpdates(1)`. In case anyone is wondering, in order to reproduce the issue where last known location is null, just cold boot an emulator and call `getLastKnownLocation()` right away. – Big McLargeHuge Apr 25 '19 at 14:08
  • What is the point of calling `getLastLocation()` on the fused location provider client here? To get the location sooner than the first update in the location callback? Additionally, can you call `getLastLocation()` immediately after you call `requestLocationUpdates`? – Adam Johns Jul 06 '21 at 20:48
  • @AdamJohns `getLastLocation()` simply returns last saved location from `FusedLocationProviderClient`, And `requestLocationUpdates` simply used to trigger the `FusedLocationProviderClient` to request location, so then `FusedLocationProviderClient` will try to get the latest location, basically we will use this method when `getLastLocation()` method returns null. – Gunaseelan Jul 07 '21 at 03:47
  • @Gunaseelan why not just use `requestLocationUpdates` initially instead of only when `getLastLocation` returns null? – Adam Johns Jul 07 '21 at 04:21
  • You can use. The actual purpose of using `FusedLocationProviderClient` is battery power consumption. Most of the time `getLastLocation` returns your current location only, so we can skip `requestLocationUpdates`. More direct answer is `requestLocationUpdates` will consume more battery. – Gunaseelan Jul 07 '21 at 04:37
16

I think there is a small miss which is not visible to me in the code shown.

The mGoogleApiClient is built but seems not connected.You can verify this by calling mGoogleApiClient.isConnected().

You can just override the onStart method and call connect there. Or you can override onResume() in case you want to access the location whenever ur activity is visible.

  @Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}
aleksandrbel
  • 1,422
  • 3
  • 20
  • 38
Nicks
  • 16,030
  • 8
  • 58
  • 65
13

First, create a LocationRequest object:

 // Create the LocationRequest object
 mLocationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

Then, make sure the user has granted permission to use location. If so, get the location from requestLocationUpdates as follows:

void getLocation() {
    Location location = null;
    if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

        /*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/

    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    mLastLocation = location;
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}

Be sure to remove the updates if you only need one location without constant monitoring. This way, you will never get a null Location.

For more information, go to http://blog.teamtreehouse.com/beginners-guide-location-android.

Johan B
  • 890
  • 3
  • 23
  • 39
rogerodipo
  • 187
  • 1
  • 9
3

I am using the below code to get location as per the latest documentation of android https://developer.android.com/training/location/retrieve-current https://developer.android.com/training/location/receive-location-updates

MainActivity.java

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CHECK_SETTINGS = 1;
private static final int REQUEST_GRANT_PERMISSION = 2;
private FusedLocationProviderClient fusedLocationClient;
LocationRequest locationRequest;
private Location currentLocation;
private LocationCallback locationCallback;
Button getUpdates,removeUpdates;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    createLocationRequest();
    settingsCheck();
    getUpdates = findViewById(R.id.button);
    removeUpdates = findViewById(R.id.button2);

    getUpdates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_GRANT_PERMISSION);
                return;
            }
            if(locationCallback==null)
                buildLocationCallback();
            if(currentLocation==null)
                fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
        }
    });
    removeUpdates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_GRANT_PERMISSION);
                return;
            }
            if(locationCallback!=null)
                fusedLocationClient.removeLocationUpdates(locationCallback);
        }
    });
}

protected void createLocationRequest() {
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

// Check for location settings
public void settingsCheck() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            Log.d("TAG", "onSuccess: settingsCheck");
            getCurrentLocation();
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                Log.d("TAG", "onFailure: settingsCheck");
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}

public void getCurrentLocation(){
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        return;
    }
    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    Log.d("TAG", "onSuccess: getLastLocation");
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        currentLocation=location;
                        Log.d("TAG", "onSuccess:latitude "+location.getLatitude());
                        Log.d("TAG", "onSuccess:longitude "+location.getLongitude());
                    }else{
                        Log.d("TAG", "location is null");
                        buildLocationCallback();
                    }
                }
            });
}

private void buildLocationCallback() {
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                // Update UI with location data
                currentLocation=location;
                Log.d("TAG", "onLocationResult: "+currentLocation.getLatitude());
            }
        };
    };
}

//called after user responds to location permission popup
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode==REQUEST_GRANT_PERMISSION){
        getCurrentLocation();
    }
}
//called after user responds to location settings popup
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("TAG", "onActivityResult: ");
    if(requestCode==REQUEST_CHECK_SETTINGS && resultCode==RESULT_OK)
        getCurrentLocation();
    if(requestCode==REQUEST_CHECK_SETTINGS && resultCode==RESULT_CANCELED)
        Toast.makeText(this, "Please enable Location settings...!!!", Toast.LENGTH_SHORT).show();
}}

XML file

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.locationexample.MainActivity">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="88dp"
    android:text="getLocationUpdates"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.502"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="RemoveLocationUpdates"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button"
    app:layout_constraintVertical_bias="0.363" /</android.support.constraint.ConstraintLayout>

Manifest File

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationexample">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

3

Android - Kotlin

If you need to get user location in android, I am using this my function and suggest it:

// Get user location after getting permission.
private fun findUserLocation() {

    if (ActivityCompat.checkSelfPermission(requireContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(requireContext(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Check location permission. Some one is missing.
    }
    else {
        val locationRequest = LocationRequest.create() // Create location request.
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY // Set priority.

        val locationCallback: LocationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                for (location in locationResult.locations) {
                    if (location != null) {

                        // TODO: Show your code here. 
                        // Such as:
                        val lat = location.latitude  
                        val lon = location.longitude
                    }
                }
            }
        }

        // Create a location provider client and send request for getting location.
        val client = LocationServices.getFusedLocationProviderClient(requireContext())
        client.requestLocationUpdates(locationRequest, locationCallback, null)
    }
}
canerkaseler
  • 6,204
  • 45
  • 38
2

If getLastLocation() is always returning null, try this hack. I have used it to solve my problem. Implement LocationListener (import com.google.android.gms.location.LocationListener) in your activity.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        Context mContext = this;

        manager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

        createLocationRequest();

        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();

}

private void createLocationRequest(){
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(SET_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}

onStart or onResume (i preferred onResume)

@Override
protected void onResume() {
    super.onResume();
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }else{
        // Showyourmesg();  
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
}

protected void startLocationUpdates(){
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest,this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

Now, in your onLocationChanged method check whether the googleApiClient is connected or not. If its connected, disconnect it, and connect again.

@Override
public void onLocationChanged(Location location) {
    Log.d("SplashAct", "LocatinChngListner, loc: " + location.getLatitude() + "," + location.getLongitude());

    if (mGoogleApiClient != null)
        if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()){
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
        } else if (!mGoogleApiClient.isConnected()){
            mGoogleApiClient.connect();
        }
}

And finally, in your onConntected() method

@Override
  public void onConnected(Bundle bundle) {

    Log.d("ACTIVITY", "ApiClient: OnConnected");

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);

    if (mLastLocation == null){
        startLocationUpdates(); // bind interface if your are not getting the lastlocation. or bind as per your requirement.
    }

    if (mLastLocation != null){
        while (latitude == 0 || longitude == 0){
            pDialog.setMessage("Getting Location");
            pDialog.show();

            latitude = mLastLocation.getLatitude();
            longitude = mLastLocation.getLongitude();

            if (latitude != 0 && longitude != 0){
                stopLocationUpdates(); // unbind the locationlistner here or wherever you want as per your requirement.
                pDialog.dismiss(); // location data received, dismiss dialog, call your method or perform your task.
            }
        }
    }
}

We are repeatedly trying to connect to googleApiClient, even if its already connected, so that we can get the lastLocation data. This will depend on the LocationRequest intervals. You can get the location data in onLocationChanged too, and perform your task from there.

beginner
  • 528
  • 4
  • 16
  • Does your while loop ever result in an endless loop, or do you always get a location? What would happen if the phone doesn't have connectivity? How can onLocationChanged() be called if there isn't a connected GoogleApiClient? It seems like you'd want to call getLastLocation() from the onLocationChanged event instead of the onConnected event. – John Ward Nov 09 '16 at 14:43
  • @JohnWard Yes i always get location and my while loop never went into endless mode although yes the there were times when even after getting location i was not able to perform further task as i was performing task on both occasions in onconnected where lastLocation == null and lastLocation != null. Now i have changed that into a if-else condition and it works perfectly fine. Connectivity? connectivity to internet or gps? connectivity to gps is totally required. I guess you cannot call onLocChange without connecting GoogleApiClient. If it gives loc in OnConctd good, else get from OnLocChngd. – beginner Dec 29 '16 at 07:15
1

If you are using Android Marshmallow (API 23) or newer version of Android, you can face same problem because permission is not granted. You should either explicitly request permission at run time for location or, if it's a test project you can grant location permission from app settings on your phone.

Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
1

Here is the exact answer and explanation.

LocationClient getLastLocation() return null

Community
  • 1
  • 1
Uddhav P. Gautam
  • 7,362
  • 3
  • 47
  • 64
1

I was getting null for location, I figured out that maps app was not installed on emulator. I installed it and enabled the device location, then problem solved

0

This is related to Amit K. Saha's answer but for me, on one of my Lollipop devices I kept getting null. So I opened up the maps app and I got the screen below asking me to turn on all that jazz to improve my location.

Once I did that once, my device was able to receive the location with just one call to getLastLocation();

I presume then one would have to ask for these permissions on app install for users who may not have used their maps app yet.

enter image description here

aleksandrbel
  • 1,422
  • 3
  • 20
  • 38
Micro
  • 10,303
  • 14
  • 82
  • 120
  • You should trigger that dialog from you app as described [here](https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient). – manfcas Apr 20 '18 at 14:58
0

i installed an emulator which have google play services and worked

Akif Kara
  • 442
  • 6
  • 14
-1

To make a single location request you can use

Method 1-> getCurrentLocation()

cancellationTokenSource = CancellationTokenSource()

val currentLocationTask = LocationServices
        .getFusedLocationProviderClient(requireContext()).getCurrentLocation(
            LocationRequest.PRIORITY_HIGH_ACCURACY,
            cancellationTokenSource.token
        )

you can cancel the request using,

cancellationTokenSource.cancel()

Method 2-> setNumUpdates(1)

mLocationRequest
        .setNumUpdates(1)
Ezhilan
  • 44
  • 4