android中延迟的问题

来源:互联网 发布:淘宝手机市场 编辑:程序博客网 时间:2024/05/21 12:44

   Android开发中有的时候需要延时执行某个任务,此时我们需要做一个延时操作。

下面列出来其中的几个方法

一、利用线程的sleep进行延时

[html] view plain copy
  1. 1. new Thread(new Runnable(){    
  2. 2.     public void run(){    
  3. 3.         Thread.sleep(XXXX);    
  4. 4.         handler.sendMessage();发送一个消息,告诉主线程来去执行任务这个延时任务  
  5. 5.     }    
  6. 6. }).start    
二、使用TimerTask延时器
[html] view plain copy
  1. 1. TimerTask task = new TimerTask(){    
  2. 2.     public void run(){    
  3. 3.     //execute the task     
  4. 4.     }    
  5. 5. };    
  6. 6. Timer timer = new Timer();  
  7.    timer.schedule(task, delay);// delay1000为一秒
三、android消息处理(推荐使用)
[html] view plain copy
  1. new Handler().postDelayed(new Runnable(){    
  2.     public void run() {    
  3.     //execute the task    
  4.     }    
  5.  }, delay);   

0 0
原创粉丝点击