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

后端 未结 11 1993
青春惊慌失措
青春惊慌失措 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:14

    I believe for this typical case, i.e. to run something with a fixed interval, Timer is more appropriate. Here is a simple example:

    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {          
    @Override
    public void run() {
        // If you want to modify a view in your Activity
        MyActivity.this.runOnUiThread(new Runnable()
            public void run(){
                tv.append("Hello World");
            });
        }
    }, 1000, 1000); // initial delay 1 second, interval 1 second
    

    Using Timer has few advantages:

    • Initial delay and the interval can be easily specified in the schedule function arguments
    • The timer can be stopped by simply calling myTimer.cancel()
    • If you want to have only one thread running, remember to call myTimer.cancel() before scheduling a new one (if myTimer is not null)

提交回复
热议问题