通知操作不会触发PendingIntent

我想创建一个显示下载进度的通知(它现在被模拟),并允许用户取消下载。 我使用通知生成器并添加“取消下载”操作。 该操作将显示,但不会单击发送PendingIntent。 我确认PendingIntent正在通过设置contentIntent来工作。 广播接收者能够获得内容点击的消息,但不能点击该动作。

在这里输入图像描述

下载服务

val cancelIntent = Intent(applicationContext, NotificationBroadcastReceiver::class.java).apply { action = "xxx.xxx.xxx.CANCEL_DOWNLOAD" putExtra("notification_id", NOT_ID_PROGRESS) } val pendingIntent = PendingIntent.getBroadcast(applicationContext, 1, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT) pendingIntent.send() val notificationBuilder = NotificationCompat.Builder(applicationContext, "updates").apply { setContentTitle("Title") setContentText("Text") setSmallIcon(R.drawable.ic_logo_full_black) setOnlyAlertOnce(true) setContentIntent(pendingIntent) addAction(NotificationCompat.Action.Builder(R.drawable.ic_delete, "Cancel", pendingIntent).build()) } startForeground(NOT_ID_PROGRESS, notificationBuilder.build()) Thread({ for (i in 0..100) { notificationBuilder.setProgress(100, i, false) notificationManager?.notify(NOT_ID_PROGRESS, notificationBuilder.build()) Thread.sleep(100L) } notificationBuilder.setProgress(0, 0, false) notificationBuilder.setContentText("Download completed") notificationManager?.notify(NOT_ID_COMPLETE, notificationBuilder.build()) onFinish() }).start() 

NotificationBroadcastReceiver

 class NotificationBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val notificationId = intent?.getIntExtra("notification_id", 0) ?: 0 Log.d(TAG, "NotificationBroadcastReceiver: notificationId = $notificationId") (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?)?.cancel(notificationId) } } 

AndroidManifest.xml中

 <service android:name=".services.DownloadService" /> <receiver android:name=".services.PackageDownloadService$NotificationBroadcastReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="xxx.xxx.xxx.CANCEL_DOWNLOAD" /> </intent-filter> </receiver> 

我自己找到了答案。 首先,一切都配置正确。 我唯一需要改变的是通知的更新间隔。 将间隔设置为大约2000ms后 ,选择“中止操作”按钮时触发点击事件。

 Thread({ for (i in 0..100 step 20) { notificationBuilder.setProgress(100, i, false) notificationManager?.notify(NOT_ID_PROGRESS, notificationBuilder.build()) Thread.sleep(2000L) } notificationBuilder.setProgress(0, 0, false) notificationBuilder.setContentText("Download completed") notificationManager?.notify(NOT_ID_COMPLETE, notificationBuilder.build()) onFinish() }).start()