I'm developing an Android application; this App needs to send periodically (every 10 minutes) the current position (coordenates) to a web service. But ... I'm a little confused about the more correct way (and friendlier to the device battery) to do that.
I read this answer and her method _getLocation()
looks well; but I don't know whether that method could get the availability of the location I need; total availability...
I would like, if the location is not available using GSM / WIFI, application choose the GPS method.
Is that what makes this method?
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
}
Anybody know one way to get the coordinates of the device periodically... without dramatically increase battery consumption?
If you are worried about battery and not so stricted on the 10 minutes interval you could try to use PassiveProvider instead of GPS/Coarse.
Usually other applications request locations often enough so you don't need to worry about it.
If you are strict, than you could try to ask for location yourself in case one hasn't received in the past interval.
Here is an example for using the Passive Provider.
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
// Do work with new location. Implementation of this method will be covered later.
doWorkWithNewLocation(location);
}
};
long minTime = 10*60*1000;
long minDistance = 0;
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, minTime, minDistance, locationListener);
Play Services has a Low Consumption location API. You can found more info in Android Developer Site
UPDATE
Here you can found a example of Play Location Service stored in Github. Look the LocationUpdates example.
When you setup you Location Request you can change the priority, see more info here. I think that you use PRIORITY_BALANCED_POWER_ACCURACY
来源:https://stackoverflow.com/questions/28200818/get-location-coordinates-periodically-without-dramatically-increase-battery-co