Android的闹钟使用AlarmManager实现,在API 19(Android4.4)之前主要使用下面三个方法实现一次性和重复闹钟:
- set(int type, long startTime, PendingIntent intent) //设置一次性闹钟
- setRepeating(int type, long startTime, long intervalTime, PendingIntent intent)//设置重复闹钟
- setInexactRepeating(int type, long startTime, long intervalTime, PendingIntent intent)//设置重复闹钟
参数解释:
- type:闹钟类型:
RTC_WAKEUP(闹钟会在设备休眠状态下唤醒设备)
,RTC(闹钟在设备休眠状态下不会唤醒设备,但是下次设备被唤醒的时候该闹钟会有效)
,ELAPSED_REALTIME_WAKEUP
orELAPSED_REALTIME,RTC和REALTIME闹钟的区别在于RTC是根据时区时间触发闹钟,可以通过修改系统时间的方式触发闹钟,而REALTIME则是根据系统开机时间的流逝时间来触发闹钟
startTime:触发闹钟的时间,单位ms,设置的是距离1970年1月1日的ms数
intervalTime:重复闹钟的时间间隔单位ms
intent:PendingIntent是一种特殊的intent,他需要满足一定的条件才能执
- setWindow(int type, long startTime, PendingIntent intent)//会出现延时
- setExact(int type, long startTime, PendingIntent intent)//精确
- 如何设置重复闹钟
public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra("type", 0); long intervalMillis = intent.getLongExtra("intervalMillis", 0); if (intervalMillis != 0){ AlarmManageUtil.setAlarmTime(context, System.currentTimeMillis() + intervalMillis, intent); } intent.setClass(context, AlarmActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); }
- 关机之后闹钟失效