通知操作未触发PendingIntent

时间:2017-10-19 08:29:20

标签: android notifications kotlin

我想创建一个显示下载进度的通知(暂时被模拟)并允许用户取消下载。我使用通知生成器并添加“取消下载”#39;行动。将显示该操作,但不会在单击时发送PendingIntent。我通过设置contentIntent确认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>

1 个答案:

答案 0 :(得分:0)

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

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