私のアプリでは、NotificationListener
を使って、さまざまなサードパーティのアプリからのメッセージ(例えば、WhatsApp)を読み上げています。Android Nougatの直接リプライ機能をNotificationListenerと併用するにはどうすればよいですか?
これまでのところ、1つのチャットしか未読の場合は返信することができました。コードは以下のとおりです。
しかし、WhatsAppの場合、メッセージは一緒にバンドルされるので、2つ以上のチャットが未読の場合、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;
}
}
上記のコードがどのように機能するかをいくつか説明:通知を受信すると名前がremoteInputのタイトルにある場合、アプリはアクションと小切手を取得しようとします(通常は、それは返信」の形式であります$ NAME ")が見つかった場合、アクションはReplyIntentSenderクラスに保存されます。このクラスは、sendNativeIntent
によってトリガーされると、そのアクションのすべてのRemoteInputを循環し、そのメッセージをインテントに追加します。複数のチャットが未読の場合、getNotification().actions
はnullを返します。
以下は2つのスクリーンショットです。最初のスクリーンショットは問題なく動作し、2番目は問題のないスクリーンショットです。
NotificationListenerServiceまたはカスタムNotificationListenerインターフェイスを使用していますか? –
read:https://developer.android.com/reference/android/service/notification/NotificationListenerService.html – CristiC777
@PravinDivraniya私は通常のNotificationListenerServiceを使用しています。 – Force