每次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);
如果我运行这个代码,我会得到几分钟的空白显示,然后崩溃。
Logcat:
ActivityManager Reason: keyDispacthingTimeot
问题出在哪里?我想让它尽可能简单…
请帮忙!
如果你想让sthg变得非常简单,那么只需使用
Thread.currentThread();
Thread.sleep(1000);
注意:正如Adeel所说,不要在UI线程中睡眠=)
EDIT:您应该像这样实现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++;
}
}
然后实现了在UI线程上运行的onProgressUpdate
方法,并:
protected void onProgressUpdate(Integer... progress) {
int i = progress[0].intValue();
if(i%2 ==0){
myTextView.setText("true");
}
else{
myTextView.setText("false");
}
}
这是关于异步任务的文档
尝试将其添加到while循环中
线程睡眠(1000);