I'm trying to get the user location using FusedLocationProviderClient
as follows:
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, null);
I get location updates in this location calls
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for (Location location : locationResult.getLocations()) {
// list of locations
}
}
};
I read that locationResult.getLocations()
retrieves a list of location objects ordered from oldest to newest, I couldn't understand that all I want is to get the user location at the moment.
Any help regarding this?
You can use locationResult.getLastLocation()
to get the most up to date location available.
From the docs: LocationResult.getLastLocation()
public Location getLastLocation ()
Returns the most recent location
available in this result, or null if no
locations are available.
You could use LocationManager
instead of FusedLocationProviderClient
. It could be more easier.
LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d("Current location", location.toString());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
//Checks permission
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
This will give you location when user moves.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.