Android实现倒计时30分钟功能
程序员文章站
2023-12-05 22:12:40
以30分钟为例写的一个倒计时:
直接上代码
public class mainactivity extends appcompatactivity {...
以30分钟为例写的一个倒计时:
直接上代码
public class mainactivity extends appcompatactivity { private int minute = 30;//这是分钟 private int second = 0;//这是分钟后面的秒数。这里是以30分钟为例的,所以,minute是30,second是0 private textview timeview; private timer timer; private timertask timertask; //这是接收回来处理的消息 private handler handler = new handler() { public void handlemessage(message msg) { if (minute == 0) { if (second == 0) { timeview.settext("time out !"); if (timer != null) { timer.cancel(); timer = null; } if (timertask != null) { timertask = null; } } else { second--; if (second >= 10) { timeview.settext("0" + minute + ":" + second); } else { timeview.settext("0" + minute + ":0" + second); } } } else { if (second == 0) { second = 59; minute--; if (minute >= 10) { timeview.settext(minute + ":" + second); } else { timeview.settext("0" + minute + ":" + second); } } else { second--; if (second >= 10) { if (minute >= 10) { timeview.settext(minute + ":" + second); } else { timeview.settext("0" + minute + ":" + second); } } else { if (minute >= 10) { timeview.settext(minute + ":0" + second); } else { timeview.settext("0" + minute + ":0" + second); } } } } } }; @override protected void oncreate(bundle savedinstancestate) { requestwindowfeature(window.feature_no_title); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); timeview = (textview) findviewbyid(r.id.tv); timeview.settext(minute + ":" + second); timertask = new timertask() { @override public void run() { message msg = new message(); msg.what = 0; handler.sendmessage(msg); } }; timer = new timer(); timer.schedule(timertask, 0, 1000); } @override protected void ondestroy() { if (timer != null) { timer.cancel(); timer = null; } if (timertask != null) { timertask = null; } minute = -1; second = -1; super.ondestroy(); } @override protected void onstart() { super.onstart(); } @override protected void onstop() { super.onstop(); } @override protected void onresume() { super.onresume(); } @override protected void onrestart() { super.onrestart(); } @override protected void onpause() { super.onpause(); } }
ok,这就完成了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。