Search code examples
androidlocation

Google Play Services for Location not running


I'm using FusedLocationProviderClient interface to get the current location. The dependency implementation 'com.google.android.gms:play-services-location:21.0.1' is present in the build.gradle file. Google Play Services is available (isGooglePlayServicesAvailable returns success) but it seems that it's not running. No location is found and there is no blinking icon in the status bar to indicate the location search.

But if I run in the same time the app 'Gps Test', the blinking icon appears and a location can be found. And then, my app can use the location. So, it seems that the app 'Gps Test' starts or can use the location service. How to do from an app?

This problem comes up on a device with Android 4.4. i'll try on another device with Android 11.


Solution

  • Code:

    build.gradle
    ...
    dependencies {
        ...
        implementation 'com.google.android.gms:play-services-location:21.0.1'
    }
    

    AndroidManifest.xml
    ...
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    ...
    

    MainActivity
     ...
    
        Activity mActivity = this;
    
        FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    
        Timer TM = new Timer();
        TM.schedule(new TimerTask() {
            @Override
            public void run() {                                 
    fusedLocationClient.getLastLocation().addOnSuccessListener(mActivity, new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                // show location.getLatitude() + ", " + location.getLongitude()
                            }
                        });
                    }
                }, 0, 10000);
    ...
    

    EDIT: After posting this code, I found why the Google service was not running on the device with Android Kitkat. This is because I used getLastLocation instead of getCurrentLocation. Getting the last location doesn't run the location search, that's logical.

    But that doesn't totally explain the behaviour difference between devices. Maybe, on devices with Android higher than 4.4, the last position is kept into memory. And so, a last position is always available.