应用场景:从 [应用启动]---->到---->[应用退出] 都一直存在的定时器,不考虑停止的周期心跳计时器。
一、定义接口
为了使工具更具有实用性,先定义一个接口,用来做事件的回调。
public interface ActionDo {
void toDo();
}
二、实现
(因为我这里写的是心跳计时器,理论上)
写一个单例类,类中的start()初始化ActionDo,同时启动第一次倒计时,reset()方法是重置倒计时的方法,具体代码实现请看注释。代码如下:
import android.os.Looper;
import android.os.Message;
/**
* 心跳计时器
*/
public class Heartbeat {
//事件标签
public final int ACTION_TAG =0xFF;
//要回调的接口
private ActionDo thisActionDo;
//单例的基本操作
private static Heartbeat myCountDownTimer;
private Heartbeat() { }
public static Heartbeat getInstance(){
//这个是不是传说中的懒汉式单例 ?
if (myCountDownTimer==null)myCountDownTimer=new Heartbeat();
return myCountDownTimer;
}
//Handler事件监听器
private android.os.Handler mHandler = new android.os.Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case ACTION_TAG:
thisActionDo.toDo();
break;
}
}
};
//首次启动心跳(倒计时)
public void start(int countDownTime,ActionDo actionDo){
thisActionDo=actionDo;
reset(countDownTime);
};
//重置倒计时
public void reset(int countDownTime){
mHandler.removeMessages(ACTION_TAG);
Message msg = mHandler.obtainMessage();
msg.what = ACTION_TAG;
mHandler.sendEmptyMessageDelayed(ACTION_TAG,countDownTime);
}
}
三、使用方法
单例启动,得到事件回调后,把事件递归到reset()方法进行下一轮操作。
Heartbeat.getInstance().start(60000,new ActionDo() {
@Override
public void toDo() {
// TODO: 2022/9/2 在这里做心跳该做的事情,比如WebSocket心跳检测这样的事情
//这里重新进入下一次的心跳(类似递归,不知道算不算递归?)
Heartbeat.getInstance().reset(60000);
}
});
很奇怪,我发的文章从来没有人看,是不是我没有开CSDN VIP ? 哈哈哈。开玩笑