2

I have a niche application that needs to send a server its location every few seconds. (Don't worry about a mobile phone's battery life). How would I make a thread or something execute every few seconds? I have a gpslistener but the name of its subclass is "onlocationchanged" which seems to only want to provide information if the location changed, I will need an updated location sent to the server every time though on an interval that I define

How would I do this?

insight appreciated

CQM
  • 42,592
  • 75
  • 224
  • 366

2 Answers2

9

Place this in onCreate of a service.

  mTimer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
           // What you want to do goes here
         }
    }, 0, REFRESH_TIME);

REFRESH_TIME is the frequency or time in milliseconds when the run repeats itself.

500865
  • 6,920
  • 7
  • 44
  • 87
  • Java Timers run in a separate thread, a more Android-y approach would be to use a Handler. On the other hand, a network request should preferably happen in a separate thread anyway.. – Delyan Oct 08 '11 at 01:48
  • Thank you, this works great... Just had to change like this : new Timer().scheduleAtFixedRate(new TimerTask() { – Christian Jun 14 '15 at 06:48
1

You cannot just ask android for the current position. GPS takes some time and may not be available. This is stated in this post.

What you can do is use a timer like the one mentioned by user500865, and then request the last known location like this

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1, this);
Location l = null;
l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

You can keep track of the last location and do some logic if the new location is different or the same.

The method requestLocationUpdates has the following parameters:

minTime -the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.

minDistance -the minimum distance interval for notifications, in meters

Use these to customize how often you want to get a location update

Community
  • 1
  • 1
Mike L.
  • 589
  • 6
  • 16