Sean
Sean

Reputation: 1123

How to get gps location every 30 mins in the background

I am trying to make an app that will send your gps location to a webserver every x mins. Im confused about how I should do this. Do I use a timer or a different service to call the get gps function every x mins?

This is what I'm using to get the gps signal

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                String bestProvider = locationManager.getBestProvider(criteria,
                        false);
                LocationListener loc_listener = new LocationListener() {

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

                    }

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

                    }

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

                    }

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

                    }
                };
                try {
                    Looper.prepare();
                    locationManager.requestLocationUpdates(bestProvider, 0, 0,
                            loc_listener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Location location = locationManager
                        .getLastKnownLocation(bestProvider);

Upvotes: 0

Views: 2977

Answers (2)

Jems
Jems

Reputation: 11620

An alarm is perfect for this. You can have your application request the system to set off the alarm every 30 minutes (either manually each time or with the setRepeating() method). This alarm will go off regardless of whether your application is running at the time or not. You will need a broadcast receiver to handle the intent it generates. There is a good tutorial on alarms here.

Upvotes: 2

MByD
MByD

Reputation: 137442

You should register to the AlarmManger to start your IntentService which will get the position and send it to the server.

At the end of your service execution, set a new Alarm for 30 minutes from current time.

Upvotes: 1

Related Questions