in Android development, there are 3 ways to implement a scheduled task:
The sleep (long) method with handler and thread (not recommended, Java implementation)
Second, using handler postdelayed (Runnable, Long) method (the simplest Android implementation)
Third, the use of handler and timer and timertask combination of methods (more tasks recommended)
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.
[Java]View Plaincopy
- Handler Handler = new Handler () {
- public void Handlemessage (Message msg) {
- //What to do
- super.handlemessage (msg);
- }
- };
2. Create a new thread class that implements the Runnable interface, as follows:
[Java]View Plaincopy
- Public class MyThread implements Runnable {
- @Override
- public Void Run () {
- //TODO auto-generated method stub
- While (true) {
- try {
- Thread.Sleep (10000); Thread paused for 10 seconds, per millisecond
- Message message = new Message ();
- Message.what = 1;
- Handler.sendmessage (message); //Send Message
- } catch (Interruptedexception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- }
- }
3. Add the following statement where you want to start the thread:
[Java]View Plaincopy
- 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
[Java]View Plaincopy
- Handler handler=New Handler ();
- Runnable runnable=New Runnable () {
- @Override
- public Void Run () {
- //TODO auto-generated method stub
- //What to do
- Handler.postdelayed (This, 2000);
- }
- };
2. Start the timer
[Java]View Plaincopy
- Handler.postdelayed (runnable, ); Runnable is performed every two seconds.
3. Stop Timer
[Java]View Plaincopy
- Handler.removecallbacks (runnable);
Third, the use of handler and timer and TimerTask combination method
1. Define timer, timer task and handler handle
[Java]View Plaincopy
- Private Final Timer timer = new timer ();
- Private TimerTask task;
- Handler Handler = new Handler () {
- @Override
- public void Handlemessage (Message msg) {
- //TODO auto-generated method stub
- //What to do
- super.handlemessage (msg);
- }
- };
2. Initializing Timer tasks
[Java]View Plaincopy
- Task = new TimerTask () {
- @Override
- public Void Run () {
- //TODO auto-generated method stub
- Message message = new Message ();
- Message.what = 1;
- Handler.sendmessage (message);
- }
- };
3. Start the timer
[Java]View Plaincopy
- Timer.schedule (Task, 2000);
3. Stop Timer
[Java]View Plaincopy
- Timer.cancel ();
3 ways to implement scheduled tasks in Android