Timer Alarmmanager in Android

Source: Internet
Author: User

There are two kinds of timers commonly used on Android, one is Java.util.Timer, the other is System Alarmservice

The explanation in the Alarmmanager's role document is that it broadcasts a specified intent for us at a particular moment. Simply put, we set a time, and then when that time comes, Alarmmanager broadcasts a intent we set for us, there are five common methods:
(1) Set (int type,long starttime,pendingintent pi);

This method is used to set a one-time alarm, the first parameter represents the alarm type, the second parameter indicates the alarm execution times, and the third parameter represents the alarm response action.

(2) setrepeating (int type,long starttime,long intervaltime,pendingintent pi);

This method is used to set a repeating alarm, the first parameter represents the alarm type, the second parameter represents the first time the alarm is executed, the third parameter represents the interval between two executions of the alarm, and the fourth parameter represents the alarm response action. Java-like timer inside Scheduleatfixedrate (timertask task, long delay, long period): Every time you execute a task's plan repeatedly The scheduled execution time for executing this task was initially determined, i.e. scheduledexecutiontime (nth time) =firstexecutetime +n*periodtime; If the nth execution of a task For some reason this time of execution is too long, after the execution of systemcurrenttime>= Scheduledexecutiontime (n+1), then do not do period interval wait, immediately execute the N+1 task, and the next n+ The Scheduledexecutiontime (n+2) of the 2-time task is still firstexecutetime+ (n+2) *periodtime which was set for the first execution of the task. Plainly, this approach is more focused on maintaining the stability of the execution frequency.

(3) setinexactrepeating (int type,long starttime,long intervaltime,pendingintent pi);

This method is also used to set a repeating alarm, similar to the second method, although the interval between the two alarms is not fixed. It is relatively more energy efficient (power-efficient), because the system may combine several similar alarms into one to execute, reducing the number of wake-up times of the device. A bit like a Java timer inside schedule (timertask task, Date Firsttime, long period): When you repeatedly execute a task's plan, The scheduled execution time for each execution of this task changes with the actual execution time of the previous one, which is Scheduledexecutiontime (n+1) =realexecutiontime (nth) +periodtime. That is, if the nth execution of a task, for some reason the execution time is too long, after the execution of the systemcurrenttime>= scheduledexecutiontime (n+1), then do not wait for a moment, immediately execute the first n+ 1 tasks, and the next n+2 task Scheduledexecutiontime (n+2) becomes realexecutiontime (n+1 times) +periodtime. Plainly, this approach is more focused on keeping the interval stable.

(4) Cancel (Pendingintent operation)

Cancel a set of alarms

(5) Settimezone (String timeZone)

Sets the default time zone for the system. Requires Android.permission.SET_TIME_ZONE permissions

Three methods of each parameter:
(1) INT type: The type of alarm clock, commonly used has 5 values:

[Java] View plaincopyprint? Alarmmanager.elapsed_realtime
Alarmmanager.elapsed_realtime_wakeup
Alarmmanager.rtc
Alarmmanager.rtc_wakeup
Alarmmanager.power_off_wakeup

Alarmmanager.elapsed_realtime
Alarmmanager.elapsed_realtime_wakeup
Alarmmanager.rtc
Alarmmanager.rtc_wakeup
Alarmmanager.power_off_wakeup

Alarmmanager.elapsed_realtime This type of alarm does not wake the system when the system goes to sleep. Until the next time the system wakes up to pass it, the time spent in the alarm is relative to the time it starts, including the sleep time, which can be obtained by calling Systemclock.elapsedrealtime (). The system value is 3  (0x00000003)    alarmmanager.elapsed_realtime_wakeup indicates that the alarm will wake up the system and perform the prompt function in the sleep state, the alarm clock also uses the relative time, the use of the same ELAPSED _realtime, the system value is 2 (0x00000002)           ALARMMANAGER.RTC indicates that the alarm is in a sleep state and this type of alarm does not wake the system. It is not delivered until the next time the system wakes up, the time spent in the alarm is absolute, and the time spent is UTC time, which can be obtained by calling System.currenttimemillis (). The system value is 1 (0x00000001)    alarmmanager.rtc_wakeup indicates that the alarm will wake up the system and perform the prompt function in the state of sleep, the alarm is used absolute time, the system value is 0 (0x00000000);    Alarmmanager.power_off_wakeup means that the alarm clock in the state of the hand machine can also be a normal function (shutdown alarm clock), so it is one of the most used in 5 states, the alarm is also used absolute time, the system value of 4 (0x00000004) However, this status appears to be affected by the SDK version, and some versions are not supported;

(2) long startTime:

