I am developing an Android application in which current and precise location is key. After GPS fix is detected, it moves to the next activity.
The problem is that I tested it outdoors and found that sometimes it just uses a location from a previous fix.
So what I am asking; is there any other logic to get location from LocationManager other than by getLastKnownLocation? I haven't yet found an example that wouldn't look something like
Location location = locationManager.getLastKnownLocation(provider);
Thanx!
getLastLocation () gets a location estimate more quickly and minimizes battery usage that can be attributed to your app. However, the location information might be out of date, if no other clients have actively used location recently. getCurrentLocation () gets a fresher, more accurate location more consistently.
Get the last known location 1 Set up Google Play services. To access the fused location provider, your app's development project must include Google Play services. 2 Specify app permissions. ... 3 Create location services client. ... 4 Get the last known location. ... 5 Maintain a current best estimate. ...
There are two ways to get the current location of any Android device: Question: Which one is efficient and why? Answer: Fused Location Provider because it optimizes the device’s use of battery power. Before moving any of the above methods we will have to take location permission.
If not then ask first. Step 1: Creating an instance of LocationManager in the context of LOCATION_SERVICE. Step 2: Check that if the GPS and Network are available or not and if both are available then we use one with greater accuracy. Step 3: Creating an instance of LocationListener (package: android.location) for both (GPS and Network).
Here's the sample code from the official guide (with little 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);
In here, you just request updates from the GPS, and as soon as the location is received, you'll get a callback call.
You can use LocationListener and then call locationManager.requestLocationUpdates()
passing your own listener implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With