如何在定义的时间间隔在 Android 中运行 Runnable 线程?

How to run a Runnable thread in Android at defined intervals?(如何在定义的时间间隔在 Android 中运行 Runnable 线程?)

本文介绍了如何在定义的时间间隔在 Android 中运行 Runnable 线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 code:

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

When I run this application the text is displayed only once. Why?

解决方案

The simple fix to your example is :

handler = new Handler();

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

handler.postDelayed(r, 1000);

Or we can use normal thread for example (with original Runner) :

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

thread.start();

You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.

More details are here http://developer.android.com/reference/android/os/Handler.html

这篇关于如何在定义的时间间隔在 Android 中运行 Runnable 线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在定义的时间间隔在 Android 中运行 Runnable 线程?

基础教程推荐