1

I have question. is this code timer correct;]? or i can do it more easily

package timer2.android;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Timer2Activity extends Activity {

private TextView tv;
private Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = (TextView)findViewById(R.id.textView1);

    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

private void TimerMethod()
{

    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
}

long mStartTime = System.currentTimeMillis();

private Runnable Timer_Tick = new Runnable() {
    public void run() {
        final long start = mStartTime;
        long millis = System.currentTimeMillis() - start;
        int seconds = (int) (millis / 1000);
        int minutes = (int) (seconds / 60);
         seconds     = seconds % 60;

         if (seconds < 10) 
         {
            tv.setText("" + minutes + ":0" + seconds);
         } 
         else 
         {
            tv.setText("" + minutes + ":" + seconds);            
         }

         //a++;

    //This method runs in the same thread as the UI.               

    //Do something to the UI thread here

    }
};

}

Peter
  • 11
  • 3
  • This is a way, and will indeed do the trick. Ofcourse there are many other ways, but they will all do the same. – nhaarman Aug 09 '11 at 22:07

1 Answers1

0

Can't see anything wrong here. But you should use Handler for timers as it does not create additional threads. See example here: Repeat a task with a time delay?

Community
  • 1
  • 1
inazaruk
  • 74,247
  • 24
  • 188
  • 156