使用PendingIntent.getBrocast() 在 onReceive 中接受不到intent 的问题

今天在service 中使用了 PendingIntent.getBrocast()这个方法去发送一个广播,然后在onReceiver中接受并获取intent中的数据。之前是这样写的:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,i,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,tiggerAtTime,pendingIntent);

然后直接在onReceive中使用 intent.getStringArrayListExtra() 。但是这样做得到的ArrayList是一个空值。报错java.lang.NullPointException

查看了API文档onReceive这个方法,里面有这样一句话:

The Intent filters used in registerReceiver(BroadcastReceiver, IntentFilter) and in application manifests are not guaranteed to be exclusive. They are hints to the operating system about how to find suitable recipients. It is possible for senders to force delivery to specific recipients, bypassing filter resolution. For this reason, onReceive() implementations should respond only to known actions, ignoring any unexpected Intents that they may receive.

可以看到onReceiver说明了:onReceive() implementations should respond only to known actions, ignoring any unexpected Intents that they may receive.  而我在代码里没有给intent指定action,所以在onReceive方法中无法得到我想传递的intent,因此得到的数据也是空值。

这样一看,解决方法就很简单了,只需要给intent添加一个action:

i.setAction(action);

然后再onReceive方法中 判断 intent.getAction().equals(action)即可。

最后别忘了在AndroidManifest中注册你的action。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值