本文实例为大家分享了Android倒计时的开始与停止,剩余时分秒的展示效果,供大家参考,具体内容如下@H_502_1@
Handler handler = new Handler(); Runnable update_thread = new Runnable() { @Override public void run() { leftTime--; LogUtil.e("leftTime="+leftTime); if (leftTime > 0) { //倒计时效果展示 String formatLongToTimeStr = formatLongToTimeStr(leftTime); sureBtn.setText(formatLongToTimeStr); //每一秒执行一次 handler.postDelayed(this,1000); } else {//倒计时结束 //处理业务流程 //发送消息,结束倒计时 Message message = new Message(); message.what = 1; handlerStop.sendMessage(message); } } };
final Handler handlerStop = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: leftTime = 0; handler.removeCallbacks(update_thread); break; } super.handleMessage(msg); } };
3.页面关闭时,销毁定时器,重写onDestory方法@H_502_1@
@Override protected void onDestroy() { super.onDestroy(); leftTime = 0; handler.removeCallbacks(update_thread); }
4.开启倒计时@H_502_1@
handler.postDelayed(update_thread,1000);
public String formatLongToTimeStr(Long l) { int hour = 0; int minute = 0; int second = 0; second = l.intValue() ; if (second > 60) { minute = second / 60; //取整 second = second % 60; //取余 } if (minute > 60) { hour = minute / 60; minute = minute % 60; } String strtime = "剩余:"+hour+"小时"+minute+"分"+second+"秒"; return strtime; }
public String formatLongToTimeStr(Long date) { long day = date / (60 * 60 * 24); long hour = (date / (60 * 60) - day * 24); long min = ((date / 60) - day * 24 * 60 - hour * 60); long s = (date - day*24*60*60 - hour*60*60 - min*60); String strtime = "剩余:"+day+"天"+hour+"小时"+min+"分"+s+"秒"; return strtime; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。@H_502_1@ 原文链接:https://www.f2er.com/android/526133.html