Three implementation methods of regularly executing tasks in Android (recommended)

In Android development, there are three implementation methods for regularly executing tasks:

1、 Use the sleep (long) method of handler and thread (not recommended, Java implementation)

2、 The handler's postdelayed (runnable, long) method (the simplest Android Implementation) is adopted

3、 Adopt the method of combining handler with timer and TimerTask (recommended for more tasks)

The following are introduced one by one:

1、 Sleep (long) method using handle and thread

Handler is mainly used to process received messages. This is only the main method. Of course, there are other methods in the handler for implementation. If you are interested, you can check the API. There is no more explanation here.

1. Define a handler class to process the received message.

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

3. Add the following statement where the thread needs to be started:

new Thread(new MyThread()).start();

4. After starting the thread, the thread sends a message every 10s.

2、 The postdelayed (runnable, long) method of handler is adopted

This implementation is simpler.

1. Define a handler class

2. Start the timer

handler. postDelayed(runnable,2000);// Execute runnable every two seconds

3. Stop timer

handler. removeCallbacks(runnable);

3、 The method of combining handler with timer and TimerTask is adopted

1. Define timer, timer task and handler handle

2. Initialize timer task

3. Start the timer

timer. schedule(task,2000,2000);

4. Stop timer

timer.cancel();

Briefly describe some of the contents mentioned in the above three steps:

1. Timer task, as its name implies, is the work to be done when the timer reaches the specified time. Here, it is to send a message to the handler for processing by the handler class.

2. java. util. Timer. Schedule (TimerTask task, long delay): this method means that the task will be executed after dalay / 1000 seconds Execute only once.

Java. Util. Timer. Schedule (TimerTask task, long delay, long period): this method is to execute the task after delay / 1000 seconds, and then execute the task again after period / 1000 seconds. This is used to cycle the task and execute it countless times. Of course, you can use timer. Cancel(); Cancels the execution of the timer.

Each timer corresponds to only one thread.

Timer does not guarantee that the task is executed accurately.

The timer class is thread safe.

The above is all the contents of the three implementation methods (recommended) for regularly executing tasks in Android brought by Xiaobian. I hope you can support more programming tips~

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>