Home > Java > javaTutorial > body text

How to Safely Update the UI from a Thread in Android Timer?

DDD
Release: 2024-11-27 12:37:14
Original
878 people have browsed it

How to Safely Update the UI from a Thread in Android Timer?

Android Thread for a Timer

Problem

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.

Solution

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:

1. CountDownTimer

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>
Copy after login

2. Handler

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>
Copy after login

3. Timer

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template