(1)handler+postDelayed() 方式
(2)handler&Timer&TimerTask 方式
(3)ScheduledExecutorService + handler 方式
(4)RxJava 方式(推荐)
(5)CountDownTimer 方式(推荐)
(1)自定义的 handler
几种方式都会用到的 handler 放前面,避免 handler 引起的内存泄露,使用 handler 时建议按如下方式让 handler 持有一个当前 Activity 的弱引用:
private LooperHandler mHandler = new LooperHandler(this);
/**
* handler 持有当前Activity的弱引用防止内存泄露
*/
private static class LooperHandler extends Handler {
WeakReference mWeakReference;
LooperHandler(LoopersActivity activity) {
mWeakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
LoopersActivity loopersActivity = mWeakReference.get();
switch (msg.what) {
case 0:
break;
case 1:
break;
}
}
}
(2)handler_postDelayed延时方法
/**
* handler_postDelayed方法实现
*/
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
Message msg = mHandler.obtainMessage(2);
mHandler.sendMessage(msg);
}
};
// handler+postDelayed方式,反复发送延时消息
private void handlerPostDelayed() {
mHandler.postDelayed(mRunnable, ONECE_TIME);
}
(3)简洁方法
new Handler().postDelayed(new Runnable(){
public void run() {
//execute the task
}
}, delay);
/**
* TimkerTask 方式实现
*/
private void timerTask() {
TimerTask task = new TimerTask() {
@Override
public void run() {
Message message = mHandler.obtainMessage(1);
mHandler.sendMessage(message);
}
};
Timer timer = new Timer();
timer.schedule(task, 0, ONECE_TIME);
}
/**
* ScheduledExecutorService 方式实现
* 此方式中handler功能与timer方式一致
*/
private ScheduledExecutorService scheduled;
private void scheduledExecutorService() {
//初始化一个线程池大小为 1 的 ScheduledExecutorService
scheduled = new ScheduledThreadPoolExecutor(1);
mStart.setEnabled(false);//在发送数据的时候设置为不能点击
mStart.setBackgroundColor(Color.GRAY);//背景色设为灰色
scheduled.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Message msg = mHandler.obtainMessage(0);
mHandler.sendMessage(msg);
}
}, 0, ONECE_TIME, TimeUnit.MILLISECONDS);
}
(1)RxJava的Observable.timer()方法(推荐)
Observable.timer(5, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe(new Action1() {
@Override
public void call(Long aLong) {
subscriber.unsubscribe();
}
});
Observable.timer(8, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
tooltip.dismiss();
}
});
Observable.timer的解释是:
(2)RxJava的Observable.interval()方法
public long TOTAL_TIME = 20000;
Observable observable = Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟,每隔一秒发送一条数据
.take(TOTAL_TIME) // 设置总共发送的次数
.map(new Func1() {// long值是从小到大,倒计时需要将值倒置
@Override
public Long call(Long aLong) {
return TOTAL_TIME - aLong;
}
})
.observeOn(AndroidSchedulers.mainThread());//操作UI主要在UI线程
final Subscriber subscriber = new Subscriber() {
@Override
public void onCompleted() {
button.setText("done!");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Long aLong) { // 接收到一条就是会操作一次UI
button.setText(aLong + "s");
}
};
observable.subscribe(subscriber);
// 注意:倒计时时间都是毫秒。倒计时总时间+间隔
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();// 调用CountDownTimer对象的start()方法开始倒计时,也不涉及到线程处理
/**
* 调用startTimer()和stopTimer()实行暂停重启倒计时。
*/
private CountDownTimer countDownTimer;
/**
* 开启倒计时
*/
private void startTimer() {
if (countDownTimer == null) {
countDownTimer = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
};
}
countDownTimer.start();
}
/**
* 结束倒计时
*/
private void stopTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
}