android - Notification.Builder 添加 Action

标签 android notifications push android-pendingintent

我想知道按下了哪个按钮,所以我在 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/

相关文章:

python - 钢铁 worker 工作完成通知

c# - Windows Server 2008 中没有气球工具提示关闭按钮

android - Cordova PushPlugin - 如果应用程序未运行,则无法在 Android 上接收 GCM 通知

java - setTextSize 不适用于 Android 中的 AutofitTextView

android - MAP-API 如何在 ANDROID 中用于一个简单的用例

android 媒体商店艺术

jquery - 使用 MySql/Node js 创建通知服务器

javascript - Angular 4嵌套FormArrays无法读取null的属性 'push'

ios6 - 发送推送通知时如何从 APN 获取反馈

android - 在 oncreate 中为 ListView 着色