Android: simple time counter
You can introduce flag. Something like isPaused
. Trigger this flag whenever 'Pause' button pressed. Check flag value in your timer task. Success.
Timer T=new Timer();T.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { myTextView.setText("count="+count); count++; } }); } }, 1000, 1000); onClick(View v) { //this is 'Pause' button click listener T.cancel(); }
Chekout this example, that uses the Chronometer class: http://android-er.blogspot.com/2010/06/android-chronometer.html
Using the Chronometer class will save you managing the thread yourself.
This way it is much simpler. It is a feature made available on the android developer site. Link
public void initCountDownTimer(int time) { new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { textView.setText("seconds remaining: " + millisUntilFinished / 1000); } public void onFinish() { textView.setText("done!"); } }.start();}
Kotlin Version
fun initCountDownTimer(time: Int) {object : CountDownTimer(30000, 1000) { override fun onTick(millisUntilFinished: Long) { textView.setText("seconds remaining: " + millisUntilFinished / 1000) } override fun onFinish() { textView.setText("done!") }}.start()
}