Home > Java > javaTutorial > body text

How to Implement a Countdown Timer in Android Using Threads?

DDD
Release: 2024-11-05 20:11:02
Original
491 people have browsed it

How to Implement a Countdown Timer in Android Using Threads?

Timer Thread in Android: A Comprehensive Guide

Problem:
A Java code block for creating a countdown timer thread in Android is malfunctioning. The goal is to create a timer that counts down from 5 minutes to 0:00, updating the time display on a TextView.

Solution:

1. UI Thread Update Restriction:
Threads other than the UI thread cannot directly update the user interface. In this case, the thread is attempting to modify the TextView from the background thread, which is not permissible.

2. Recommended Approaches:

  • CountDownTimer: Android provides a convenient class for countdowns, which handles UI updates automatically.
  • Handler: Schedules a task to be executed at specific intervals and provides a way to perform UI updates from a background thread.
  • Timer: Allows scheduling tasks on a separate thread, but explicitly requires thread synchronization to update UI elements.

3. Alternative Implementation Examples:

a. CountDownTimer

<code class="java">public class MainActivity extends Activity {

    Button b;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        b = (Button) findViewById(R.id.button1);

        b.setOnClickListener(v -> startTimer(120000)); // start countdown for 2 minutes
    }

    private void startTimer(long time) {
        CountDownTimer counter = new CountDownTimer(time, 1000){
            public void onTick(long millisUntilDone) {
                tv.setText("You have " + millisUntilDone + "ms");
            }

            public void onFinish() {
                tv.setText("DONE!");
            }
        }.start();
    }
}</code>
Copy after login

b. Handler

<code class="java">Handler m_handler;
Runnable m_handlerTask;
int timeLeft = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    m_handler = new Handler();
    m_handlerTask = () -> {
        if (timeLeft >= 0) {
            Log.i("timeleft", "" + timeLeft);
            timeLeft--;
        } else {
            m_handler.removeCallbacks(m_handlerTask); // cancel run
        }
        m_handler.postDelayed(m_handlerTask, 1000);
    };
    m_handlerTask.run();
}</code>
Copy after login

c. Timer

<code class="java">int timeLeft = 100;
Timer _t = new Timer();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    _t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(() -> {
                Log.i("timeleft", "" + timeLeft);
                // update UI elements here
            });
            if (timeLeft > 0) {
                timeLeft--;
            } else {
                _t.cancel();
            }
        }
    }, 1000, 1000);
}</code>
Copy after login

The above is the detailed content of How to Implement a Countdown Timer in Android Using Threads?. 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