android-初始位置中的FusedLocationClient与LocationManager
作者:互联网
在Android中,很容易在LocationManager或FusedLocationClient之间进行选择,只需选择FusedLocationClient,因为这样可以节省电量,建议将其作为最佳实践.
但是,在这种情况下,我必须获取设备的“初始位置”,或者仅获取当前/最近的已知位置.在3种不同的情况下,FusedLocationClient可能会将其视为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);
标签:google-play-services,android-location,android-fusedlocation,android 来源: https://codeday.me/bug/20191109/2011860.html