Android: get only recent location, not getLastKnownLocation?

I am developing an Android application in which the current and accurate location is key. After detecting the GPS fix, it proceeds to the next step.

The problem is that I tested it outdoors and found that sometimes it just uses the location from the previous fix.

So I ask; is there any other logic to get location from LocationManager other than getLastKnownLocation? I have not yet found an example that would not look like

Location location = locationManager.getLastKnownLocation(provider); 

Thanx!

+6
source share
3 answers

Here is a sample code from the official guide (with slight modifications):

 // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 

Here you simply request updates from GPS, and as soon as the location is received, you will receive a callback.

+2
source

You can use a LocationListener and then call locationManager.requestLocationUpdates() , passing in your own listener implementation.

+2
source

Google has released a new Location API, check this link https://developer.android.com/training/location/index.html ,

the question for you is, you need to implement a location update callback to get the current location. https://developer.android.com/training/location/receive-location-updates.html

+1
source

Source: https://habr.com/ru/post/949022/


All Articles