int delay = 1000; // delay for 1 sec.
int period = 10000; // repeat every 10 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
displayData(); // display the data
}
}, delay, period);
其他:
while(needToDisplayData)
{
displayData(); // display the data
Thread.sleep(10000); // sleep for 10 seconds
}
它们都不起作用(应用程序被强制关闭)。我可以尝试哪些其他选项?
最佳答案
您的代码失败,因为您在后台线程中执行 sleep ,但显示数据必须在 UI 线程中执行。
您必须从 runOnUiThread(Runnable) 运行 displayData 或定义处理程序并向其发送消息。
例如:
(new Thread(new Runnable()
{
@Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(1000);
runOnUiThread(new Runnable() // start actions in UI thread
{
@Override
public void run()
{
displayData(); // this action have to be in UI thread
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
})).start(); // the while thread will start in BG thread
关于java - 每秒运行一次循环java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687011/