Andriod Scheduled Tasks

Source: Internet
Author: User

Reference Address:,

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)

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
    1. Handler Handler = new Handler () {
    2. public void Handlemessage (Message msg) {
    3. //What to do
    4. super.handlemessage (msg);
    5. }
    6. };

2. Create a new thread class that implements the Runnable interface, as follows:

[Java]View Plaincopy
  1. Public class MyThread implements Runnable {
  2. @Override
  3. public Void Run () {
  4. //TODO auto-generated method stub
  5. While (true) {
  6. try {
  7. Thread.Sleep (10000); Thread paused for 10 seconds, per millisecond
  8. Message message = new Message ();
  9. Message.what = 1;
  10. Handler.sendmessage (message); //Send Message
  11. } catch (Interruptedexception e) {
  12. //TODO auto-generated catch block
  13. E.printstacktrace ();
  14. }
  15. }
  16. }
  17. }

3. Add the following statement where you want to start the thread:

[Java]View Plaincopy
    1. 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
  1. Handler handler=New Handler ();
  2. Runnable runnable=New Runnable () {
  3. @Override
  4. public Void Run () {
  5. //TODO auto-generated method stub
  6. //What to do
  7. Handler.postdelayed (This, 2000);
  8. }
  9. };

2. Start the timer

[Java]View Plaincopy
    1. Handler.postdelayed (runnable, );   Runnable is performed every two seconds.

3. Stop Timer

[Java]View Plaincopy
    1. 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
  1. Private Final Timer timer = new timer ();
  2. Private TimerTask task;
  3. Handler Handler = new Handler () {
  4. @Override
  5. public void Handlemessage (Message msg) {
  6. //TODO auto-generated method stub
  7. //What to do
  8. super.handlemessage (msg);
  9. }
  10. };

2. Initializing Timer tasks

[Java]View Plaincopy
  1. Task = new TimerTask () {
  2. @Override
  3. public Void Run () {
  4. //TODO auto-generated method stub
  5. Message message = new Message ();
  6. Message.what = 1;
  7. Handler.sendmessage (message);
  8. }
  9. };

3. Start the timer

[Java]View Plaincopy
    1. Timer.schedule (Task, 2000);

3. Stop Timer

[Java]View Plaincopy
    1. Timer.cancel ();

Briefly describe some of the three steps mentioned above:

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.

Each timer only corresponds to a single thread.
The timer does not guarantee that the task executes very precisely.
The Timer class is thread-safe.

Iv. combination of Timer and TimerTask

Timer function is realized by combining timer with TimerTask. The specific implementation process is as follows:

The first step is to get the Timer instantiation object

Timer timer= new timer ();

Step two, instantiate the TimerTask object

TimerTask timertask = new TimerTask () {

Publicvoid Run () {

Doing something



When instantiating a TimerTask object, you need to rewrite its run () method, and then add the specific actions that need to be performed in the body of the method. For example, output a word, send a message and so on.

Step three, start the timer

Timer.schedule (TimerTask, delay, period);

This completes the process of creating and starting a timer, but in practice it may require some other means of operation.

Because the parameters of the timer are modified at some point, such as Delay,period, during the course of the program's operation. In order to use the latest and correct data in a timely manner, the existing timer needs to be closed and re-created and started with the new parameters.

The first step is to cancel the timertask and delete it in the timer timer queue.

If (TimerTask = = null) {

TimerTask. Cancel ();

Second step, restart the timer

If (timertask! = null) {

TimerTask = new TimerTask (

public void Run () {

Do something

) ;

Timer.schedule (Timetask,delay,period);

It is noteworthy that the Cancle () method is executed after the TimerTask, when restarting the timer, you must re-instantiate the TimerTask is OK, otherwise it will be reported "Java.lang.IllegalStateException: TimerTask is scheduled already "error. Each timer task TimerTask can only be placed once

Andriod Scheduled Tasks

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: 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.