我想在我的 while 循环中等待 1 秒,每次它在循环中。
我尝试使用 Runnable:
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
int i=0;
while(i<10){
if(i%2 ==0){
myTextView.setText("true");
}
else{
myTextView.setText("false");
}
i++;
}
}
}, 1000);
如果我运行这段代码,我会出现几分钟的空白显示,然后崩溃。
日志:
ActivityManager Reason: keyDispacthingTimeot
问题是什么? 我想让它尽可能简单......
请帮忙!
最佳答案
如果你想让 sthg 变得非常简单,那么就使用
Thread.currentThread();
Thread.sleep(1000);
注意:正如 Adeel 所说,不要在 UI 线程中休眠 =)
编辑:你应该像这样实现 sthg:
我想你想使用 asyncTask
, 和 publishprogress
每一个秒。所以自己做asyncTask<Void, Integer, Void>
,并在 doInbackground
上方法:
protected Void doInBackground(Void... params) {
int i=0;
while(i<10){
Thread.currentThread();
try{
Thread.sleep(1000);
}catch(Exception e){
return null;
}
publishProgress(new Integer(i));
i++;
}
}
然后执行onProgressUpdate
在 UI 线程上运行的方法,以及:
protected void onProgressUpdate(Integer... progress) {
int i = progress[0].intValue();
if(i%2 ==0){
myTextView.setText("true");
}
else{
myTextView.setText("false");
}
}
这是关于 asynctasks 的文档
关于android - 如何等待代码在 Android 中执行? Runnable 对我来说失败了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11773897/