语境:
我一直在使用FusedLocationProviderClient
来获取用户的位置。当手机处于高精度模式时,一切都按预期工作。但是,并非所有手机都具有高精度。那么,我怎样才能设法仅通过 GPS 获取用户位置
到目前为止我已经尝试过:
1 - 试过这个FusedLocationProviderClient
:
providerClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.e(TAG,"CALLBACK RECEIVED");
processNewLocation(locationResult.getLastLocation());
}
};
locationRequest = new LocationRequest();
locationRequest.setInterval(LocationConstant.UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setFastestInterval(LocationConstant.FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
providerClient.requestLocationUpdates(locationRequest,
locationCallback, Looper.myLooper());
当位置仅在设备中时,永远不会调用位置回调,但如果它是高精度的,则可以完美地工作(也更改setPriority()
为每个优先级并且没有运气)。
2-尝试使用位置管理器:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyLocationListener());
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, new MyLocationListener());
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
结果还是一样