Android 11中的通知行为发生了变化。当通知被点击时,DeleteIntent不应该被触发。如果你想在通知被点击时执行某些操作,则可以使用PendingIntent。下面是示例代码:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.notification_icon);
// Create the intent that should be sent when the notification is clicked
Intent resultIntent = new Intent(context, MyActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Set the intent that should be sent when the notification is dismissed
builder.setDeleteIntent(resultPendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(notificationId, builder.build());
在上述代码中,我们使用TaskStackBuilder来创建一个包含我们想要启动的Activity的Intent,并将其添加到堆栈中。我们还使用PendingIntent.FLAG_UPDATE_CURRENT标志来确保PendingIntent中的数据是最新的。最后,我们使用setDeleteIntent()方法将PendingIntent设置为在通知被消除时发送。这样,当用户点击通知时,应用程序会启动相应的Activity,而不是调用DeleteIntent。