The first time the alarm is executed, in milliseconds, the time can be customized, but the current time is generally used. It is important to note that this property is closely related to the first property (type), and    if the alarm corresponding to the first parameter uses a relative time (Elapsed_realtime and Elapsed_realtime_wakeup), Then this property will have to use relative time (relative to the system boot time), such as the current time is expressed as: Systemclock.elapsedrealtime ();    if the first parameter corresponds to an alarm with an absolute time (RTC, Rtc_wakeup, Power_off_wakeup), then this property will have to use absolute time, such as the current time is expressed as: System.currenttimemillis ().

(3) long intervaltime:

For the latter two methods, this property exists, indicating the interval between two alarm executions, and in milliseconds.

(4) Pendingintent PI:

Is the operation of the alarm clock, such as sending a broadcast, giving hints and so on. Pendingintent is the encapsulation class for intent. It should be noted that if the alarm is implemented by starting the service, the Pendingintent object should be acquired using the Pending.getservice (Context c,int i,intent intent,int j) method If the alarm is realized by broadcasting, the Pendingintent object should be acquired using Pendingintent.getbroadcast (Context c,int i,intent intent,int j) method. If the alarm is implemented in an activity way, the Pendingintent object should be acquired using the pendingintent.getactivity (Context c,int i,intent intent,int j) method. If these three methods are wrong, although not error, but do not see the alarm effect.

Alarmmanager Use Example: Use the user-defined broadcast to implement the alarm function, starting from the current time, every 10 minutes prompt

(1) Implementation principle: Define a Alarmmanager object in Sendactivity.java, which specifies that the object starts at the current time, and sends a broadcast to the broadcast receiver named "Myalarmreceiver" every 10 minutes, with the additional message content " You should soy sauce "; Create a broadcast sink named Myreceiver that gets the value passed from the intent object in its OnReceive method (" You should soy sauce ") and displays it with a toast component To register the Sendactivity class and broadcast sink class Myreceiver in the Androidmanifest.xml file, set the value of the Myreceiver action to "Myalarmreceiver"

(2) Code implementation:

Create a broadcast receive class Myreceiver.java, get additional information for intent in its OnReceive method msg, and display it with the toast component

[Java] View plaincopyprint?public void OnReceive (Context context,intent Intent) {

String msg = Intent.getstringextra ("msg");   Toast.maketext (Context,msg,toast.length_short). Show ();

}

public void OnReceive (Context context,intent Intent) {

String msg = Intent.getstringextra ("msg"); Toast.maketext (Context,msg,toast.length_short). Show ();

}
Create Sendactivity.java to set alarms and broadcast periodically

[Java] View plaincopyprint?//create intent object, action point to broadcast receive class, additional message string "You should soy sauce."

Intent Intent = new Intent ("Myalarmreceiver");

Intent.putextra ("msg", "You should soy sauce");

Create a Pendingintent object encapsulation intent, as is the case with broadcast, note using the Getbroadcast method

pendingintent pi = pendingintent.getbroadcast (this,0,intent,0);

Get Alarmmanager Object

Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);

Set the alarm to start at the current time, execute the Pendingintent object every 10 minutes, and note the relationship between the first parameter and the second argument

Am.setrepeating (Alarmmanager.rtc_wakeup,system.currentmillis (), 600*1000,PI);

Create intent object, action point to broadcast receive class, additional message string "You should soy sauce."

Intent Intent = new Intent ("Myalarmreceiver");

Intent.putextra ("msg", "You should soy sauce");

Create a Pendingintent object encapsulation intent, as is the case with broadcast, note using the Getbroadcast method

pendingintent pi = pendingintent.getbroadcast (this,0,intent,0);

Get Alarmmanager Object

Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);

Set the alarm to start at the current time, execute the Pendingintent object every 10 minutes, and note the relationship between the first parameter and the second argument

Am.setrepeating (Alarmmanager.rtc_wakeup,system.currentmillis (), 600*1000,PI);
Sometimes, maybe we need to turn on multiple timers at the same time, let's take a look at the following code:

[Java] View plaincopyprint? Alarmmanager am = null;
am = (Alarmmanager) context.getapplicationcontext (). Getsystemservice (Context.alarm_service);
for (int i = 0; i <; i + +) {

...  Intent i = new Intent ("xxx");  Pendingintent sender = Pendingintent.getbroadcast (Context.getapplicationcontext (), 0, I, pendingintent.flag_update_ current);  ...  Am.setrepeating (...);

}

Alarmmanager am = null;
am = (Alarmmanager) context.getapplicationcontext (). Getsystemservice (Context.alarm_service);
for (int i = 0; i <; i + +) {

... Intent i = new Intent ("xxx"); Pendingintent sender = Pendingintent.getbroadcast (Context.getapplicationcontext (), 0, I, pendingintent.flag_update_ current);... am.setrepeating (...);

}
If you do this, the timer in the back will "overwrite" the previous timer, only the last timer will be activated.

Solutions

Pendingintent.getbroadcast (context context, int requestcode, Intent Intent, int flags);

The second parameter, Requestcode, must be unique, such as a different ID, if the system requires more than one timer.

Timer Alarmmanager in Android

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.