AlarmManager简介

来源:互联网 发布:软件研发部工作内容 编辑:程序博客网 时间:2024/06/14 09:39
原文:http://developer.android.com/reference/android/app/AlarmManager.html
public class

AlarmManager

extends Object
java.lang.Object   ?android.app.AlarmManager

Class Overview

This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, theIntent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. 

Alarm Manager 发出的消息在被手机Receiver的onReceive()处理时,它会holds a CPU wake lock ,以避免手机此时进入休眠,在调用完成后,它会释放该锁,此时手机又有机会进入休眠了。

If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

如你在你的Receiver的onReceive()中调用Context.startService()方法,那么可以在该Service还没启动起来,手机就sleep了,你需要另外是wake lock策略来来确保手机在sleep前,该Service已经启动。关于此请参照PowerManager简介

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Alarm Manager有个很好的特性就是即使在你的应用程序真正退出或手机休眠时,它仍然起作用。

You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.ALARM_SERVICE).

AlarmManager会在Intent中另外携带一个Intent.EXTRA_ALARM_COUNT,以表示对于该Intent已经有多少个Alarm被累计,这里的累计,是指在type为ELAPSED_REALTIMERTC时,因为设备处于休眠无法激活Alarm,无法发送Intent,从而进行累计.普通情况下该值为1.

Summary

ConstantsintELAPSED_REALTIMEAlarm time in SystemClock.elapsedRealtime() (time since boot, including sleep).
基于SystemClock.elapsedRealtime(),手机休眠时,即使时间到期也不起作用,此时不能发送我们预设的IntentintELAPSED_REALTIME_WAKEUPAlarm time in SystemClock.elapsedRealtime() (time since boot, including sleep), which will wake up the device when it goes off.
基于SystemClock.elapsedRealtime(),手机休眠时,如果时间到期,设备能被唤醒,并发送我们预设的IntentlongINTERVAL_DAY longINTERVAL_FIFTEEN_MINUTESAvailable inexact recurrence intervals recognized by setInexactRepeating(int, long, long, PendingIntent)longINTERVAL_HALF_DAY longINTERVAL_HALF_HOUR longINTERVAL_HOUR intRTCAlarm time in System.currentTimeMillis() (wall clock time in UTC).
基于System.currentTimeMillis(),手机休眠时,即使时间到期也不起作用,此时不能发送我们预设的IntentintRTC_WAKEUPAlarm time in System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.基于System.currentTimeMillis(),手机休眠时,如果时间到期,设备能被唤醒,并发送我们预设的Intent关于SystemClock.elapsedRealtime()和System.currentTimeMillis()请参照《SystemClock
Public Methodsvoidcancel(PendingIntent operation)
Remove any alarms with a matching Intent.
voidset(int type, long triggerAtTime, PendingIntent operation)
Schedule an alarm.
voidsetInexactRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour.
voidsetRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
Schedule a repeating alarm.
voidsetTime(long millis)
Set the system wall clock time.
voidsetTimeZone(String timeZone)
Set the system default time zone.
主要函数

public void set (int type, long triggerAtTime, PendingIntent operation)

Since: API Level 1

Schedule an alarm. Note: for timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler. If there is already an alarm scheduled for the same IntentSender, it will first be canceled.

If the time occurs in the past, the alarm will be triggered immediately. If there is already an alarm for this Intent scheduled (with the equality of two intents being defined by filterEquals(Intent)), then it will be removed and replaced by this one.

The alarm is an intent broadcast that goes to a broadcast receiver that you registered with registerReceiver(BroadcastReceiver, IntentFilter) or through the <receiver> tag in an AndroidManifest.xml file.

Alarm intents are delivered with a data extra of type int called Intent.EXTRA_ALARM_COUNT that indicates how many past alarm events have been accumulated into this intent broadcast. Recurring alarms that have gone undelivered because the phone was asleep may have a count greater than one when delivered.

