android - Restart TimerTask Failed -
i'm writing simple code start , stop timertask
. in code stop
can work can not restart timertask
. please me resolve problem.
my code:
public class mainactivity extends activity implements view.onclicklistener { private timerthread timerthread; private boolean timerhasstarted = false; private button button; private textview text; private final long starttime = 1000; private final long interval = 1; private handler handler; private runnable r; private mediaplayer mp; private timertask task; private timer timer; private long delay; private boolean play = true; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); button = (button) this.findviewbyid(r.id.button); button.setonclicklistener(this); text = (textview) this.findviewbyid(r.id.timer); mp = mediaplayer.create(this, r.raw.cpush); //mp.start(); delay = 1000; timer = new timer(); timerthread = new timerthread(); timer.scheduleatfixedrate(task, 0, 10); } public long nextlong(random rng, long n) { long bits, val; { bits = (rng.nextlong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0l); return val; } @override public void onclick(view v) { button.setbackgroundresource(r.drawable.finish); if( play ){ play = false; task.cancel(); } else{ play = true; /* restart timertask hear*/ } } public class timerthread extends timertask { @override public void run() { random rand = new random(); final long value = nextlong(rand, 9999999999999999l); runonuithread(new runnable() { @override public void run() { text.settext("" + value); } }); } } }
a timer can't run again after has been canceled, have make new object , start new one
Comments
Post a Comment