在Android中使用LocationManager
或FusedLocationClient
之间的决定非常简单,只需使用FusedLocationClient,因为它可以节省电量,因此建议将其作为最佳实践。
但是,我遇到的情况是我必须获取设备的“初始位置”,或者只是当前/最后已知的位置。 FusedLocationClient在3种不同的场景中可能认为是null的东西。 (see here)。
当请求位置更新时,直到设备的实际位置发生变化时才会改变。 (here)
在Android框架提供的LocationManager中,您可以通过简单地调用mLocationManager.getLastKnownLocation(provider);
轻松获取最后一个已知位置,但使用它来收听更新会花费很多功能。
这里最好的解决方案是什么?将两者结合起来是否合理?如果是,如何仅使用LocationManager获取当前位置,然后禁用它以节省电量?
你可以通过this document:
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(60000) ; // 10 seconds, in milliseconds
.setFastestInterval(10000); // 1 second, in milliseconds
if(mFusedLocationClient == null) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
locationCallback,
null /* Looper */);
}
private LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
if(location != null) {...you can get updated location
}}
//REMOVE LOCATION UPDATES
mFusedLocationClient.removeLocationUpdates(locationCallback);