In my andorid app, I am obtaining the user's location. But when the user has no GPS on or Network, I am trying to get the last location:
if (!isGPS && !isNetwork) {
showSettingsAlert();
getLastLocation();
}
private void getLastLocation() {
try {
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
if(provider==null) { progressDialog.cancel();
showSettingsAlert(); progressDialog.cancel();}
else {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {updateUI(location);}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
The problem is, Criteria()
is already deprecated. Is there any alternative I can use in my code?
I found something like this:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(null, false);
But now getBestProvider
has null instead of criteria. How to getBestProvider when I can't use Criteria?
Create the location provider client:
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Now you can get the last location:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// do what you want with location object
}
}
});