注意点
- CountDownTimer单位是毫秒。
- 判断时注意把毫秒转成秒,直接对比毫秒会有问题。
- start()开始后,调用cancel()再start(),不是暂停后继续而是会从开始倒计时。
示例代码
以一个导计时结束弹出提示框进行关机的例子,
CountDownPowerOff.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.util.Log;
public class CountDownPowerOff extends CountDownTimer {
static private final long SHOW_POWER_OFF_SECONDS = 10L;
AlertDialog alertDialog;
Context context;
public CountDownPowerOff(long millisInFuture, Context context) {
super(millisInFuture, 1000L);
this.context = context;
}
@Override
public void onTick(long millisUntilFinished) {
long secondsUntil = millisUntilFinished / 1000L;
Log.d("", "倒计时关机:" + secondsUntil);
// 注意这里是把毫秒除以1000后得到秒后再比较,因为millisUntilFinished大部分无法整除1000, 比如值为10071
if (secondsUntil == SHOW_POWER_OFF_SECONDS) {
if (alertDialog == null) {
alertDialog = new AlertDialog.Builder(context)
.setTitle("倒计时关机")
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
cancel();
Log.d("", "取消倒计时关机");
}
}).show();
}
}
if (alertDialog != null) {
if (!alertDialog.isShowing()) {
alertDialog.show();
}
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setText(secondsUntil + "秒后关机, 点击取消");
}
}
@Override
public void onFinish() {
if (alertDialog != null) {
cancel();
alertDialog.cancel();
// shutDown();
}
}
}
// 这里把秒转成毫秒
countDownPowerOff = new CountDownPowerOff(15L * 1000L, this);
countDownPowerOff.start();
作者:帅得不敢出门