In Android development, the timer generally has the following 3 ways to implement:
1, using handler and thread of sleep (long) method
2, the use of handler postdelayed (Runnable, Long) method
3, the use of handler and timer and TimerTask combination method
Here are the following:
The sleep (long) method using handle and thread
Handler is primarily used to handle received messages. This is only the main method, of course, there are other ways to achieve handler, interested in the API can be checked, there is not too much explanation.
1. Define a handler class to handle the received message.
New Handler () { publicvoid handlemessage (Message msg) { // Things to do Super. Handlemessage (msg);} };
2. Create a new thread class that implements the Runnable interface as follows:
Public classMyThreadImplementsRunnable {@Override Public voidrun () {//TODO auto-generated Method Stub while(true) { Try{Thread.Sleep (10000);//thread paused for 10 seconds, per millisecondMessage message =NewMessage (); Message.what= 1; Handler.sendmessage (message);//Send Message}Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
3. Add the following statement where you want to start the thread:
New Thread (new MyThread ()). Start ();
4. After the thread is started, the thread sends a message every 10s.
Second, using handler postdelayed (Runnable, Long) method
This implementation is relatively simple.
1. Define a handler class
Handler handler=New Handler (); Runnable Runnable=new Runnable () { @Override publicvoid run () { // TODO auto-generated method stubs // things to do Handler.postdelayed (This, a); }};
2. Start the timer
Handler.postdelayed (Runnable, 2000); // runnable is performed every two seconds.
3. Stop Timer
Handler.removecallbacks (runnable);
Third, the use of handler and timer and TimerTask combination method
1, define timer, timer task and handler handle
Private Final New privatenew Handler () { @Override publicvoid handlemessage (Message msg) { // TODO auto-generated method stub // Super. Handlemessage (msg);} ;
2. Initialize Timer task
New TimerTask () { @Override publicvoid run () { // New Message (); = 1; Handler.sendmessage (message); } };
3. Start Timer
Timer.schedule (Task, 2000, 2000);
1. Timer task (TimerTask) as the name implies, that is, when the timer arrives at the specified time to do the work, here is to handler send a message, by the handler class for processing.
2. Java.util.Timer.schedule (timertask task, long delay): This method means that the task is executed after dalay/1000 seconds. Only once.
Java.util.Timer.schedule (timertask task, long delay, long period): This method is to say that the task is executed after delay/1000 seconds and then into period/ 1000 seconds to execute the task again, this is used for looping tasks, executed countless times, of course, you can use Timer.cancel (); Cancel the execution of the timer.
How to implement the Android timer function