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