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

来源:互联网 发布:网络舆论战 编辑:程序博客网 时间:2024/04/26 04:14

今天在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。



0 0
原创粉丝点击