首页 > 解决方案 > 带有关闭通知操作按钮的多个通知

问题描述

我有一个应用程序,它将某些实体与唯一 ID 相关联,并将实体通知给用户,我将使用 notificationID 与实体 ID 相同。

我已经根据以下示例解决方案构建了一个带有解除操作的通知,完全没有任何修改。

到目前为止,一切进展顺利,直到我尝试使用示例创建 2 个具有不同 ID 的通知。一个问题是,dismiss按钮只接收到第一个通知的notificationID:

第一个通知按预期正常运行。

但是getExtra()BroadcastReceiver 中的第二个通知取而代之的是第一个通知的 notificationID,而取消通知只是继续取消第一个通知。

我的创建通知函数,我只是用不同的 ID 调用了这个函数两次:

void createNoti(int NOTIFICATION_ID){

    Intent buttonIntent = new Intent(context, ButtonReceiver.class);
    buttonIntent.putExtra("notificationId", NOTIFICATION_ID);

    PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);

    NotificationCompat.Builder mb = new  NotificationCompat.Builder(getBaseContext());
    mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
    manager.notify(NOTIFICATION_ID, mb.build());
}

广播接收器类:

public class ButtonReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        int notificationId = intent.getIntExtra("notificationId", 0);

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }
}

标签: androidnotificationsbroadcastreceiver

解决方案


我相信问题在于传递0到 PendingIntent:

PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);

在我开始将通知 ID 作为第二个参数传递之前,我遇到了同样的问题;因此,不要传入 ,而是传入0通知的 id:

PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), NOTIFICATION_ID, buttonIntent, 0);

进行更改后,我注意到单击单个通知(尤其是组中的通知)时,一切都按预期工作。


推荐阅读