首页 > 解决方案 > 如何使用android远程输入将额外数据传递给广播接收器

问题描述

我已经看到了这个问题的几个重复项,所以如果我错过了一个,我很抱歉,但我发现没有一个有解决方案,例如这里我正在尝试做与此相同的事情尽管。我想使用直接回复(消息样式)通知,但我需要添加一些额外的数据(recipientId 等),我很困惑我可以在哪里添加这些额外的数据,我的意图、待处理意图和 RemoteInput 的代码看起来像这个

    String replyLabel = getString(R.string.notif_action_reply);
    intent = new Intent(this, ReplyReceiver.class);

    replyPendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
    RemoteInput remoteInput = new 
    RemoteInput.Builder(NOTIFICATION_REPLY).setLabel(replyLabel).build();
    NotificationCompat.Action action = new 
    NotificationCompat.Action.Builder(R.drawable.ic_send_white_24dp,
            this.getString(R.string.reply), replyPendingIntent)
            .addRemoteInput(remoteInput)
            .setAllowGeneratedReplies(true)
            .build();

现在要发送额外的数据,我尝试将其添加为字符串

intent.putExtra(Constants.MSG_RECIPIENT, message.getRecipientId());

并作为捆绑

Bundle bundle = new Bundle();
bundle.putString(Constants.MSG_RECIPIENT, message.getRecipientId());
intent.putExtras(bundle);

在意图和作为 RemoteInput 的一部分

RemoteInput remoteInput = new RemoteInput.Builder(NOTIFICATION_REPLY)
.setLabel(replyLabel).addExtras(bundle).build();

并在尝试取回数据时,我尝试从 onReceive 意图中将其作为字符串或捆绑包获取

intent.getExtras(); 
intent.getStringExtra(Constants.MSG_RECIPIENT);

但似乎没有什么对我有用的结果总是在另一边为空(发送时数据绝对不为空)有人可以告诉我如何添加意图数据并在另一边检索它吗?

更新

好的,它现在可以工作了

    String replyLabel = getString(R.string.notif_action_reply);
    intent = new Intent(this, ReplyReceiver.class);
    //intent.putExtras(bundle);
    intent.putExtra(Constants.MSG_SENDER_NAME, message.getSenderName());
    intent.putExtra(Constants.MSG_SENDER, message.getSenderId());
    intent.putExtra(Constants.MSG_RECIPIENT_NAME, 
    message.getRecipientName());
    intent.putExtra(Constants.MSG_RECIPIENT, message.getRecipientId());

    replyPendingIntent = PendingIntent.getBroadcast
    (this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
    RemoteInput remoteInput = new 
    RemoteInput.Builder(NOTIFICATION_REPLY).setLabel(replyLabel).build();
    NotificationCompat.Action action = new 
    NotificationCompat.Action.Builder(R.drawable.ic_send_white_24dp,
            this.getString(R.string.reply), replyPendingIntent)
            .addRemoteInput(remoteInput)
            .setAllowGeneratedReplies(true)
            .build();

并接收它我在 onReceive 中使用它

 String senderId = intent.getStringExtra(Constants.MSG_SENDER_NAME);

标签: androidandroid-intentbundleandroid-pendingintentremote-input

解决方案


尝试添加PendingIntent.FLAG_UPDATE_CURRENTgetBroadcast()

replyPendingIntent = 
        PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

此外,您没有显示将“附加”添加到 Intent 的位置。您必须在调用之前添加它们PendingIntent.getBroadcast()


推荐阅读