项目中遇到一个情况,先生成文件再上传;但有时候发出指令后上传会不成功,需要再发一次指令方能上传。
猜想是由于文件还没生成就执行「上传」指令了。想到要延时。Android中单纯用currentThread.sleep()方法好像是不行的,要用「Handler」。
用以下代码成功实现延时:
1
2
3
4
5
|
new Handler().postDelayed( new
Runnable(){
public
void run() {
//显示dialog
}
}, 5000 ); //5秒
|
补充:API是这么解释的:
「There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.」
参考:
http://www.cnblogs.com/meieiem/archive/2011/11/11/2245245.html
http://developer.android.com/reference/android/os/Handler.html