Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Location Listener call very often

I am using Network Location provider. I need to call onLocationChanged method from my LocationListener only once per 1 hour. Here is my code:

MyLocationListener locationListener = new MyLocationListener();   
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3600000, 0,locationListener);

But it doesn't work. My onLocationChanged calling very often.

What parameters must I use?

like image 772
Victoria Seniuk Avatar asked Dec 20 '22 14:12

Victoria Seniuk


1 Answers

From the LocationManager#requestLocationUpdates() documentation:

Prior to Jellybean, the minTime parameter was only a hint, and some location provider implementations ignored it. From Jellybean and onwards it is mandatory for Android compatible devices to observe both the minTime and minDistance parameters.

However you can use requestSingleUpdate() with a Looper and Handler to run the updates once an hour.


Addition
To start you can read more about Loopers and Handlers here.

You are using API 8 which is a good choice, but this limits which LocationManager methods we can call since most were introduced in API 9. API 8 only have these three methods:

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)

Let's use the first method, it is the simplest.

First, create your LocationManager and LocationListener as you normally would, but in onLocationChanged() stop requesting more updates:

@Override
public void onLocationChanged(Location location) {
    mLocationManager.removeUpdates(mLocationListener);
    // Use this one location however you please
}

Second, create a couple new class variables:

private Handler mHandler = new Handler();
private Runnable onRequestLocation = new Runnable() {
    @Override
    public void run() {
        // Ask for a location
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        // Run this again in an hour
        mHandler.postDelayed(onRequestLocation, DateUtils.HOUR_IN_MILLIS);
    }
};

Of course, you ought to disable all of your callbacks in onPause() and enable them again in onResume() to prevent the LocationManager from wasting resources by acquiring unused updates in the background.


A more technical point:
If you are concerned about blocking the UI thread with the LocationManager, then you can use the second requestLocationUpdates() method to supply a specific Looper from a new Thread (say a HandlerThread).

like image 110
Sam Avatar answered Dec 30 '22 00:12

Sam