如何以定义的时间间隔在 Android 中运行 Runnable 线程? [英] How to run a Runnable thread in Android at defined intervals?
问题描述
我开发了一个应用程序,用于在 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();
您可以将 runnable 对象视为可以发送到消息队列执行的命令,而将处理程序视为用于发送该命令的辅助对象.
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
这篇关于如何以定义的时间间隔在 Android 中运行 Runnable 线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!