首页 > 解决方案 > PendingIntent.getBroadcast() 在 Android 11 中不起作用

问题描述

我想要什么:当用户手动删除我的应用程序的通知时,我想执行某个操作。

我是如何实现它的:我通过创建一个PendingIntent将使用PendingIntent.getBroadcast(). 然后我将此意图传递setDeleteIntent()Notification.Builder.

这在以前的 Android 版本上运行良好,但在 Android 11 中,广播没有被发送(或者至少我的接收器没有收到它)。我认为问题出在PendingIntent.getBroadcast()(对我来说似乎更有可能)或setDeleteIntent().

提示 1: 我确保我的 BroadcastReceivers 工作正常:当我使用它执行广播时,sendBroadcast(new Intent(BROADCAST_REMOVE_NOTIFICATION));它工作得非常好。

提示 2: 我刚刚注意到,在我的应用程序通知以前不可删除的状态下(在播放音频文件期间,我将播放器服务作为前台服务启动),现在它在 Android 11 中是可删除的。不确定这是否有与上述问题有关。

我不知道是什么导致了 Android 11 和以前版本之间的这种行为差异。有人可以帮忙吗?

// Set up intent to stop service when notification is removed
Intent intent = new Intent(BROADCAST_REMOVE_NOTIFICATION);
PendingIntent deleteIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);

// Create a new notification
mNotificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        // Hide the timestamp
        .setShowWhen(false)
        // Set the notification style
        .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
                // Attach our MediaSession token
                .setMediaSession(mediaSession.getSessionToken())
                // Show our playback controls in the compat view
                .setShowActionsInCompactView(0, 1, 2))
        // Set the notification color
        .setColor(getResources().getColor(R.color.colorAccent))
        // Set the large and small icons
        .setLargeIcon(notificationCover)
        .setSmallIcon(R.drawable.ic_notification_new)
        // Set notification content information
        .setContentText(mActiveAudio.getAlbumTitle())
        .setContentTitle(audioTitle)
        // Set the intent for the activity that is launched on click
        .setContentIntent(launchIntent)
        // Set intent that is launched on delete notificaiton
        .setDeleteIntent(deleteIntent)
        // Set the visibility for the lock screen
        .setVisibility(VISIBILITY_PUBLIC)
        // Make notification non-removable if the track is currently playing
        .setOngoing(title.equals(getString(R.string.button_pause)))
        // Add playback actions
        .addAction(R.drawable.ic_media_backward, getString(R.string.button_backward), playbackAction(3))
        .addAction(notificationAction, title, play_pauseAction)
        .addAction(R.drawable.ic_media_forward, getString(R.string.button_forward), playbackAction(2));

标签: androidandroid-notificationsandroid-pendingintentandroid-broadcastandroid-11

解决方案


推荐阅读