title: How to change a TextView every second in Android
body: <p>I've made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make the activity Runnable and put this in run():</p>
  
  <pre><code>int position = 0;
  while (MPService.getMP() != null &amp;&amp; position&lt;MPService.duration) {
  try {
      Thread.sleep(1000);
      position = MPService.getSongPosition();
  } catch (InterruptedException e) {
      return;
  }
  
  // ... convert position to formatted minutes:seconds string ...
  
  currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
  </code></pre>
  
  <p>But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?</p>
  
  <hr>
  
  <p>new code:</p>
  
  <pre><code>private int startTime = 0;
  private Handler timeHandler = new Handler();
  private Runnable updateTime = new Runnable() {
      public void run() {
          final int start = startTime;
          int millis = appService.getSongPosition() - start;
          int seconds = (int) ((millis / 1000) % 60);
          int minutes = (int) ((millis / 1000) / 60);
          Log.d("seconds",Integer.toString(seconds)); // no problem here
          if (seconds &lt; 10) {
              // this is hit, yet the text never changes from the original value of 0:00
              currentTime.setText(String.format("%d:0%d",minutes,seconds));
          } else {
              currentTime.setText(String.format("%d:%d",minutes,seconds));
          }
          timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
      }
  
  };
  
  private ServiceConnection onService = new ServiceConnection() {
  public void onServiceConnected(ComponentName className,
          IBinder rawBinder) {
        appService = ((MPService.LocalBinder)rawBinder).getService();
  
      // start playing the song, etc. 
  
      if (startTime == 0) {
          startTime = appService.getSongPosition();
          timeHandler.removeCallbacks(updateTime);
          timeHandler.postDelayed(updateTime,1000);
      }
  }
  </code></pre>