計時器的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中文網其他相關文章!