闹钟开发过程中用PendingIntent传送数据丢失解决办法

本文介绍如何使用Android系统中的AlarmManager设置闹钟,并通过Intent传递数据到BroadcastReceiver。重点在于解决Intent数据传递过程中可能出现的null值问题,通过设置PendingIntent的标志位为FLAG_UPDATE_CURRENT确保数据正确传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当要设置一个闹钟时,可以把数据放在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);的最后一个参数参数是intflag,这个值可以是FLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT,FLAG_UPDATE_CURRENT
简单翻译一下:
intFLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。
intFLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.
intFLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。
intFLAG_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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值