Parameters
typeOne of ELAPSED_REALTIMEELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP.triggerAtTimeTime the alarm should go off, using the appropriate clock (depending on the alarm type).operationAction to perform when the alarm goes off; typically comes from IntentSender.getBroadcast().
public void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
Since: API Level 3

Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour. These alarms are more power-efficient than the strict recurrences supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' phase to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.

Your alarm's first trigger will not be before the requested time, but it might not occur for almost a full interval after that time. In addition, while the overall period of the repeating alarm will be as requested, the time between any two successive firings of the alarm may vary. If your application demands very low jitter, usesetRepeating(int, long, long, PendingIntent) instead.

Parameters
typeOne of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP}, RTC or RTC_WAKEUP.triggerAtTimeTime the alarm should first go off, using the appropriate clock (depending on the alarm type). This is inexact: the alarm will not fire before this time, but there may be a delay of almost an entire alarm interval before the first invocation of the alarm.intervalInterval between subsequent repeats of the alarm. If this is one of INTERVAL_FIFTEEN_MINUTESINTERVAL_HALF_HOUR,INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY then the alarm will be phase-aligned with other alarms to reduce the number of wakeups. Otherwise, the alarm will be set as though the application had called setRepeating(int, long, long, PendingIntent).operationAction to perform when the alarm goes off; typically comes from IntentSender.getBroadcast().
public void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
Since: API Level 1

Schedule a repeating alarm. Note: for timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler. If there is already an alarm scheduled for the same IntentSender, it will first be canceled.

Like set(int, long, PendingIntent), except you can also supply a rate at which the alarm will repeat. This alarm continues repeating until explicitly removed with cancel(PendingIntent). If the time occurs in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

If an alarm is delayed (by system sleep, for example, for non _WAKEUP alarm types), a skipped repeat will be delivered as soon as possible. After that, future alarms will be delivered according to the original schedule; they do not drift over time. For example, if you have set a recurring alarm for the top of every hour but the phone was asleep from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens, then the next alarm will be sent at 9:00.

If your application wants to allow the delivery times to drift in order to guarantee that at least a certain time interval always elapses between alarms, then the approach to take is to use one-time alarms, scheduling the next one yourself when handling each alarm delivery.

Parameters
typeOne of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP}, RTC or RTC_WAKEUP.triggerAtTimeTime the alarm should first go off, using the appropriate clock (depending on the alarm type).intervalInterval between subsequent repeats of the alarm.operationAction to perform when the alarm goes off; typically comes from IntentSender.getBroadcast().
使用实例google的DeskClock应用程序的com.android.deskclock.Alarms
 /**
     * Sets alert in AlarmManger and StatusBar.  This is what will
     * actually launch the alert when the alarm triggers.
     *
     * @param alarm Alarm.
     * @param atTimeInMillis milliseconds since epoch
     */
    private static void enableAlert(Context context, final Alarm alarm,
            final long atTimeInMillis) {
        AlarmManager am = (AlarmManager)
                context.getSystemService(Context.ALARM_SERVICE);

        if (Log.LOGV) {
            Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
        }

        Intent intent = new Intent(ALARM_ALERT_ACTION);

        // XXX: This is a slight hack to avoid an exception in the remote
        // AlarmManagerService process. The AlarmManager adds extra data to
        // this Intent which causes it to inflate. Since the remote process
        // does not know about the Alarm class, it throws a
        // ClassNotFoundException.
        //
        // To avoid this, we marshall the data ourselves and then parcel a plain
        // byte[] array. The AlarmReceiver class knows to build the Alarm
        // object from the byte[] array.
        Parcel out = Parcel.obtain();
        alarm.writeToParcel(out, 0);
        out.setDataPosition(0);
        intent.putExtra(ALARM_RAW_DATA, out.marshall());

        PendingIntent sender = PendingIntent.getBroadcast(
                context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
......................................................
    }
   /**
     * Disables alert in AlarmManger and StatusBar.
     *
     * @param id Alarm ID.
     */
    static void disableAlert(Context context) {
        AlarmManager am = (AlarmManager)
                context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(
                context, 0, new Intent(ALARM_ALERT_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(sender);
...........................................................
    }
结束!
原创粉丝点击