java - TimerTask cancel / restart -
in app use timertask
repeat action every x seconds, want stop timertask
button , run again pressing another. here have far:
public class mainactivity extends activity { timer tempogatto = new timer(); timertempogatto timertempogatto = new timertempogatto(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final textview start = (textview)findviewbyid(r.id.start); start.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub if(event.getaction() == motionevent.action_down){ tempogatto.schedule(timertempogatto, 0, 20000); } return true; } }); final textview stop = (textview)findviewbyid(r.id.stop); stop.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub if(event.getaction() == motionevent.action_down){ tempogatto.cancel } return true; } }); (.....) private class timertempogatto extends timertask { @override public void run() { runonuithread(new runnable() { @override public void run() { //code want repeat every 20 second } }); } }
naturally when click stop textview
, start textview
restart timertask
, give me
java.lang.illegalstateexception: timer canceled
in android, threads , timers not reusable, thread in timertask can't reused. every time want re-launch timertask, need instantiate new one.
so add these lines
tempogatto = new timer(); timertempogatto = new timertempogatto();
before one
tempogatto.schedule(timertempogatto, 0, 20000);
Comments
Post a Comment