自动执行信息每5秒 [英] Auto execute message every 5 seconds
本文介绍了自动执行信息每5秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的Android。谁能告诉我如何执行信息每5秒。我已经试过这code,但它没有出现在我的模拟器什么。我应该怎么做呢?
,而(真){
Toast.makeText(这一点,喜,Toast.LENGTH_SHORT).show();
尝试{
视频下载(5000);
}赶上(InterruptedException的E){
// TODO自动生成catch块
e.printStackTrace();
}
}
解决方案
您不应该从GUI线程调用Thread.sleep()方法。从来没有做到这一点。使用一个处理程序这样的东西。
专用处理器处理器=新的处理程序();
私人Runnable接口可运行=新的Runnable(){
公共无效的run(){
doStuff();
/ *
*现在注册它运行下一次
* /
handler.postDelayed(这一点,1000);
}
};
我preFER这种方式,因为Timer类引入了一个新的线程,它现在是公平的做到这一点使用的定时器。
I am new to Android. Can anyone tell me how to execute a message every 5 seconds. I have tried this code, but it's not showing anything on my emulator. What should I be doing instead?
while(true) {
Toast.makeText(this, "hi", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
解决方案
You should not call Thread.sleep() from the GUI thread. Never do this. Use a handler for such thing.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
I prefer this way to using timers because the Timer class introduces a new thread and it is now fair to do this.
这篇关于自动执行信息每5秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文