计时器的 Android 线程
提供的代码创建一个从 5 分钟倒数到 0 的计时器:00,但它没有按预期工作。问题在于从 UI 线程以外的线程内更新 UI。
在 Android 中使用线程时,必须避免从非 UI 线程更新 UI 。以下是创建倒计时计时器的三种替代方法,同时确保在 UI 线程上执行 UI 更新:
示例:
<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>
示例:
<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>
示例:
<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>
以上是如何从 Android 计时器中的线程安全地更新 UI?的详细内容。更多信息请关注PHP中文网其他相关文章!