简体   繁体   中英

I have an error in a thread making time “run” (update every second)

Here is my code:

public void run() {
        try {
            while (!isInterrupted()) {
                Thread.sleep(1000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        } catch (InterruptedException e) {
        }
    }
};
thread.start();

The Thread is called Thread and I want to display the time in a TextView called TextView . There is some error in the Thread because even though the time displays in the TextView , it does not update every second. Thanks

As stated, you should use Handler with Runnable , here is an example with your code:

final Handler handler = new Handler();
final Runnable task = new Runnable() {
    @Override
    public void run() {
        //Your code
        handler.postDelayed(this, 1000);
    }
};
handler.postDelayed(task, 1000);

More info about Handlers, in the doc.

use Runnable And Handler

Runnable runnable = new Runnable() {
    @Override
    public void run() {

        Date time = Calendar.getInstance().getTime();
        textView.setText(DateFormat.format("hh:mm", time));

        handler.postDelayed(this, 1000);
    }
};

Handler handler = new Handler();
handler.post(runnable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM