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

后端 未结 7 1549
鱼传尺愫
鱼传尺愫 2020-12-09 08:59

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

相关标签:
7条回答
  • 2020-12-09 09:23

    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.

    0 讨论(0)
  • 2020-12-09 09:23

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

    0 讨论(0)
  • 2020-12-09 09:27

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

    0 讨论(0)
  • 2020-12-09 09:29

    Just remove updated from the location manager.

    locationManager.removeUpdates(this);
    
    0 讨论(0)
  • 2020-12-09 09:34
    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.

    0 讨论(0)
  • 2020-12-09 09:38

    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

    0 讨论(0)
提交回复
热议问题