当前位置: 代码迷 >> Android >> 2011.07.08(三)——— android AlarmManager闹铃定时功能
  详细解决方案

2011.07.08(三)——— android AlarmManager闹铃定时功能

热度:97   发布时间:2016-05-01 18:32:47.0
2011.07.08(3)——— android AlarmManager闹铃定时功能
2011.07.08(3)——— android AlarmManager闹铃定时功能

参考:http://www.ophonesdn.com/article/show/30
http://hualang.iteye.com/blog/1003374

AlarmManager:

5种闹铃的类型:

       public static final int ELAPSED_REALTIME        //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3    (0x00000003)。        public static final int ELAPSED_REALTIME_WAKEUP        //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002) 。        public static final int RTC        //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用 System.currentTimeMillis()获得。系统值是1 (0x00000001) 。        public static final int RTC_WAKEUP        //能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。        Public static final int POWER_OFF_WAKEUP        //能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为4(0x00000004)。



主要api:
  
 void       cancel(PendingIntent operation)    // 取消已经注册的与参数匹配的闹铃    void      set(int type, long triggerAtTime, PendingIntent operation)    //注册一个新的闹铃    void      setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)    //注册一个重复类型的闹铃    void      setTimeZone(String timeZone)    //设置时区



例子:
单次Alarm事件:
当到达指定的时间(例子中为30秒),AlarmManager将给OneShotAlarm发出一个Broadcast Intent
Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this, 0, intent, 0); Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(System.currentTimeMillis());calendar.add(Calendar.SECOND, 30); // Schedule the alarm!AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);


重复Alarm事件:
每15秒给RepeatingAlarm 发出一个Broadcast事件
Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this, 0, intent, 0); long firstTime = SystemClock.elapsedRealtime();firstTime += 15*1000; // Schedule the alarm!AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 15*1000, sender)
;


当然 OneShotAlarm RepeatingAlarm都extends BroadcastReceiver
  相关解决方案