Android 编程下的计时器代码
同样,为了防止用户恶意的频繁发送激活码,应用中需要对用户发送激活码的时间间隔进行限制,这时就需要用到倒计时器了,大概流程是这样的:页面初始化的时候,按钮为可点击状态,用户在点击“发送激活码”后按钮变为不可点击状态,同时按钮上的文字变为倒计时状态,倒计时结束后,按钮变为可点击状态,文字变为“发送激活码”。具体逻辑看下面的代码:
package cn.sunzn.countdown;
import android.app.activity;
import android.os.bundle;
import android.os.countdowntimer;
import android.view.menu;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
public class mainactivity extends activity implements onclicklistener {
private timecount timecount;
private button btn_reget_captcha;
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
init();
}
private void init() {
initview();
initdata();
}
private void initdata() {
timecount = new timecount(60000, 1000);
}
private void initview() {
btn_reget_captcha = (button) findviewbyid(r.id.btn_reget_captcha);
btn_reget_captcha.setonclicklistener(this);
}
public boolean oncreateoptionsmenu(menu menu) {
getmenuinflater().inflate(r.menu.main, menu);
return true;
}
public void onclick(view v) {
int id = v.getid();
switch (id) {
case r.id.btn_reget_captcha:
if (btn_reget_captcha.isclickable()) {
// todo run your logic that you want to do
timecount.start();
}
break;
default:
break;
}
}
class timecount extends countdowntimer {
public timecount(long millisinfuture, long countdowninterval) {
super(millisinfuture, countdowninterval);
}
public void onfinish() {
btn_reget_captcha.settext("发送激活码");
btn_reget_captcha.setclickable(true);
}
public void ontick(long millisuntilfinished) {
btn_reget_captcha.setclickable(false);
btn_reget_captcha.settext("在" + millisuntilfinished / 1000 + "秒后点击重发激活码");
}
}
}
最后,附上工程代码:countdown