1. 程式人生 > >安卓android模擬通訊時間定時重新整理

安卓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();// 定時器