Android开发中有的时候需要延时执行某个任务,此时我们需要做一个延时操作。
下面列出来其中的几个方法
一、利用线程的sleep进行延时
- 1. new Thread(new Runnable(){
- 2. public void run(){
- 3. Thread.sleep(XXXX);
- 4. handler.sendMessage();发送一个消息,告诉主线程来去执行任务这个延时任务
- 5. }
- 6. }).start
二、使用TimerTask延时器
- 1. TimerTask task = new TimerTask(){
- 2. public void run(){
- 3. //execute the task
- 4. }
- 5. };
- 6. Timer timer = new Timer();
- timer.schedule(task, delay); // delay1000为一秒
三、android消息处理(推荐使用)
- new Handler().postDelayed(new Runnable(){
- public void run() {
- //execute the task
- }
- }, delay);