我想知道按下了哪个按钮,所以我在 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()
中的代码将始终返回相同的 PendingIntent
。每次调用此方法时,您都不会创建单独的 PendingIntent
。为确保每次调用都创建一个单独的 PendingIntent
,您需要使 Intent
唯一。您可以通过在 Intent
中设置 ACTION 来做到这一点,如下所示:
intent.setAction(action.name());
为了确保具有相同 ACTION 的所有旧 PendingIntent
都被最新的额外内容覆盖,我还会像这样调用 getBroadcast()
:
return PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
关于android - Notification.Builder 添加 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023735/