Reputation: 613
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 is deprecated in API level 30 and it asks me to use getCurrentLocation instead. How can I achieve this?
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();
Upvotes: 13
Views: 13581
Reputation: 816
N.B. Below is deprecated in API 30 (it still works at present) - but may be useful for older target devices
In a class that implements LocationListener, e.g. an Activity:
val locationMgr = getSystemService(Context.LOCATION_SERVICE) as LocationManager
...
locationMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null)
...
// below needed for some API versions ...
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onLocationChanged(location: Location) {
val lat = location.latitude
val lon = location.longitude
...do your stuff here :)
}
Upvotes: 1
Reputation: 613
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
}
});
Upvotes: 11