2515天 Mr.贰呆

唯一自信的就是自己的人品。
寻求王者玩家一起开黑净化峡谷环境​​

【Android】倒计时功能简单实现及日期工具类分享

发布于 / 4853 次围观 / 0 条评论 / Android / 二呆 /

    比如某一商家搞活动需要用到倒计时功能,用Android代码简单实现其实就是用到了计时器类(Timer),主要算法封装在日期工具类里了。

1、算法

  1. /**  
  2.      * me.tongleer.com  
  3.      * 通过秒格式化时间  
  4.      * @param s  
  5.      * @return  
  6.      */  
  7.     public static String formatTimeBySecond(Integer s) {           
  8.         int hour = 0;   
  9.         int minute = 0;   
  10.         int second = 0;   
  11.         second = s;   
  12.         if (second > 60) {   
  13.             minute = second / 60;   
  14.             second = second % 60;   
  15.         }   
  16.         if (minute > 60) {   
  17.             hour = minute / 60;   
  18.             minute = minute % 60;   
  19.         }   
  20.         String strtime = hour+":"+minute+":"+second;   
  21.         return strtime;   
  22.     }  

2、倒计时方法


  1. private void countDown(){   
  2.         tvTime.setText("距离结束\n"+DateUtil.formatTimeBySecond(second));   
  3.         timer = new Timer();   
  4.         TimerTask task=new TimerTask() {   
  5.             @Override  
  6.             public void run() {   
  7.                 runOnUiThread(new Runnable() {   
  8.                     @Override  
  9.                     public void run() {   
  10.                         tvTime.setText("距离结束\n"+DateUtil.formatTimeBySecond(second));   
  11.                         if(second<=0){   
  12.                             timer.cancel();   
  13.                         }   
  14.                         second--;   
  15.                     }   
  16.                 });   
  17.             }   
  18.         };   
  19.         timer.schedule(task, 10001000);   
  20.     }  
sitemap