安卓android模拟通信时间定时刷新




在使用的地方直接使用startTimer 方法即可,页面开始计时

private Long hours ;
private Long minitues ;
private Long seconds ;
Date startDate;
private void startTimer () {
   startDate = new Date(System.currentTimeMillis());
   hours = new Long(0);
   minitues = new Long(0);
   seconds = new Long(0);
   try {
      if(mTimer!=null){
         mTimer.cancel();// 退出之前的mTimer
      }
      mTimer = new Timer();// new一个Timer,否则会报错
      timerTask();
   } catch (IllegalStateException e) {
      e.printStackTrace();
   }

}

/**
 * 消息处理器的应用
 */
public Handler mHandler = new Handler() {
   @Override
   public void handleMessage(Message msg) {
      switch (msg.what) {
         case 1:
            Date endDate = new Date(System.currentTimeMillis());
            setTimeValues(startDate, endDate);
            tv_timer.setText(toTimeStr(hours) + ":" + toTimeStr(minitues) + ":" + toTimeStr(seconds));
            break;
         case 2:
            mTimer.cancel();//
            mTimer = null;
      }
      super.handleMessage(msg);
   }
};

private String toTimeStr(Long value) {
   String result = null;
   if (value < 10) {
      result = "0" + value;
   } else {
      result = value.toString();
   }
   return result;
}


void setTimeValues(Date startTime, Date endTime) {
   // 按照传入的格式生成一个simpledateformate对象
   long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
   long nh = 1000 * 60 * 60;// 一小时的毫秒数
   long nm = 1000 * 60;// 一分钟的毫秒数
   long ns = 1000;// 一秒钟的毫秒数
   long diff;
   long day = 0;
   // 获得两个时间的毫秒时间差异
   diff = endTime.getTime()-startTime.getTime()
   ;
   day = diff / nd;// 计算差多少天
   hours = diff % nd / nh;// 计算差多少小时
   minitues = diff % nd % nh / nm;// 计算差多少分钟
   seconds = diff % nd % nh % nm / ns;// 计算差多少秒
   // 输出结果
   System.out.println("时间相差:" + day + "天" + hours + "小时" + minitues
         + "分钟" + seconds + "秒。");
}

public void timerTask() {
   //创建定时线程执行更新任务
   mTimer.schedule(new TimerTask() {
      @Override
      public void run() {
      // if(count<=50){
            mHandler.sendEmptyMessage(1);// 向Handler发送消息
         //}else{
         // mHandler.sendEmptyMessage(2);// 向Handler发送消息停止继续执行
         //}
      }
   }, 1000, 1000);// 定时任务
}

public Timer mTimer = new Timer();// 定时器

 

猜你喜欢

转载自blog.csdn.net/jasonhongcn/article/details/85159831