在达内学习的很多朋友在平时上课中总会问到各样的问题,关于Android延时执行的几种方法是大家比较关心的一个问题,下面就让达内科技的老师来为学员们介绍一下。
一、开启新线程
new Thread(new Runnable(){
public void run(){
Thread.sleep(XXXX);
handler.sendMessage(); //告诉主线程执行任务
}
}).start
二、利用定时器
TimerTask task = new TimerTask(){
public void run(){
//execute the task
}
};
Timer timer = new Timer();
timer.schedule(task, delay);
// http://www.android-study.com/jichuzhishi/536.html
三、
new Handler().postDelayed(new Runnable(){
public void run() {
//execute the task
}
}, delay);
四、利用AlarmManager,特点时刻广播指定意图 能实现,一般的简单任务不这么做。
上述内容就是Android延时执行的几种方法的内容,希望朋友们在看完本文后能有所收获。
开启线程:
一般开启线程是直接
- 1、new testThread().start(); 或 2、new Thread(testThread).start(); 或 3、GameView.this.post(testThread);
1、new testThread().start(); 或 2、new Thread(testThread).start(); 或 3、GameView.this.post(testThread);
这样来开启线程。
假如我们游戏中要做到延时开启线程就应该
- GameView.this.postDelayed(testThread, 1000); //第一个参数为线程名,第二个是时间以毫秒为单位
GameView.this.postDelayed(testThread, 1000); //第一个参数为线程名,第二个是时间以毫秒为单位
停止线程则应该
- GameView.this.getHandler().removeCallbacks(testThread); //参数为线程名