Android make method run every X seconds (involves

2019-07-08 06:33发布

问题:

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

回答1:

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.



回答2:

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