Question

I want to collect locations of the user of the app. For that I have created a Service as below.

public class UpdateLocationService extends Service implements LocationListener {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startid) {

        Log.d("Service", "UpdateLocationService started");




        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String providerFine = locationManager.getBestProvider(criteria, true);

        if (providerFine != null) {
            locationManager.requestLocationUpdates(providerFine,
                    Constant.minLocationUpdateTime,
                    Constant.minLocationUpdateDistance, this);

        }
    }

    @Override
    public void onLocationChanged(Location loc) {
        // TODO Auto-generated method stub

        Log.d("LocationListener", "onLocationChanged");

        // update Location through web-service call


    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    .......................

}

I have started the service on user log in and on Boot. I have created a BroadcastReceiver so that it starts on boot. All the functions are working fine. Now it is required to limit the location data collection from 9 am to 6 pm everyday. What is best way to implement the feature keeping my least power consumption. Is it possible to run the service only from 9 am to 6 pm everyday?

Was it helpful?

Solution

There are a few approaches.

You could have a check within the service that checks the time and registers for location updates when it is within those times, and unregisters when after. This would provide better battery consumption as you say.

Or depending on the context you could use the alarm manager and calculate the time you would like to launch your service, and you could do this when the android boots / logs in. See here for an example.

Also, consider using the 'location poller' library, as that might meet your needs as it uses WakeLocks efficiently, so is battery aware built in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top