简体   繁体   中英

Android make method run every X seconds (involves gps and server call)

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM