Scheduled Tasks under Android

Source: Internet
Author: User

Timing tasks in Android typically have two implementations, one using the Timer class in the Java API, and the other using Android's alarm mechanism.

Both of these approaches achieve similar results in most cases, but the timer has an obvious short board that is not quite suitable for timed tasks that require long-term running in the background. As we know, in order to make the battery more durable, each cell phone will have its own sleep strategy: for example, when the phone does not use the intelligent disconnection of the WiFi connection, according to the strength of the optical fiber automatically adjust the screen brightness, according to the phone for a long time without the operation of the CPU automatically into the sleep state, when entering the sleep state This can lead to a timer task not functioning correctly in the timers. This is not the case with the Alarn mechanism, which has the ability to wake up the CPU, which guarantees that the CPU will function every time a scheduled task is required. It is important to note that the wake-up CPU and wake-up screen are not the same concept and cannot be confused.

Timer class

Use a timer and timertask to perform a task at a certain time. The timer is an ordinary class, there are several important methods. And TimerTask is an abstract class that must implement its run method when it is used. The TimerTask Run method is similar to the thread's Run method. We use a timer to create an object of his, and then use this object's schedule method to do this interval. The schedule method has three parameters
The first parameter is an object of type TimerTask, and our implementation of the TimerTask run () method is a task to be performed periodically;
The second parameter has two types, the first is a long type, which indicates how long it takes to start execution, and the other is the date type, which indicates that execution begins after that time;
The third parameter is the period of execution, which is a long type.

The schedule method also has a two-parameter execution overload, the first argument is still TimerTask, the second is represented as a long, and is executed once, for date, after a certain time. The timer is a thread, using the schedule method to complete the dispatch of the TimerTask, multiple timertask can share a timer, that is, the timer object calls a schedule method is to create a thread, And once schedule is called, the TimerTask is unrestricted, and the timer's cancel () is used to stop the operation. Of course, after the same timer executes a cancel () method, all timer threads are terminated.
1 //True indicates that the timer runs in daemon mode (Low priority, program end timer also auto-end)2Java.util.Timer Timer =NewJava.util.Timer (true); 3TimerTask task =NewTimerTask () {4      Public voidrun () {5         //put the code in here every time you need to execute it. 6     }     7 }; 8 9 Ten //Here are a few ways to schedule a task: One  A //time is a date type: Executed once at the specified times.  - Timer.schedule (task, time);  -  the //Firsttime is a date type, and period is a long, which means that it is executed every period milliseconds starting at firsttime time.  - timer.schedule (Task, firsttime, period);  -  - //delay is a long type: From now on, the delay is performed once in milliseconds.  + timer.schedule (task, delay);  -  + //delay is long,period to long: it is executed every period milliseconds after the delay from now on.  ATimer.schedule (task, delay, period);

Alarm mechanism

1. First obtain an instance of Alarmmanager.
Alarmmanager manager = (Alarmmanager) getsystemservice (Context.alarm_service)
then call Alarmmanager's set () method to set a timed task.  longten; manager. Set (alarmmanager.elapsed_realtime_wakeup,triggeratime,pendingintent);

The first parameter in the set () method is an integer parameter that specifies the work type of the Alarmmanager, with 4 values selectable, namely Elapsed_realtime, Elapsed_realtime_wakeup, RTC, and Rtc_wakeup.

Elapsed_realtime: Indicates that the trigger time of the scheduled task is counted from the start of the system, but does not wake the CPU.

Elapsed_realtime_wakeup: It also means that the trigger time for a scheduled task starts at the start of the system, but wakes up the CPU.

RTC: Indicates that the trigger time for a scheduled task starts from 0 o'clock on January 1, 1970, but does not wake the CPU.

Rtc_wakeup: Indicates that the trigger time for a scheduled task starts from 0 o'clock on January 1, 1970, but wakes up the CPU.

Usesystemclock.elapsedrealtime ()method to get the number of milliseconds that the system has been experiencing since the time it was powered on. Usesystemclock.currenttimemills ()method to get the number of milliseconds that have elapsed since 0 o'clock January 1, 1970. The second parameter is the trigger time for the scheduled task, in milliseconds. If the first parameter uses Elapsed_realtime or Elapsed_realtime_wakeup then the time of the incoming power-up here plus the time of the deferred execution. If the first parameter uses RTC or Rtc_wakeup, then this is the time of January 1, 1970, 0 o'clock to the present, plus the time to delay execution. The third parameter is pendingintent.
int int  int int. int int) Start a service component
View Code

Here we will generally call the GetService () method or the Getbroadcast () method to obtain a pendingintent that can perform the service or broadcast. This is when the timed task is triggered. The Onstartcommand () method of the service or the broadcast OnReceive () method can be executed.

What if you want to implement a service that runs regularly in the background for a long time?

You only need to define a service and write the code that triggers the timed task to the Onstartcommand () method.

1 @Override2      Public intOnstartcommand (Intent Intent,intFlagsintStartid) {3         NewThread (NewRunnable () {4 @Override5              Public voidrun () {6                 //execute the specific logic here7             }8 }). Start ();9Alarmmanager Manager =(Alarmmanager) Getsystemservice (alarm_service);Ten         intAnhour = -* -* +;//This is the number of milliseconds in an hour.  One         LongTriggerattimer = Systemclock.elapsedrealtime () +Anhour; AIntent i =NewIntent ( This, Longrunningservice.class); -pendingintent pi = Pendingintent.getservice ( This,0I0); -Manager.Set(ALARMMANAGER.ELAPSED_REALTIME_WAKEUP,TRIGGERATTIMER,PI); the         returnSuper.onstartcommand (intent,flags,startid); -}

We start with a sub-thread in the Onstartcommand () method, so that we can perform the logical operation here, because the logical operation is also time-consuming, if it is executed in the main thread, it may

The accuracy of the scheduled task has a slight impact.

After you create the thread code, you get the instance of Alarmmanager, and then define a task that has a trigger time of one hours, and then use Pendingintent to specify that the service to handle the scheduled task is Longrunningservice, and finally call set () method to complete the setup.

Once the Longrunningservice is started, a scheduled task is set in the Onstartcommand () method, so that after an hour, the Longrunningservice will be started again. Thus forming a permanent cycle, ensure that the Longrunningservice Onstartcommand () method can be executed every one hours.

If you want to start the timer service, call the following code.

New Intent (Context,longrunningservice.  Class);    Context.startservice (intent);

It is important to note that Starting from Android4.4, the trigger time of the alarm task will become inaccurate, it is possible to delay the task after a period of time, which is the system's power-consumption optimization, the system will automatically detect how many alarm tasks are present, and then the trigger time of a few tasks close together to execute, so that the CP can be significantly reduced The number of times you are awakened, thus reducing power consumption.

If it is required that the execution time of the alarm task be accurate, only the Alarmmanager setexact () method is required to override the set () method. You can basically guarantee that the task will be executed on time.

Scheduled Tasks under Android

Related Article

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: info-contact@alibabacloud.com 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.