I have to calculate time difference in hours, minutes and seconds and update time on my startup activity after each second. I am using this code.
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"));
}
But when i first time start activity , it works fine and when i start another activity from it and come back to it again , application just hangs and a black screen appears, and after much time it gives me errors like ANR, keydispatchtimeout.
I have tried several solutions like calling my updateTime() in a seperate thread but it gives me an error that “Only the original thread that created a view hierarchy can touch its views.”
any kind of help will be appreciated . Many thanks in advance.
Regards,
Munazza K
I suspect your problem may be that you’re not removing your callbacks when you leave the activity. I implemented the same thing in a slightly different way using postDelayed rather than scheduleAtFixedRate as below: