FusedLocationApi.getLastLocation always returns null(android 6.0,api 23)

freud :

I try it on my cell phone. It always returns null. Why?(all permissions were granted.ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION)

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        Toast.makeText(MainActivity.this, "Location: "+location, Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();
                    }

            });

Dependencies:

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.android.gms:play-services-location:16.0.0'}

Manifest:

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

There is never a guarantee that you get a location from getLastLocation(). Usually that means that nothing that no application has used the GPS to get your location so there is nothing cached.

Typically all you have to do is open google maps or something that a location will be cached once it has a lock

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238604&siteId=1