Notification.Builder 添加动作

Notification.Builder add action

我想知道按下了哪个按钮,所以我在 onReceive 上执行此操作

Log.e(TAG, "Clicked " + extras.getInt("ACTION"));

而且我总是,无论我按哪个按钮,得到 3 (ActionEnum.GO_TO_REMINDERS) 也就是 setContentIntent.

另一个问题是,除非我按下通知好友,否则通知不会关闭,但是当我按下按钮时它不会关闭。

public void createNotification(Context context, Reminder reminder) {
    // Build notification
    Notification noti = new Notification.Builder(context)
            .setContentTitle(reminder.getDisplayString())
            .setContentText("Pick Action")
            .setSmallIcon(R.drawable.icon_remider)
            .setContentIntent(
                    getPendingAction(context, reminder,
                            ActionEnum.GO_TO_REMINDERS))
            .addAction(R.drawable.icon, "Take",
                    getPendingAction(context, reminder, ActionEnum.TAKE))
            .addAction(R.drawable.icon, "Snooze",
                    getPendingAction(context, reminder, ActionEnum.SNOOZE))
            .addAction(R.drawable.icon, "Remove",
                    getPendingAction(context, reminder, ActionEnum.REMOVE))
            .build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // hide the notification after its selected
    noti.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, noti);

}

public PendingIntent getPendingAction(Context context, Reminder reminder,
        ActionEnum action) {
    // Prepare intent which is triggered if the
    // notification is selected
    Intent intent = new Intent(context, RemindersReceiver.class);
    intent.putExtra("ID", reminder.getIntId());
    intent.putExtra("CLICK", true);
    intent.putExtra("ACTION", action.getValue());
    Log.e(TAG, "set action : " + action.getValue());

    return PendingIntent.getBroadcast(context, 0, intent, 0);
}

您在 getPendingAction() 中的代码将始终 return 相同 PendingIntent。每次调用此方法时,您都不会创建单独的 PendingIntent。为确保每次调用都创建一个单独的 PendingIntent,您需要使 Intent 唯一。您可以通过在 Intent 中设置 ACTION 来执行此操作,如下所示:

intent.setAction(action.name());

为了确保任何具有相同 ACTION 的旧 PendingIntent 都被最新的额外内容覆盖,我也会这样调用 getBroadcast()

return PendingIntent.getBroadcast(context, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);