title: Android: Timer in a Background Service
body: <p>Greetings,</p>
  
  <p>I am trying to implement a timer that sends GPS coordinates to my server every 10 seconds.</p>
  
  <p>Here is the code snippet from the Service I'm implementing:</p>
  
  <pre><code>@Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          Timer timer=new Timer();
          TimerTask tt=new TimerTask(){
              @Override
              public void run() {
                  Location loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                  sendCoords(String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()));
                  Toast.LENGTH_SHORT).show();
                  Log.i("EOH",String.valueOf(loc.getLatitude()));
              }
          };
          timer.schedule(tt,0,10000);
  
          return START_STICKY;
      }
  </code></pre>
  
  <p>Now the problem is that anything inside run() causes my app to force closed. </p>
  
  <p>Here is the LogCat dump:</p>
  
  <blockquote>
    <p>12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537): FATAL
    EXCEPTION: Timer-0 12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537):
    java.lang.RuntimeException: Can't
    create handler inside thread that has
    not called Looper.prepare() 12-28
    18:44:18.284:
    ERROR/AndroidRuntime(6537):     at
    android.os.Handler.(Handler.java:121)
    12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537):     at
    prestocab.driver.Background$2.(Background.java:83)
    12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537):     at
    prestocab.driver.Background.sendCoords(Background.java:83)
    12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537):     at
    prestocab.driver.Background$3.run(Background.java:114)
    12-28 18:44:18.284:
    ERROR/AndroidRuntime(6537):     at
    java.util.Timer$TimerImpl.run(Timer.java:289)
    12-28 18:44:18.554:
    ERROR/WindowManager(1310): return in
    removeWindowLocked</p>
  </blockquote>
  
  <p>Can anyone suggest a fix for this?</p>
  
  <p>I've tried using the locationManager onLocationChanged() function, but I can't set the interval to 10 seconds. Apparently the time specified is only a guidance and the OS determines what's best. Even when I set the interval to 100 seconds, it gives me the location every second or so. Hence the reason for me using a timer.</p>
  
  <p>I hope someone can suggest something.</p>
  
  <p>Thanks in advance,</p>