Android Note 20170118

Source: Internet
Author: User

Create a timed task

Android's alarm mechanism.

Timed tasks can also use the Timer class provided in the Java API, but it is not very suitable for scheduled tasks that require long-term running in the background. To make the battery more durable, each cell phone will have its own hibernation strategy, and the Android phone will automatically let the CPU go to sleep for a long period of inactivity, which may cause the timer task in the timers not to function properly. Alarm, however, has the ability to wake up the CPU, which guarantees that the CPU will work properly in most cases when it is necessary to perform a scheduled task. Note: Waking the CPU and waking the screen is not a concept.

Alarmmanager manager = (alarmmanager) Getsystemservice (context.alarm_service);     long triggerattime = systemclock.elapsedrealtime () + ten *;    Manager.set (Alarmmanager.elapsed_realtime_wakeup, Triggerattime, pendingintent);

The set method receives three parameters
The first parameter is the shaping parameter, which specifies the type of work for the Alarmmanager, with 4 values selectable

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.

The elapsed_realtime_wakeup also means that the trigger time of the scheduled task is counted from the start of the system, but it wakes up the CPU.

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

Use the Systemclock.elapsedrealtime () method to obtain the number of milliseconds that the system has elapsed since the time it was powered on, using System.currenttimemillis () method to obtain the number of milliseconds that have elapsed since 0 o'clock January 1, 1970.

The second parameter represents the time, in milliseconds, that a timed task is triggered.

If the first parameter uses Elapsed_realtime or Elapsed_realtime_wakeup, then the time it takes to start the power up here plus the time to delay execution.

If the first parameter uses RTC or Rtc_wakeup, this is the time of January 1, 1970, 0 o'clock, plus the time of the deferred execution.

The third parameter is a pendingintent, which typically calls the GetService () method or the Getbroadcast () method to obtain a pendingintent that performs the service or broadcast. This allows the Onstartcommand () method of the service or the OnReceive () method of the broadcast receiver to be executed when the timed task is triggered.

Implement a service that runs regularly in the background for a long time

 Public classLongrunningserviceextendsService {@Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {        NewThread (NewRunnable () {@Override Public voidrun () {}}).        Start (); Alarmmanager Manager=(Alarmmanager) Getsystemservice (Alarm_service); intAnhour = 60 * 60 * 1000; LongTriggerattime = Systemclock.elapsedrealtime () +Anhour; Intent I=NewIntent ( This, Longrunningservice.class); Pendingintent Pi= Pendingintent.getservice ( This, 0, I, 0);        Manager.set (Alarmmanager.elapsed_realtime_wakeup, Triggerattime, pi); return Super. Onstartcommand (Intent, flags, Startid); }}

A child thread is opened in the Onstartcommand () method and a logical operation is performed here. Because the logical operation takes time, it may have a slight effect on the accuracy of the scheduled task if it is placed in the main thread

Finally, just call the following code when you want to start the timer service:

Intent Intent = new Intent (context, longrunningservice.class);

Context.startservice (Intent);

Note: Starting from the Android4.4 system, the trigger time of the alarm task will become inaccurate and it may be delayed for a period of time before the task can be executed. This is the system optimization in terms of power consumption performance. The system automatically detects how many alarm tasks are present and then executes several tasks that have a similar trigger time, which can significantly reduce the number of times the CPU wakes up, effectively prolonging battery life.

If you require the alarm task to be executed at the correct time, the Alarmmanager setexact () method is used instead of the set () method, which basically guarantees that the task can be executed on time.

Android Note 20170118

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.