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

问题描述:

我开发了一个应用程序,用于在Android模拟器屏幕中按定义的时间间隔显示一些文本.我正在使用Handler类.这是我的代码的一个片段:

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);

或者我们可以使用普通线程作为示例(使用原始Runner):

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.

更多详细信息在这里 http://developer.android.com/reference/android/os/Handler.html