带有“取消通知”操作按钮的“多个通知”

时间:2019-05-10 05:50:45

标签: android notifications broadcastreceiver

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

我已经根据关注sample solution构建了具有撤消操作的通知,因为我的意思是完全相同,没有任何修改,因为它可以工作。

到目前为止,情况一直很好,直到我尝试使用示例创建2个具有不同ID的通知。 出现问题,解除按钮仅接收第一个通知的notificationID:

第一个通知的行为正常。

但是,BroadcastReceiver中的第二个通知getExtra()取而代之的是FIRST通知的notifyID,使取消通知仅保持取消第一个通知即可。

我的创建通知功能,我只是使用不同的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 个答案:

答案 0 :(得分:1)

我认为问题在于将0传递给PendingIntent:

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

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

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

做出更改后,我发现单击单个通知(尤其是组中的通知)时,所有内容均按预期工作。