【发布时间】:2017-03-15 03:34:59
【问题描述】:
我的应用正在使用NotificationListener 来读取来自各种第 3 方应用(例如 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;
}
}
上面代码如何工作的一些解释:一旦收到通知,应用程序就会尝试获取操作并检查名称是否在远程输入的标题中(通常格式为“回复 $NAME”) ,如果找到,则将 Action 保存到 ReplyIntentSender 类中,该类在由 sendNativeIntent 触发时,循环遍历该 Action 的所有 RemoteInputs 并将消息添加到意图中。如果多个聊天未读,getNotification().actions 返回 null。
下面是两张截图,第一张可以正常工作,第二张没有问题。
【问题讨论】:
-
您使用的是 NotificationListenerService 还是您的自定义 NotificationListener 接口?
-
@PravinDivraniya 我正在使用常规 NotificationListenerService。
-
好的...如果可能的话,如果它与您的问题相关,请您发布该侦听器服务的代码。
-
如果你愿意,我可以,但监听器基本上只是将 StatusbarNotification 传递给类。
标签: android android-7.0-nougat notification-listener remote-input