0
我想創建一個顯示下載進度的通知(它現在被模擬)並允許用戶取消下載。我使用通知生成器並添加「取消下載」操作。該操作會顯示,但不會在點擊時發送PendingIntent。我確認PendingIntent正在通過設置contentIntent來工作。廣播接收器能夠獲取內容點擊的消息,但不能獲得點擊的動作。Notification Action not firing PendingIntent
下載服務
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>