安卓AlarmManager类的使用

安卓AlarmManager类的使用


安卓的AlarmManager可以实现在一定时间点或一定时间段后实现对消息的提醒或者是执行一定的操作,AlarmManager就像一个定时器,到点也可以调用组件如Activity,Service或是BroadcastReceiver。

以下为AlarmManager常用的对象方法

方法描述
cancel( PendingIntent operation )取消AlarmManager的定时服务
set( int type,long triggerAtTime,PendingIntent operation )设置当到达参数triggerAtTime所指定的时间时,按照type参数所指定的服务类型启动由operation参数指定的组件
setInexactRepeating ( int type ,long triggerAtTime,PendingIntent operation )设置一个非精确的周期性任务,例如,我们设置一个每小时启动一次的闹钟,但是系统并不一定总是每小时开始时启动闹钟
setRepeating( int type ,long triggerAtTime,PendingIntent operation )设置一个周期性执行的定时服务
setTime( long millis )设置定时的时间
setTimeZone(String timeZone)设置系统默认的时区

在上述的方法中,存在一个参数int type
这里type一共有下面几种类型

  1. ELAPSED_REALTIME
    该类型指的是设置一个时间段,一个时间段过去后开始启动提醒功能
  2. ELAPSED_REALTIME_WAKEUP
    该类型功能同上,但是触发提醒时能够唤醒系统
  3. RTC
    该类型指的是设置一个时间点,到了时间点触发提醒功能
  4. RTC_WAKEUP
    该类型功能同上,但是触发提醒时能够唤醒系统

以下为具体使用代码片

Intent intent = new Intent(MainActivity.this,AlarmActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
//获取闹钟的Pending

AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar c = Calendar.getInstanc();
//获取日历对象
c.set(Calendar.HOUR_OF_DAY,timepicker.getHour());
c.set(Calendar.MINUTE,timepicker.getMinute());
c.set(Calendar.SECOND,0);

alarm.set(AlarmManager.RTC_WAKEUP,c.getTimeeInMillis(),pendingIntent);
//这里用到了type类型中的第四类
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值