How do I spin Runnable Trash on Android?

Asked 2 years ago, Updated 2 years ago, 134 views

We are developing an application that shows the same text at fixed intervals on the Android emulator screen. I'm writing a Handler class now.

handler = new Handler();
Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");               
    }
};
handler.postDelayed(r, 1000);

The problem is that when I launch the app, the text is displayed only once. Why is that?

android multithreading

2022-09-22 13:55

1 Answers

Fix it like below.

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

Or you can just use the thread.

Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(this);
            }
        } } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

Since the handler does not continue to operate, you must call the method so that threads continue to be called inside the handler.


2022-09-22 13:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.