Android Thread for a Timer
The provided code creates a timer that counts down from 5 minutes to 0:00, but it does not work as expected. The issue lies in updating the UI from within a thread other than the UI thread.
When working with threads in Android, it is essential to avoid updating the UI from non-UI threads. The following are three alternative approaches to creating a timer that counts down while ensuring UI updates are performed on the UI thread:
Example:
<code class="java">public class MainActivity extends Activity { private TextView timer1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); timer1 = findViewById(R.id.timer1); startTimer(5 * 60 * 1000); // 5 minutes in milliseconds } private void startTimer(long time) { CountDownTimer timer = new CountDownTimer(time, 1000) { @Override public void onTick(long millisUntilFinished) { int minutes = (int) (millisUntilFinished / (1000 * 60)); int seconds = (int) (millisUntilFinished / 1000) % 60; timer1.setText(String.format("%02d:%02d", minutes, seconds)); } @Override public void onFinish() { timer1.setText("00:00"); } }; timer.start(); } }</code>
Example:
<code class="java">public class MainActivity extends Activity { private Handler mHandler; private Runnable mRunnable; private int timeleft = 5 * 60; // 5 minutes @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); mRunnable = new Runnable() { @Override public void run() { if (timeleft >= 0) { int minutes = timeleft / 60; int seconds = timeleft % 60; timer1.setText(String.format("%02d:%02d", minutes, seconds)); timeleft--; } else { // Stop the timer mHandler.removeCallbacks(mRunnable); } mHandler.postDelayed(mRunnable, 1000); } }; mRunnable.run(); } }</code>
Example:
<code class="java">public class MainActivity extends Activity { private Timer timer; private TimerTask timerTask; private int timeleft = 5 * 60; // 5 minutes @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (timeleft >= 0) { int minutes = timeleft / 60; int seconds = timeleft % 60; timer1.setText(String.format("%02d:%02d", minutes, seconds)); timeleft--; } else { // Cancel the timer timer.cancel(); } } }); } }; timer.scheduleAtFixedRate(timerTask, 1000, 1000); } }</code>
The above is the detailed content of How to Safely Update the UI from a Thread in Android Timer?. For more information, please follow other related articles on the PHP Chinese website!