Notification Action not firing PendingIntent

问题描述:

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

enter image description here

下载服务

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> 

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

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()