Timer+thread Primer, Simple Package

Source: Internet
Author: User

We often use a timer, but placing the timer on the main thread can add to the burden of the main thread.

So we prefer to use multithreading to implement a timer, and then notify the main thread to update the UI every once in a while.


General idea:

    1. Using Thread,run,handler,msg for Multithreading
    2. Using Timer,timertask to implement timer functions
Let's first implement the main thread and update the UI functionality
Create a new handler, execute the steps we define when you receive code for the specified task
Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubsuper.handleme Ssage (msg); if (msg.what = = Task_code) {//timer Action}}};
We now open another thread class, we can think of, he needs a few parameters, Handler+delay length (milliseconds) + time interval (milliseconds) + task code, for security reasons, I added the context
Public TimerThread (context context, Handler Handler, int delay,int interval, int task_code) {//TODO auto-generated Constr Uctor Stubthis.handler = Handler;mcontext = Context;this.delay = Delay;this.interval = Interval;this.task_code = Task_cod e;} @Overridepublic void Run () {//TODO auto-generated method Stubsuper.run (); timer = new timer (); Timer.schedule (New Timertas K () {@Overridepublic void Run () {//TODO auto-generated method Stubmessage msg = new Message (); msg.what = Task_code;handle R.sendmessage (msg),}}, delay, interval);//Schedule (Timertask,delay Duration,timer task duration)}
That's what it looks like. To call TimerTask,
TimerThread TimerThread = new TimerThread (this, handler,1000,1000,task_code); Timerthread.start ();
If you want to stop the timer,
TimerThread.timer.cancel ();
All right

Here's the code: →http://download.csdn.net/detail/edwardwayne/8647501

Timer+thread Primer, Simple Package

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.