我有一个应用程序,它将一些实体与唯一 ID 相关联,并向用户通知有关实体的信息,我将使用与实体 ID 相同的 notificationID。
我已经根据以下 sample solution 构建了一个带有关闭操作的通知完全没有任何修改。
到目前为止一切进展顺利,直到我尝试使用示例创建 2 个具有不同 ID 的通知。 一个问题出现了,dismiss 按钮只接收第一个通知的 notificationID:
第一个通知按预期正常运行。
但是 BroadcastReceiver 中的第二个通知的 getExtra()
取而代之的是第一个通知的 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);
}
}
最佳答案
我认为问题在于将 0
传递给 PendingIntent:
PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);
在我开始将通知 ID 作为第二个参数传递之前,我遇到了同样的问题;所以不要传入 0
,而是传入通知的 id:
PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), NOTIFICATION_ID, buttonIntent, 0);
进行更改后,我注意到在单击单个通知(尤其是组中的通知)时,一切都按预期进行。
关于android - 带有关闭通知操作按钮的多重通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071452/