Notification.Builder 添加操作

Jes*_*rix 4 notifications android push android-pendingintent

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

Log.e(TAG, "Clicked " + extras.getInt("ACTION"));
Run Code Online (Sandbox Code Playgroud)

而且我总是,无论我按哪个按钮,都会得到 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);
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ser 5

您的代码getPendingAction()将始终返回相同的PendingIntent. PendingIntent每次调用此方法时,您都不会创建一个单独的对象。为确保每个调用都创建一个单独的PendingIntent,您需要使Intent. 您可以通过在 中设置 ACTION 来做到这一点Intent,如下所示:

intent.setAction(action.name());
Run Code Online (Sandbox Code Playgroud)

为确保任何PendingIntent具有相同 ACTION 的旧s 被最新的附加项覆盖,我也会这样调用getBroadcast()

return PendingIntent.getBroadcast(context, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)