How to use LocationMarnager#getCurrentLocation in Android

Viewed 4513

I need to get current location information. For now I am using getLastKnownLocation but sometimes it might return null or obsolete information. I'm trying to use requestSingleUpdate but it deprecated in API level 30 and ask me to use getCurrentLocation instead. How can i achieve it?

Here is my current code for reference.

LocationManager locationManager = (LocationManager) ApplicationProvider.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

float accuracy = location.getAccuracy();
double altitude = location.getAltitude();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float speed = location.getSpeed();
1 Answers

I've solved. Here is the code.

locationManager.getCurrentLocation(
    LocationManager.GPS_PROVIDER,
    null,
    application.getMainExecutor(),
    new Consumer<Location>() {
  @Override
  public void accept(Location location) {
    // code
  }
});
Related