获取最后一个位置,有很多方法

Getting last location, so many ways

当我查看 Android 教程 and/or Android 官方文档时,似乎有多种不同的方法可以查询位置。我很困惑,因为我不确定哪种方法是正确的,或者文档是否已过时。

例如,

1) GoogleApiClient: 这样,它使用Google API客户端

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

然后它会像这样查询位置

LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

2) 位置管理器:这种方式使用位置管理器

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

3) FusedLocationApi(第二种风格):

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.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
                }
            }
        });

我们应该使用哪种方式?

FusedLocationProvider 是目前获取 Android 位置的最佳方式。 您提到了两种使用 FusedLocationManager

的方法
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

上述方法的问题是它会为您提供最后一个已知位置,该位置也可能为空,因此您也需要检查是否为空。

 mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
 mFusedLocationClient.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
            }
        }
    });

在上面的这种方法中,您正在注册一个 fusedlocationListener,它将在成功注册后调用 onSuccess 方法并提供位置对象,在设备重新启动的情况下,该对象可能再次为 null here.Usually 最后一个已知位置是null.There 还有其他一些情况。 我建议您使用第二种方法,因为它使用 fusedlocationprovider 来获取最后一个已知位置,因为它更有效。