如何在Android Studio中通过Java代码实现回复WhatsApp通知功能
WhatsApp通知回复功能实现方案
核心原理:Android 7.0及以上系统支持通知直接回复能力,WhatsApp的新消息通知默认携带了带RemoteInput的回复动作,你可以通过NotificationListenerService直接调用该动作完成回复,不需要额外申请其他权限。
具体实现步骤
1. 提取通知中的回复动作
首先我们需要从收到的WhatsApp通知中找到可回复的动作对象,对应代码如下:
// 从通知中获取可用的回复Action private Notification.Action getReplyAction(Notification notification) { if (notification.actions == null) return null; for (Notification.Action action : notification.actions) { // 检查Action是否携带RemoteInput,这是直接回复的标识 if (action.getRemoteInputs() != null && action.getRemoteInputs().length > 0) { // 额外校验下Action的标题是否是回复相关,避免匹配到其他动作 String title = action.title.toString().toLowerCase(); if (title.contains("reply") || title.contains("回复")) { return action; } } } return null; }
2. 构造回复内容并发送
拿到回复动作后,我们就可以构造回复内容,调用动作触发回复,对应方法如下:
// 执行回复操作 public boolean sendReply(StatusBarNotification sbn, String replyContent) { Notification notification = sbn.getNotification(); Notification.Action replyAction = getReplyAction(notification); if (replyAction == null) return false; // 获取RemoteInput的key,这是存放回复内容的键值 RemoteInput remoteInput = replyAction.getRemoteInputs()[0]; Intent replyIntent = new Intent(); // 把回复内容放到Intent里 Bundle bundle = new Bundle(); bundle.putCharSequence(remoteInput.getResultKey(), replyContent); RemoteInput.addResultsToIntent(replyAction.getRemoteInputs(), replyIntent, bundle); try { // 执行PendingIntent触发回复 replyAction.actionIntent.send(getApplicationContext(), 0, replyIntent); return true; } catch (PendingIntent.CanceledException e) { e.printStackTrace(); return false; } }
3. 调用示例
你可以在需要回复的地方直接调用上述方法,比如你收到某条消息后要自动回复,直接在原有逻辑中新增即可:
if (sbn.getPackageName().equals(WHATSAPP_PACKAGE_NAME)) { // 你原来的通知捕获、消息存储逻辑... String sender = sbn.getNotification().extras.getString(Notification.EXTRA_TITLE); // 示例:给指定联系人自动回复 if ("测试联系人".equals(sender)) { sendReply(sbn, "我现在忙,稍后回复你"); } }
注意事项
- 该方案只支持Android 7.0及以上系统,更低版本系统WhatsApp通知没有自带直接回复能力,无法用该方案实现
- 不要短时间内高频触发自动回复,可能会触发WhatsApp的风控机制,导致账号功能受限
- 部分群通知、系统通知或者特殊场景的通知可能没有携带回复动作,调用
sendReply会返回false,需要自行处理异常场景
内容的提问来源于stack exchange,提问作者ABDO-AR
相关产品推荐
相关产品推荐

