如何在运行Android的一个Runnable线程? [英] How to run a Runnable thread in Android?
问题描述
我开发了一个小小的应用程序显示在Android模拟器的屏幕一些文字定义的时间间隔。我使用的Handler类,从我的code小片段:
I developed one small application to display some text at defined intervals in the android emulator screen. I am using Handler class, small 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. Please any one knows how to run a thread using Handler help me.
推荐答案
在简单的解决您的例子是:
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();
您可以考虑您的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.
更多细节在这里<一href="http://developer.android.com/reference/android/os/Handler.html">http://developer.android.com/reference/android/os/Handler.html
这篇关于如何在运行Android的一个Runnable线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!