开发者社区 问答 正文

FusedLocationApi.getLastLocation始终返回null

我在手机上尝试。它始终返回null。为什么?(已授予所有权限.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'}

表现:


问题来源:Stack Overflow

展开
收起
montos 2020-03-27 22:48:37 813 分享 版权
1 条回答
写回答
取消 提交回答
  • 永远不能保证您会从中获得位置getLastLocation()。通常,这意味着没有任何应用程序没有使用GPS来获取您的位置,因此不会缓存任何内容。

    通常,您要做的就是打开google地图,或者在拥有锁定后会缓存位置的信息

    回答来源:Stack Overflow

    2020-03-27 22:48:47
    赞同 展开评论
问答地址: