如何利用NotificationListener使用Android Nougat的直接回复功能?

For*_*rce 17 android notification-listener android-7.0-nougat remote-input

我的应用程序使用a NotificationListener来读取来自各种第三方应用程序的消息,例如WhatsApp.

到目前为止,如果只有一个聊天未读,我能够发送回复,代码如下.

但是,在WhatsApp的情况下,getNotification().actions当未读取两个以上的聊天时返回一个空对象,因为消息被捆绑在一起.正如您在下面的图片中看到的,如果通知被扩展,还有一个选项可以发送直接回复,因此我确信可以利用它,我认为像PushBullet这样的应用程序正在使用此方法.

我怎样才能访问该通知的RemoteInput?

public static ReplyIntentSender sendReply(StatusBarNotification statusBarNotification, String name) {

            Notification.Action actions[] = statusBarNotification.getNotification().actions;

            for (Notification.Action act : actions) {
                if (act != null && act.getRemoteInputs() != null) {
                    if (act.title.toString().contains(name)) {
                        if (act.getRemoteInputs() != null)
                            return new ReplyIntentSender(act);
                    }
                }
            }
            return null;
        }



public static class ReplyIntentSender {
      [...]

    public final Notification.Action action;

    public ReplyIntentSender(Notification.Action extractedAction) {
            action = extractedAction;
     [...]
    }

private boolean sendNativeIntent(Context context, String message) {
            for (android.app.RemoteInput rem : action.getRemoteInputs()) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putCharSequence(rem.getResultKey(), message);
                android.app.RemoteInput.addResultsToIntent(action.getRemoteInputs(), intent, bundle);
                try {
                    action.actionIntent.send(context, 0, intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

上面代码如何工作的一些解释:收到通知后,应用程序尝试获取操作并检查名称是否在remoteInput的标题中(通常是"回复$ NAME"的格式),如果是发现Action被保存到ReplyIntentSender类中,当触发该类时sendNativeIntent,循环遍历该Action的所有RemoteInput并将消息添加到intent.如果未读取多个聊天,则getNotification().actions返回null.

下面是两个截图,第一个是没有任何问题的工作,第二个没有任何问题.

我可以回复此邮件

我无法回复此邮件

Pra*_*iya 2

你可以考虑这个作为我的建议。我对此做了一些研究,并得出了以下结论。(而且看起来你对此做了很多研究,所以你可能知道我在下面写的内容)

\n\n

许多应用程序发送特定于 Wear 的通知,其中许多包含可通过 Android Wear 设备访问的操作。我们可以抓取设备上的这些 Wear 通知,提取操作,查找回复操作(如果存在),用我们自己的响应填充它,然后执行将PendingIntent我们的响应发送回原始应用程序,以便将其发送给收件人。

\n\n

为此,您可以参考此链接(Rob J 的一个很好的解决方法)。您还可以在这种情况下参考此链接(Micha\xc5\x82 Tajchert 所做的出色研究工作)。(您可能需要解决NotificationCompat.isGroupSummary

\n\n
\n

这就是我的感受(也许我完全错了)

\n\n

.actions方法返回通过addAction(int,\n CharSequence, PendingIntent)附加到当前通知的所有Notification.Action \n 结构的数组,这里 addAction 方法已被弃用\n 1,因此它可能无法按预期工作。

\n
\n\n

我无法在最后对此进行测试,否则我很乐意提供带有代码的工作解决方案。

\n\n

希望对你有帮助。快乐编码!!!

\n