title: GPS trace every 2 minutes (requestLocationUpdates, Timer or Handler)
body: <p>I am developing an application that needs to save every 2 minutes a trace of the GPS position of the device.<br>
  The first attempt was to use <strong>requestLocationUpdates</strong>:</p>
  
  <pre><code>locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000L, 0f, this);
  </code></pre>
  
  <p>For testing I use a <strong>Samsung Galaxy Mini (Android 2.3.5)</strong>.<br>
  If I do the test in debug mode with the USB cable connected, everything works perfect, every two minutes I get the position.<br>
  The problem is when I unplug the USB and go to the street and testing. This way I get a GPS position every second. This is too much.<br>
  After much review my code I have decided to use a Timer:</p>
  
  <pre><code>new Timer().scheduleAtFixedRate(new TimerTask(){
      @Override
      public void run() {
          Location loc=getLastBestLocation(Activity.this);
          GpsStore.save(loc);
      }   
  }, 120000L, 120000L);
  </code></pre>
  
  <p>Again, if testing the application in debug mode with the USB cable everything goes right.<br>
  If I go out and get tested if the application is in the foreground all goes well, if the application is in the background the TimerTask does not run every 2 minutes, it is stopped and when the application returns to the foreground suddenly runs all times the TimerTask it had executed normally. But everything quickly in about 1 second.</p>
  
  <p>Again after much review my code, I decided to use instead of Timer Handler:</p>
  
  <pre><code>        final Handler handler = new Handler();
          Runnable runnable = new Runnable() {
             public void run() {
                                      Location loc=getLastBestLocation(Activity.this);
                                      GpsStore.save(loc);
  
                  handler.removeCallbacks(this);
                  handler.postDelayed(this,120000L);
             }
          };
          handler.removeCallbacks(runnable);
          handler.postDelayed(runnable, 120000L);
  </code></pre>
  
  <p>As always everything works fine in debug mode with USB. What happens now when I do the test on the street is that when the application is in the foreground by handler does not run exactly every 2 minutes sometimes do it every 4 other times in 1, but when the application is in background in order Runnable using the Handler does not run every 2 minutes, never runs.</p>
  
  <p>I would use just requestLocationUpdates but is called every second.<BR>
  I need your help. Thank you.</p>