下面是一个可以触发 deleteIntent 的 Android 媒体样式通知示例代码,可参考修改:
// 使用媒体样式创建通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId); MediaSessionCompat mMediaSession; mMediaSession = new MediaSessionCompat(context, "MediaSessionTag"); builder.setStyle(new androidx.media.app.NotificationCompat.MediaStyle() .setShowActionsInCompactView(0, 1, 2, 3) .setCancelButtonIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP)) .setMediaSession(mMediaSession.getSessionToken()) .setDeleteIntent(getDeleteIntent(context)));
// 在 NotificationCompat.Builder 中添加 getDeleteIntent() 函数 private PendingIntent getDeleteIntent(Context context) { Intent intent = new Intent(context, NotificationBroadcastReceiver.class); intent.setAction(NotificationBroadcastReceiver.ACTION_DELETE_NOTIFICATION); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); }
// 在 NotificationBroadcastReceiver 中处理 deleteIntent 意图 public void onReceive(final Context context, final Intent intent) { if (intent.getAction().equals(ACTION_DELETE_NOTIFICATION)) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(1); } }