android – How to read location only once with locationManager (GPS and NETWORK PROVIDER) and not any more looking for updates of location?-ThrowExceptions

Exception or error:

How to read location only once with locationManager (GPS and NETWORK PROVIDER) and not any more looking for updates of location, to save battery?

How to solve:

Although requestSingleUpdate() is the technically correct answer, you should use

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, mLocationListener);

Wait for a while after getting your first location. The location tends to wobble for a few seconds. To determine if the fix is stable use, location.getAccuracy(). Once the accuracy stabilizes, call locationManager.removeUpdates(mLocationListener);

###

public LocationManager locationManager;

try { 
 locationManager.requestSingleUpdate( LocationManager.GPS_PROVIDER, new MyLocationListenerGPS(), null );  
} catch ( SecurityException e ) { e.printStackTrace(); }

public class MyLocationListenerGPS implements LocationListener {
 @Override
 public void onLocationChanged(Location location) {
 // your code and required methods go here...
}

Using ‘null’ in ‘requestSingleUpdate’ keeps the update check on the same thread (for use in a service). The method allows for you to put it in a Looper if you’re running it from an activity. I would think that using an async task would be the better approach.

###

Just remove updated from the location manager.

locationManager.removeUpdates(this);

###

Please read Obtaining User Location developer guide :
http://developer.android.com/guide/topics/location/obtaining-user-location.html

This link for best Performance

Don’t forget to specify android.permission.ACCESS_FINE_LOCATION in the Android manifest

###

To get the location only once you can refer this link and search for the requestSingleUpdate

###

Its easy just once read the loacation update like

locationManager.requestLocationUpdates(provider, 400, 1, this);

and after reading the location once called

locationManager.removeUpdates(this);

so system will not ask for location update after this and you cab save your battery.

###

Using requestSingleUpdate with your LocationManager.
For more info, official guide is interesting:
INFO

Leave a Reply

Your email address will not be published. Required fields are marked *