Matej
Matej

Reputation: 186

LocationManager requestLocationUpdates minTime OR minDistance

I'm using Android's LocationManager and its method requestLocationUpdates like this:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, this);

As I found out both the conditions of minTime and minDistance have to be met for location update, but I need to get update every 3 seconds or 10 meters.

I tried to put 2 requests like this:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, this);

but it doesn't work, I only get update every 10 meters with this code, not every 3 seconds.

I'm working with API19 if that matters.

Upvotes: 2

Views: 9354

Answers (2)

Marco
Marco

Reputation: 124

I read this discussion for a similar problem. I had to update location every second, but setting:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);

I didn't achieve my goal. In the official documentation I read that also if you fix a timerate for updates, it could be not keeped so rigid as setted. (I can't find anymore the developper page which talk about).

To have a fixed and sure timerate for updates I found this post.

My problem was that Location updates went to update (by observers) the activity and I got error using Timer (as suggested). the error was:

Only the original thread that created a view hierarchy can touch its views.

For anyone has similar problem I suggest to use Handler:

Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            notifyLocationObservers();
        }
    }, 1000);

Upvotes: 0

Dipali Shah
Dipali Shah

Reputation: 3798

The Documentation on requestLocationUpdate() says :

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

Register for location updates using the named provider, and a pending intent.

So you should be calling it like locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, this);

But If you set minTime to 0, it will be called once when it first receives a location update, then it won't be called until you change your position in minDistance meters.

Documentation Link for Reference

EDIT

As per the Discussion with @Matej I need to get update every 10 meters even if it happened in less than 3 seconds, and update every 3 seconds even if the location didn't change by more than 10 meters

If you want to regularly requestLocationUpdates, you should use Timer and TimerTask and have requestLocationUpdates run once every 3 seconds

schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

Upvotes: 5

Related Questions