Android, Location Request, set expiration duration doesn't work

Hesam picture Hesam · Jun 4, 2013 · Viewed 7.6k times · Source

I'm using new API of location which had been introduced in I/O 2013.

It works fine and I have no problem with its results. My problem is when I set setExpirationDuration(WHATEVER_MILLIS) to whatever millis however it works for one minutes.

This is my code:

LocationRequest locationRequest = LocationRequest.create()
                            .setInterval(10 * 60 * 1000) // every 10 minutes
                            .setExpirationDuration(10 * 1000) // After 10 seconds
                            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

When I run the app, satellite indicator will be displayed in tray so, I expect to see it just 10 seconds. However, it will be disappear after a minute.

Any suggestion or comments would be appreciated. Thanks.

Answer

Sorcerer picture Sorcerer · Dec 31, 2013

Since it seems to be a real problem in Android, a workaround could be a Handler to remove location updates manually.

    listHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                mLocationClient.removeLocationUpdates(MyActivity.this);
                //Location Updates are now removed
            }
            super.handleMessage(msg);
        }
    };

After you request for location updates (for a maximum duration of 10s) you call this Handler, of course delayed for 10s.

myLocationClient.requestLocationUpdates(...);
listHandler.sendEmptyMessageDelayed(0, 10000);

This makes sure, that after 10s your location updates are removed.