How to run a Runnable thread in Android at defined intervals?

后端 未结 11 2186
青春惊慌失措
青春惊慌失措 2020-11-22 02:50

I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my cod

11条回答
  •  無奈伤痛
    2020-11-22 03:30

    I think can improve first solution of Alex2k8 for update correct each second

    1.Original code:

    public void run() {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
    

    2.Analysis

    • In above cost, assume tv.append("Hello Word") cost T milliseconds, after display 500 times delayed time is 500*T milliseconds
    • It will increase delayed when run long time

    3. Solution

    To avoid that Just change order of postDelayed(), to avoid delayed:

    public void run() {
        handler.postDelayed(this, 1000);
        tv.append("Hello World");
    }
    

提交回复
热议问题