当要设置一个闹钟时,可以把数据放在Intent里,再用intent对象生成一个PendingIntent对象,然后用AlarmManager 来邦定PendingIntent对象设置闹钟,具体代码如下:

Intent intent = new Intent(context,
AlarmReceiver.class);

intent.putExtra("id", alarm.getId());

intent.putExtra("weekday", getCurrentWeekday());

PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
alarm.getId(), intent, 0);

AlarmManager alarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtTime,
pendingIntent);

闹钟设置的代码基本上是这样的,但是如果在启动的Broadcast中接收Intent过来的数据,有时会得到一个null值,也就是说,根本没有数据传过来。

因此查看官方api,发现 PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, alarm.getId(), intent,
0);的最后一个参数参数是int flag,这个值可以是FLAG_ONE_SHOT, FLAG_NO_CREATE,
FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT

简单翻译一下:

int
FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。

int
FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.

int
FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。

int
FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。

我们需要把最后一个参数改为PendingIntent.FLAG_UPDATE_CURRENT,这样在启动的Activity里就可以用接收Intent传送数据的方法正常接收。

Intent intent = new Intent(context,
AlarmReceiver.class);

intent.putExtra("id", alarm.getId());

intent.putExtra("weekday", getCurrentWeekday());

PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
alarm.getId(),
intent,endingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtTime,
pendingIntent);

最新文章

  1. 数据库:mongodb与关系型数据库相比的优缺点 (转)
  2. switch结构2016/03/08
  3. [转载] linux 速查表
  4. python RabbitMQ队列使用(入门篇)
  5. android之ViewStub的使用
  6. JAVA基础2——类初始化相关执行顺序
  7. Hadoop2.9.0安装
  8. 利用 html2canvas 做个简单的诗词卡片生成器
  9. visual studio code运行时报错,无法将“cnpm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称,Cannot find module 'webpack'
  10. python语法_算数运算+赋值运算符+比较运算符+逻辑运算符
  11. 第三百六十七节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)scrapy写入数据到elasticsearch中
  12. python实战——网络爬虫之request
  13. mysql 5.6 与5.7安装
  14. 导航跳转后保持选中状态 jquery高亮当前选中菜单
  15. Java关于日期时间的工具类
  16. Animation学习笔记
  17. react 执行 yarn build 后 去除 .js.map 文件
  18. Oracle RAC(Real Application Clusters)
  19. java - day13 - ImplementDemo
  20. react native的环境搭建中常见问题

热门文章

  1. angularJS的过滤器!
  2. SQL中 decode()函数简介(转载)
  3. 【git】------git的基本命令------【巷子】
  4. MacBook鼠标指针乱窜/不受控制问题的解决方法
  5. javascript 执行环境,作用域链和闭包
  6. numpy中的convolve的理解
  7. PHP的线性安全和非线性安全的区别
  8. toml-lang - Tom's Obvious, Minimal Language
  9. 过山车---hdu2063(最大匹配)
  10. React 教程