多个通知与可关闭通知操作按钮

3

我有一个应用程序,将一些实体与唯一的ID关联起来,并向用户通知这些实体,我将使用notificationID作为实体ID。

我已经按照以下示例解决方案构建了一个具有解除操作的通知,没有进行任何修改。

到目前为止,当我尝试使用该示例创建具有不同ID的2个通知时,出现了一个问题。解除按钮只接收第一个通知的notificationID:

第一个通知的行为与预期的一样正常。

但是,BroadcastReceiver中第二个通知的getExtra()获取的是第一个通知的notificationID,因此取消通知只会取消第一个通知。

我的create Notification函数,我使用不同的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());
}

BroadcastReceiver类:

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);
    }
}
1个回答

3
我认为问题在于向PendingIntent传递了“0”:

我认为问题在于向 PendingIntent 中传递了 0

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

直到我开始将通知ID作为第二个参数传递,我才解决了同样的问题;所以不要传递0,而是传递通知的ID:

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

在我做出那个更改后,我注意到当点击单独的通知时(尤其是组内的通知),一切都按预期工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接