Вы можете использовать методы, указанные ниже, чтобы получить текущие координаты местоположения пользователя и информацию о местоположении.
//Get last known location coordinates
private void getLastLocationNewMethod() {
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//session.saveCurrentLocation("Everywhere");
return;
}
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
double myLat = location.getLatitude();
double myLon = location.getLongitude();
getAddress(myLat, myLon);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("MapDemoActivity", "Error trying to get last GPS location");
e.printStackTrace();
}
});
}
//get location name from coordinates
public void getAddress(double lat, double lng) {
String currentLocation = "";
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
Log.v("IGA", "Address" + add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}