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

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

我在我的手机上试了一下 phone。它始终 returns 为空。为什么?(所有权限都是 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 {
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'}

清单:

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

永远无法保证您从 getLastLocation() 获得位置。通常这意味着没有任何应用程序使用 GPS 获取您的位置,因此没有任何缓存。

通常你所要做的就是打开 google 地图或某个位置一旦被锁定就会被缓存的东西