倒计时:Timer + TimerTask + handler
倒计时:Timer + TimerTask + handler
Dialog
提示框
textViewDialog = new TextView(this);
dialogDialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setCancelable(false)
.setView(textViewDialog)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
timerDialog.cancel();//关闭
}
})
.create();
dialogDialog.show();
dialogDialog.setCanceledOnTouchOutside(false);
Timer + TimerTask
倒计时
timerDialog = new Timer(true);//倒计时
TimerTask tt = new TimerTask() {
int countTime = 10;
public void run() {
if (countTime > 0) {
countTime--;
}
Message msg = new Message();
msg.what = countTime;
handlerDialog.sendMessage(msg);
}
};
timerDialog.schedule(tt, 1000, 1000);
Handler
handlerDialog = new Handler() {
public void handleMessage(Message msg) {
if (msg.what > 0) {
//动态显示倒计时
textViewDialog.setText("\n"+" 升级固件"+"\n"+" 倒计时进入升级:"+msg.what);
} else {
//倒计时结束自动关闭
if(dialogDialog!=null){
dialogDialog.dismiss();
}
timerDialog.cancel();
}
super.handleMessage(msg);
}
};
使用
定义
TextView textViewDialog;
Dialog dialogDialog;
Handler handlerDialog;
Timer timerDialog;
放入自定义函数中使用更加方便
void RunDialog(){
textViewDialog = new TextView(this);
dialogDialog = new AlertDialog.Builder(this)
.setTitle("提示")
.setCancelable(false)
.setView(textViewDialog)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
timerDialog.cancel();//关闭--
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
timerDialog.cancel();
}
})
.create();
dialogDialog.show();
dialogDialog.setCanceledOnTouchOutside(false);
handlerDialog = new Handler() {
public void handleMessage(Message msg) {
if (msg.what > 0) {
//动态显示倒计时
textViewDialog.setText("\n"+" 倒计时:"+msg.what);
} else {
//倒计时结束自动关闭--
if(dialogDialog!=null){
dialogDialog.dismiss();
}
timerDialog.cancel();
}
super.handleMessage(msg);
}
};
timerDialog = new Timer(true);//倒计时
TimerTask tt = new TimerTask() {
int countTime = 10;
public void run() {
if (countTime > 0) {
countTime--;
}
Message msg = new Message();
msg.what = countTime;
handlerDialog.sendMessage(msg);
}
};
timerDialog.schedule(tt, 1000, 1000);
}
使用时调用
RunDialog();
效果如图
欢迎指错,一起学习