android - androidL how to reset a timer -
i learning use timer, , follow example in http://examples.javacodegeeks.com/android/core/os/handler/android-timer-example/.
i implement in way timer start off when user pressing button , stop when user's hand off, have coded follows:
codes:
button_right.setontouchlistener( new view.ontouchlistener() { @override public boolean ontouch(view arg0, motionevent event) { if(event.getaction()==motionevent.action_down ) { starttime = systemclock.uptimemillis(); customhandler.postdelayed(updatetimerthread, 0); if((event.getaction()==motionevent.action_up || event.getaction()==motionevent.action_cancel)) { timeswapbuff += timeinmilliseconds; customhandler.removecallbacks(updatetimerthread); } return false; } }); // setting timer private runnable updatetimerthread = new runnable() { public void run() { timeinmilliseconds = systemclock.uptimemillis() - starttime; updatedtime = timeswapbuff + timeinmilliseconds; int secs = (int) (updatedtime / 1000); int mins = secs / 60; secs = secs % 60; int milliseconds = (int) (updatedtime % 1000); tv_timing.settext("" + mins + ":" + string.format("%02d", secs) + ":" + string.format("%03d", milliseconds)); customhandler.postdelayed(this, 0); } };
questions:
everything works fine, , timer start when user presses button, keep running when holding , stop when hand off. yet discover when user presses button again, timer start off stops last time instead of resetting 0 before counting time.
if using code, how modified such timer reset 0 count on again when button being pressed again? thanks!!
digging further details in code , researching further through web, found answer , modify code follows , works.
all in all, monica introducing chronometer, seems nice! , zyoo sparkling me make removecallbacks under action_down
if(event.getaction()==motionevent.action_down ) { if(starttime == 0l) { starttime = systemclock.uptimemillis(); customhandler.removecallbacks(updatetimerthread); customhandler.postdelayed(updatetimerthread, 0); } if((event.getaction()==motionevent.action_up || event.getaction()==motionevent.action_cancel)) { // timeswapbuff += timeinmilliseconds; //remove this! customhandler.removecallbacks(updatetimerthread); starttime = 0l; } return false; private runnable updatetimerthread = new runnable() { public void run() { timeinmilliseconds = systemclock.uptimemillis() - starttime; //updatedtime = timeswapbuff + timeinmilliseconds; //remove this!! else starting stops last time! int secs = (int) (timeinmilliseconds / 1000); int mins = secs / 60; secs = secs % 60; int milliseconds = (int) (timeinmilliseconds % 1000); tv_timing.settext("" + mins + ":" + string.format("%02d", secs) + ":" + string.format("%03d", milliseconds)); customhandler.postdelayed(this, 0); } };
Comments
Post a Comment