0

I'm working with timer function in Android, I have the code of 1 to up timer. Please help me make it a countdown timer without clicking a button?

public class MainActivity extends Activity {

    public int time = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Declare the timer
        Timer t = new Timer();
        //Set the schedule function and rate
        t.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        TextView tv = (TextView) findViewById(R.id.main_timer_text);
                        tv.setText(String.valueOf(time));
                        time += 1;
                    }

                });
            }

        }, 0, 1000);
    }
WinEunuuchs2Unix
  • 1,801
  • 1
  • 17
  • 34
chicharp
  • 103
  • 1
  • 2
  • 11

1 Answers1

3

You can use CountDownTimer for this

new CountDownTimer(20000, 1000) {

 public void onTick(long millisUntilEnd) {
     mTextView.setText(String.valueOf(millisUntilEnd / 1000));
 }

 public void onFinish() {
     mTextView.setText("done");
 }
}.start();

This will update your time TextView each second for 20 seconds.

Josef Raška
  • 1,291
  • 10
  • 8