使用 locationManager 时已弃用 android Criteria

问题描述 投票:0回答:1

在我的 andorid 应用程序中,我正在获取用户的位置。但是当用户没有打开 GPS 或网络时,我试图获取最后的位置:

    if (!isGPS && !isNetwork) {
        showSettingsAlert();
        getLastLocation();
    }

private void getLastLocation() {
    try {
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);

        if(provider==null) {     progressDialog.cancel();
        showSettingsAlert();     progressDialog.cancel();}
        else {
            Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {updateUI(location);}
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

问题是,

Criteria()
已被弃用。我可以在我的代码中使用任何替代方案吗?

我发现了这样的东西:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String provider = locationManager.getBestProvider(null, false);

但是现在

getBestProvider
有 null 而不是标准。当我无法使用 Criteria 时如何获取BestProvider?

android location android-location
1个回答
0
投票

创建位置提供商客户端:

FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

现在您可以获得最后的位置:

fusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    // do what you want with location object
                }
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.