1. 代码工具类
public class BaseTimerTask extends TimerTask {
private ITimerListener mITimerListener=null;
public BaseTimerTask(ITimerListener iTimerListener) {
this.mITimerListener = iTimerListener;
}
@Override
public void run() {
if(mITimerListener!=null){
mITimerListener.onTimer();
}
}
}
public interface ITimerListener {
void onTimer();
}
2. 使用
public class mainActivity extends AppCompatActivity implements ITimerListener {
private Timer mTimer=null;
private int mCount=15; //单位s
private boolean isStart=false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTimer();
}
private void setTimer(){
isStart=false;
this.mCount=15;
mTimer=new Timer();
final BaseTimerTask task=new BaseTimerTask(this);
mTimer.schedule(task,0,1000);
}
@Override
public void onTimer() {
new Thread(() -> {
if(!isStart){
mCount--;
Log.d("kly",mCount+"");
if(mCount<0){
if(mTimer!=null){
mTimer.cancel();
mTimer=null;
isStart=true;
}
}
}
}).start();
}
}
谢谢使用!