How do I spin threads on Android?

Asked 1 years ago, Updated 1 years ago, 72 views

As a practice, I'm making an application that prints strings at intervals defined on the screen. To turn the thread

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

I used the Handler class like this, but if I run it, it will be printed only once. Please teach me how to keep turning the thread.

multithreading android

2022-09-21 23:14

1 Answers

handler = new Handler();

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

handler.postDelayed(r, 1000);

I modified it a little bit. Or how to do it like a normal thread

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

thread.start();

You can do it like this.


2022-09-21 23:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.