2

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

              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(),但它给了我一个错误“只有创建视图层次结构的原始线程才能触及它的视图。”</p>

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

问候, 穆纳扎 K

4

2 回答 2

0

您应该使用runOnUiThread来更新您的视图。

于 2012-05-16T18:57:36.913 回答
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);
        }
于 2012-05-16T20:47:14.917 回答