计算当前时间与未来时间之间的时间差,每秒后计算一次

时间:2012-05-16 18:43:37

标签: android

我必须计算小时,分钟和秒的时差,并在每秒后更新我的启动活动时间。我正在使用此代码。

              private Handler handler=new Handler() ;
private Runnable updateTimeTask = new Runnable() {
    @Override
    public void run() {

            updateTime();
            //handler.postDelayed(updateTimeTask, 1000);

    }
    };          @Override
protected void onResume() {
    super.onResume();



    int delay = 1000; // delay for 1 sec.

    int period = 1000; // repeat every 4 sec.

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

    public void run() {

         handler.post(updateTimeTask);

    }

    }, delay, period);           }         
      private void updateTime() {

    final TextView time = (TextView) findViewById(R.id.txtViewTime);
    final TextView date = (TextView) findViewById(R.id.txtViewAlarmDesc);


    pref = new Prefs(this);
    String goal_dateTime= pref.getValue("first_goal_dateTime", "");

    Date d1 = Utils.strToDate(goal_dateTime);


    Calendar cal = Calendar.getInstance();
    if(d1!=null && d1.after(new Date()))
    {
    cal.setTime(d1);
    }
    Date cur = new Date();
    Calendar cal_cur = Calendar.getInstance();
    cal_cur.setTime(cur);


    final SimpleDateFormat formatterTime = new SimpleDateFormat("H:mm");

      long milliseconds1 = cal.getTimeInMillis();
      long milliseconds2 = cal_cur.getTimeInMillis();
      long diff = milliseconds1 - milliseconds2;
      long diffSeconds = diff / 1000;
      long diffMinutes = diff / (60 * 1000);
      long diffHours = diff / (60 * 60 * 1000);
      long diffDays = diff / (24 * 60 * 60 * 1000);


      time.setText(diffHours + " : " + diffMinutes+" : "+diffSeconds);
      date.setText(String.valueOf(diffDays+" days left to complete goal"));


}

但是,当我第一次开始活动时,它工作正常,当我从它开始另一个活动并再次回到它时,应用程序只是挂起并出现黑屏,经过很长时间它会给我一些错误,如ANR,keydispatchtimeout

我尝试了几个解决方案,例如在一个单独的线程中调用我的updateTime(),但它给了我一个错误“只有创建视图层次结构的原始线程才能触及它的视图。”

任何形式的帮助将不胜感激。非常感谢提前。

此致 Munazza K

2 个答案:

答案 0 :(得分:0)

您应该使用runOnUiThread来更新您的观看次数。

答案 1 :(得分:0)

我怀疑您的问题可能是您在离开活动时没有删除回调。我使用postDelayed而不是scheduleAtFixedRate以稍微不同的方式实现了同样的事情,如下所示:

    private Handler h = new Handler();
    private static final long TIME_EVERY_SECOND = 1000;

    private Runnable onEverySecond = new Runnable() {
            public void run() {
                updateTime();
                h.postDelayed(onEverySecond, TIME_EVERY_SECOND);
            }
        };

        @Override
        public void onPause() {
            super.onPause();

            if (h != null) {
                h.removeCallbacks(onEverySecond);
            }
        }

        @Override
        public void onResume() {
            super.onResume();
            h.postDelayed(onEverySecond, TIME_EVERY_SECOND);
        }