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:
- Using Thread,run,handler,msg for Multithreading
- 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