今天在做需求时,要用到延时程序:自己一开始没注意UI更新的问题,直接用了延时代码,如下:
try {
Thread.currentThread();
Thread.sleep(5000);// 毫秒
}
catch (Exception e) {
}
但调试时发现UI没有更新,无论延时多久都不起作用,后来才想起来安卓的耗时操作要写在子线程里,所以将代码改成如下写法:
new Handler().postDelayed(new Runnable() {
public void run() {
// execute the task
v.dismiss();
}
}, 300);
这样写之后,程序达到预期效果。
接下来把网上的方法整理下:
// 方法1:线程
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(null);// ----告诉主线程执行任务
}
}).start();
// 方法2:延时器
TimerTask task = new TimerTask() {
public void run() {
// execute the task
}
};
Timer timer = new Timer();
timer.schedule(task, 1000);
// 方法3:消息处理机制
new Handler().postDelayed(new Runnable() {
public void run() {
// execute the task
}
}, 1000);
好了,以上就是安卓开发中常用的延时方法,实际工作中注意选择合适的。