Search code examples
javaandroidgoogle-mapsfusedlocationproviderapi

LocationService.FusedLocation returning null only on some devices


I am trying to get the last known location of the user.

After Google API is connected, I call my function:

@Override
public void onConnected(Bundle bundle) {
    initilizeMap();
}

The function looks like this:

private void initilizeMap(){
    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null){
        ...
    }else{
        // location unknown
    }
}

I opened up the Google maps first to get the current location of the user. However, mLastLocation is still null.

The most interesting thing is that the code is working on Sony tablet. But I changed my phone today to Nexus and it is not working on this device!

How can I fix this?

P.S. I included these permissions in my manifest file:

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

and android version is 6.0.1


Solution

  • Any dangerous permissions as listed here need to be requested at run time, as shown on Requesting Permissions at Run Time otherwise you'll get a Permission Denied error which can have unexpected results in your app.

    You check a permission with: ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACCESS_FINE_LOCATION)

    it can return either PackageManager.PERMISSION_GRANTED or PackageManager.PERMISSION_DENIED

    if you get a PackageManager.PERMISSION_DENIED then you can request that permission with:

    ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_LOCATION);

    where MY_PERMISSION_REQUEST_ACCESS_LOCATION is your defined int variable that is passed to the callback of onRequestPermissionsResult where you handle the outcome of the permission allow/deny.