Android Combat Simple Tutorial-the 58th gun (small example of alarmmanager usage)

Source: Internet
Author: User

I. Concepts and Related methods

There are two ways to implement timed tasks in Android, one is to use the timer class provided in the Java API, and the other is to use the Android alarm mechanism. The timer mechanism has a short board is not very suitable for those who need to run in the background long-term tasks, we know that in order to make the battery more durable, will not operate the phone for a long time, the CPU goes into hibernation, which is likely to cause the timer task does not run correctly. So we're going to focus on the alarm mechanism.

Alarmmanager, as the name implies, is a "reminder", a system-level cue service commonly used in Android, that broadcasts a specified intent for us at specific times. The simple thing is that we set a time, and then at that time, Alarmmanager broadcast a intent we set for us, usually we use pendingintent,pendingintent can be understood as intent package, The simple thing is to add a specified action on the intent. When using intent, we also need to perform startactivity, StartService, or sendbroadcast to make intent useful. And Pendingintent's words are to include this action inside.

Defines a Pendingintent object.
pendingintent pi = pendingintent.getbroadcast (this,0,intent,0);

2, there are three common methods of Alarmmanager:

(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 third parameter represents the alarm response action.

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

3, three methods of each parameter keyholder:

(1) INT type: The type of alarm clock, commonly used has 5 values:alarmmanager.elapsed_realtime, Alarmmanager.elapsed_realtime_wakeup, ALARMMANAGER.RTC, Alarmmanager.rtc_wakeup, Alarmmanager.power_off_wakeup.

alarmmanager.elapsed_realtime means that the alarm clock is not available when the phone is asleep, and the alarm is used relative to the time (starting with the system boot) and the state value is 3;

Alarmmanager.elapsed_realtime_wakeup indicates that the alarm will wake up the system and perform the prompt function, the alarm clock also uses relative time, the status value is 2;

ALARMMANAGER.RTC indicates that the alarm is not available in sleep, and the alarm is used in absolute time, that is, the current system time, the status value is 1;

Alarmmanager.rtc_wakeup means that the alarm will wake up the system and perform the prompt function when the alarm is in the state of sleep, which has an absolute time and a state value of 0.

Alarmmanager.power_off_wakeup means that the alarm clock in the mobile phone shutdown State can also function as normal, so it is one of the most used in 5 states, the alarm is also used absolute time, the status value of 4 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 System start-up time), such as the current time is expressed as: Systemclock.elapsedrealtime (); If the first parameter corresponds to an alarm that uses 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: Binding the execution 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.

Second, example 1First, we look at a simple instance of sending a small instance of the broadcast on a timed basis:Mainactivity.java:
Package Com.example.alarmmangertest;import Android.app.activity;import Android.app.alarmmanager;import Android.app.pendingintent;import android.content.intent;import android.os.bundle;/** * @author Yayun * @since September 13, 2015 * */public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {s Uper.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Intent Intent = new Intent ("Elitor_clock"  );      Intent.putextra ("msg", "Five seconds Hint message");  Defines a Pendingintent object, Pendingintent.getbroadcast contains the action of Sendbroadcast.      That is, the intent pendingintent pi = pendingintent.getbroadcast (this,0,intent,0) of the action "Elitor_clock" is sent;   Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);  Alarmmanager object//Set alarm starting from the current time, Pendingintent object pi is executed every 5s, note the relationship between the first parameter and the second parameter//5 seconds after sending the broadcast via the Pendingintent Pi object Am.setrepeating (Alarmmanager.rtc_wakeup,system.currenttimemillis (), 5*1000,PI); void android.app.AlarmManager.setRepeating (int type, long Triggeratmillis, long intervalmillis, pendingintent operation)}} 

2. Broadcast class:
Package Com.example.alarmmangertest;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import Android.util.log;import Android.widget.toast;public class MyReceiver extends Broadcastreceiver  {        @Override public      void OnReceive (context context, Intent Intent)      {          log.d (" MyTag "," Onclock ... ".........");          String msg = Intent.getstringextra ("msg");          Toast.maketext (Context,msg,toast.length_short). Show ();      }    }

3. configuration file:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.alarmmangertest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses -SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowba" Ckup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@sty Le/apptheme "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <receiver android:name=" Com.example.alarmmang Ertest. Myreceiver "> <intent-filter> <action android:name=" ElitoR_clock "/> </intent-filter> </receiver> </application></manifest> 

Run this instance:
we can see that the toast is printed every five seconds. We can change the toast to the service we want to start, so we can create a services that run regularly in the background.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat Simple Tutorial-the 58th gun (small example of alarmmanager usage)

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.