getLastKnownLocation 在 Android 10 中总是 returns null,在代码在 Android 9 中正常工作之后

getLastKnownLocation always returns null in Android 10, after code was working fine in Android 9

此代码在 Android API 29 级(Android 9 / Pie)中运行良好,但加载到 Android API 30 级(Android 10) 它不再有效。 getLastKnownLocation() returns 对所有提供者每次都为空。即使我创建了一个模拟提供者并设置了一个位置。

    public static Location getDeviceLocation(Context context)
    {
        // Request permission for location access
        PermissionRequester requester = new PermissionRequester();
        requester.addPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
        requester.requestPermissions();

        // Get first device location found from providers
        LocationManager manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

        Location deviceLocation = null;
        List<String> providers = manager.getAllProviders();
        for (String provider : providers)
        {
            deviceLocation = manager.getLastKnownLocation(provider);
            if (deviceLocation != null)
            {
                return deviceLocation;
            }
        }
        return deviceLocation;
    }

getLastLocation() 方法似乎没有被弃用。

这是 运行 在 Android 10 模拟器上的 Cucumber 步骤定义代码(Android 使用 Gherkin 和 Cucumber 进行 GUI 测试的测试代码)。

我建议你使用融合位置,它更可靠

创建时:

    FusedLocationProviderClient usedLocationClient = LocationServices.getFusedLocationProviderClient(this);

然后在这里得到结果

fusedLocationClient.getLastLocation()
    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            // Got last known location. In some rare situations this can be null.
            if (location != null) {
                // Logic to handle location object
            }
        }
    });

添加 Manifest.permission.ACCESS_BACKGROUND_LOCATION 权限导致上述代码再次按原样运行。

https://developer.android.com/training/location/permissions#background