Reputation: 81
My requirement is to check the location of the device every 10 minutes using a background service. So the basic gist of what should happen every 10 minutes is this -
What I have tried doing till now -
I don't need an entire code as the answer, I would rather appreciate a strategy I should adopt which will fulfil my requirements without hurting the battery much. As with my approach, unless and until the location is found, the GPS remains ON draining the battery constantly.
Upvotes: 3
Views: 7338
Reputation: 5052
onLocationChanged() from the LocationListener has the method - stopSelf() included, so that the service ends after receiving a location. However, this method is called a numerous times. I checked that while debugging. Is this because there are many instances of onLocationChanged() called ?
Basically, when you receive the first location, also stopping the service via stopSelf() thats okay too.
But how the onLocationChanged method being called numerous time ?
Dont you remove location updates when the service shutting down ?
Upvotes: 0
Reputation: 3173
Instead of alarm manager which is scheduling each 10 min, use the FusedLocationAPI and location request in order to get accurate location.
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);//Change to PRIORITY_HIGH_ACCURACY for more accurate.
mLocationRequest.setInterval(600000); // Update location every 10 minute
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Call this method whenever you need the location
/**
* Get the Location Detail from Fused Location API.
* @param mContext
* @return
*/
private Location getLocationDetails(Context mContext) {
Location location = null;
if (mGoogleApiClient != null) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG,"Location Permission Denied");
return null;
}else {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
return location;
}
Upvotes: 2
Reputation: 1578
try with this
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10; // 10 minute
for more info example try with this
Upvotes: 0