Timer and TimerTask packages that support pause and resume in Android

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.