如何通过PendingIntent向Broadcast发送数据?
我试图通过 PendingIntent
发送一些额外的数据,例如:
MyMessage message;
//...
Intent intent;
SmsManager sms = SmsManager.getDefault();
intent = new Intent(Constants.SENT_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId()); //putting long id (not -1L)
PendingIntent sentPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
intent = new Intent(Constants.DELIVERED_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId());
PendingIntent deliveredPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
sms.sendTextMessage(phoneNumber, null, message.getBody(), sentPI, deliveredPI);
然后在 Broadcast
中尝试捕获数据:
@Override
public void onReceive(Context context, Intent intent) {
String message, prefix = "";
String action = intent.getAction();
long id = intent.getLongExtra(Constants.EXTRA_RAW_ID, -1L); //here I receive id=-1
// blah-blah....
}
我看到 Broadcast
onReceive()
被调用 - 这意味着 Broadcast
以正确的方式注册,但额外内容仍然是空的。
有什么想法吗?
I'm trying to send via PendingIntent
some extra data, like:
MyMessage message;
//...
Intent intent;
SmsManager sms = SmsManager.getDefault();
intent = new Intent(Constants.SENT_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId()); //putting long id (not -1L)
PendingIntent sentPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
intent = new Intent(Constants.DELIVERED_PLAIN);
intent.putExtra(Constants.EXTRA_RAW_ID, message.getId());
PendingIntent deliveredPI = PendingIntent.getBroadcast(activity, 0, intent, 0);
sms.sendTextMessage(phoneNumber, null, message.getBody(), sentPI, deliveredPI);
Then in Broadcast
trying to catch data:
@Override
public void onReceive(Context context, Intent intent) {
String message, prefix = "";
String action = intent.getAction();
long id = intent.getLongExtra(Constants.EXTRA_RAW_ID, -1L); //here I receive id=-1
// blah-blah....
}
I see that Broadcast
onReceive()
called - which means that Broadcast
registered in a proper way, but still extras are empty.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将您正在待定意图中使用的数据作为附加内容放入意图中。
您将在
BroadCast
接收器的onReceive
方法中获得此意图。尝试如下定义待处理意图。
Put data in intent you are using in pending intent as Extras.
You will get this intent in
onReceive
Method ofBroadCast
receiver.Try to define Pending intent as below.
正如 待处理意图 中所述:
as said on pending intent :
任何在广播接收器中遇到 null extras 的人:
您应该使用
FLAG_MUTABLE
这是一个示例:
Anyone who are experiencing getting null extras in Broadcast Receiver:
You should use
FLAG_MUTABLE
Here is an example: