Android延迟执行

来源:互联网 发布:暗黑钻油井升级数据 编辑:程序博客网 时间:2024/06/01 09:39

android App开发在某些情况下需要有延时功能。

常用的三种方法:

一、线程
[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    
二、延时器
[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);  
三、android消息处理
[html] view plain copy
  1. new Handler().postDelayed(new Runnable(){    
  2.     public void run() {    
  3.     //execute the task    
  4.     }    
  5.  }, delay);   

推荐使用第三种

注意:如果只使用一次延迟就需要置空线程个人习惯做法:以第一种为例

boolen running=true;

new Thread(new Runnable(){public void run(){Thread.sleep(5000);//单位毫秒
while(running){
running=false;
//progress code
}}}).start

原创粉丝点击