Because the timer and the TimerTask class object can only be used once, if you want to dispatch the same task multiple times, you must instantiate it again.
So, a Timerhelper class is encapsulated, and the test is available.
1 Public Abstract classTimerhelper {2 3Private Timer Mtimer =NULL;4 5 Public voidStartLongDelayLongperiod)6 {7 stop ();8 9Mtimer =NewTimer ();TenMtimer.schedule (NewTimerTask () { One @Override A Public voidrun () { - -Timerhelper. This. Run (); the } - }, delay, period); - } - + Public voidStop () - { + if(Mtimer! =NULL) { A at Mtimer.cancel (); -Mtimer =NULL; - } - } - - PublicTimerhelper () { in -Mtimer =NULL; to } + - Public Abstract voidrun (); the}
Example code:
1 Public classMainactivityextendsActivity {2 3 Private FinalString TAG = This. GetClass (). Getsimplename ();4 5 PrivateTimerhelper Mtimerhelper =NULL;6 7 @Override8 protected voidonCreate (Bundle savedinstancestate) {9 Super. OnCreate (savedinstancestate);Ten Setcontentview (r.layout.activity_main); One A /// -Mtimerhelper =NewTimerhelper () { - @Override the Public voidrun () { - -LOG.D (TAG, "Timer run-----"); - } + }; - } + A @Override at protected voidOnresume () { - -Mtimerhelper.start (500, 5000); - - Super. Onresume (); - } in - @Override to protected voidOnPause () { + - mtimerhelper.stop (); the * Super. OnPause (); $ }Panax Notoginseng}
Timer and TimerTask packages that support pause and resume in Android