当我第一次启动我的应用程序时,FusedLocationProviderClient最多需要30秒才能开始提供位置更新(即在蓝点出现之前最多30秒)。我有一个封装在LiveData中的FusedLocationProvider,如下所示,我试图找出错误但无法解决的问题。
public class LocationLiveData extends LiveData<Location> {
private final static int LOCATION_REQUEST_INTERVAL_SECONDS = 5;
private final static int MIN_DISPLACEMENT_REQUEST_METRES = 0;
private final String TAG = this.getClass().getName();
private final Context context;
private FusedLocationProviderClient fusedLocationProviderClient = null;
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
setValue(locationResult.getLastLocation());
}
};
public LocationLiveData(Context context) {
this.context = context;
}
@Override
protected void onActive() {
super.onActive();
FusedLocationProviderClient locationProviderClient = getFusedLocationProviderClient();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(TimeUnit.SECONDS.toMillis(LOCATION_REQUEST_INTERVAL_SECONDS));
locationRequest.setSmallestDisplacement(MIN_DISPLACEMENT_REQUEST_METRES);
locationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
Log.d(TAG, "Getting location...");
}
@NonNull
private FusedLocationProviderClient getFusedLocationProviderClient() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
}
return fusedLocationProviderClient;
}
@Override
protected void onInactive() {
if (fusedLocationProviderClient != null) {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
}
}
这是我的片段,它包含另一个MapFragment并在其上调用getMapAsync()。以下是相关代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_map, viewGroup, false);
mBinding.setView(this);
mBinding.setViewModel(ViewModelProviders.of(this).get(MapsViewModel.class));
FragmentManager fragmentManager = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
return mBinding.getRoot();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setInfoWindowAdapter(new InfoWindowAdapter(getLayoutInflater()));
animateCameraToUserLocation();
}
答案 0 :(得分:0)
您可以做的是,在检索gps位置之前,可以将缓存的位置与getLastLocation()
一起使用,这将为您提供最后一个已知位置,并且比等待gps信号并获取更新的位置要快,您可以随时放置一个计时器,如果5秒钟内尚未用GPS提取位置信息,则可以使用getLastLocation()
https://developer.android.com/training/location/retrieve-current.html#GetLocation