当前位置:   article > 正文

android自动计时器,Android中几种常用的定时器

安卓中有哪些计时器

一、三种常用的定时器

1.Handler类的postDelayed方法:

final Handler mHandler = new Handler();

Runnable r = new Runnable() {

@Override

public void run() {

//do something

//每隔1s循环执行run方法

mHandler.postDelayed(this, 1000);

}

};

//主线程中调用:

mHandler.postDelayed(r, 100);//延时100毫秒

2.用handler+timer+timeTask方法:

final Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

if (msg.what == 1) {

//do something

}

super.handleMessage(msg);

}

};

Timer timer = new Timer();

TimerTask timerTask = new TimerTask() {

@Override

public void run() {

Message message = new Message();

message.what = 1;

handler.sendMessage(message);

}

};

//主线程中调用:

timer.schedule(timerTask, 1000, 500);//延时1s,每隔500毫秒执行一次run方法

3.Thread+handler方法:

final Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

if (msg.what == 1) {

//do something

}

super.handleMessage(msg);

}

};

class MyThread extends Thread {//这里也可用Runnable接口实现

@Override

public void run() {

while (true) {

try {

Thread.sleep(1000);//每隔1s执行一次

Message msg = new Message();

msg.what = 1;

handler.sendMessage(msg);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

//主线程中调用:

new Thread(new MyThread()).start();

4.ScheduledThreadPoolExecutor方法:

private ScheduledThreadPoolExecutor mThreadPoolExecutor;

if (mThreadPoolExecutor != null) {

mThreadPoolExecutor.shutdownNow();

}

mThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

mThreadPoolExecutor.scheduleWithFixedDelay(new Runnable() {

@Override

public void run() {

}

}, 0, 500, TimeUnit.MILLISECONDS);

二、三种延时的快捷方法:

1.Handler的postDelayed方法:

new Handler().postDelayed(new Runnable() {

@Override

public void run() {

//do something

}

}, 1000); //延时1s执行

2.timer + TimerTask方法:

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

//do something

}

},1000);//延时1s执行

3.Thread方法:

new Thread(new Runnable() {

@Override

public void run() {

try {

Thread.sleep(1000);//延时1s

//do something

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}).start();

自带定时器 CountDownTimer

利用 CountDownTimer 实现一个时长为 5 秒的 View 倒计时显示,要求从 5s 开始每隔 1 秒倒计时显示到 1s

CountDownTimer countDownTimer = new CountDownTimer(totalTime, 2000) {

@Override

public void onTick(long millisUntilFinished) {

updateFileData(fileId); //执行任务

}

@Override

public void onFinish() {

if (User.getInstance().isLoginIng()) {

if (countDownTimer != null) {

countDownTimer.start();

}

}

}

};

countDownTimer.start();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/240578
推荐阅读
相关标签
  

闽ICP备14008679号