Damir
Damir

Reputation: 56199

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

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

Upvotes: 26

Views: 44655

Answers (7)

Quentin DOMMERC
Quentin DOMMERC

Reputation: 876

Just remove updated from the location manager.

locationManager.removeUpdates(this);

Upvotes: 7

Dinesh Prajapati
Dinesh Prajapati

Reputation: 9510

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

Upvotes: 1

VikingGlen
VikingGlen

Reputation: 1715

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.

Upvotes: 7

Reno
Reno

Reputation: 33792

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);

Upvotes: 34

ArcDare
ArcDare

Reputation: 3106

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

Upvotes: 0

neeraj t
neeraj t

Reputation: 4754

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.

Upvotes: 0

u.jegan
u.jegan

Reputation: 833

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

Upvotes: 1

Related Questions