Home > OS >  What should I change so that when I click on the notification button, it closes?
What should I change so that when I click on the notification button, it closes?

Time:12-08

I do somethink like this, but idk what i what to do. Can you help me?

private fun sendNotification(){


       val snoozeIntent = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS).apply {
           putExtra(CHANNEL_ID, 0)
       }
       val snoozePendingIntent: PendingIntent =
           PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
       ...
        .addAction(R.drawable.ic_launcher_background, "200 мл", snoozePendingIntent)

CodePudding user response:

I think you maybe want to call

.setAutoCancel(true)

on your NotificationCompat.Builder

CodePudding user response:

Create additional action button and PendingIntent

val closeIntent = Intent(this, CloseNotificationReceiver::class.java)
    .putExtra("ID", notificationId)
val closeFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    PendingIntent.FLAG_IMMUTABLE else 0
val closePendingIntent = PendingIntent
    .getBroadcast(this, requestCode, closeIntent, closeFlag)

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
    // ...
    .addAction(R.drawable.ic_close, "Close", closePendingIntent)
    // ...

NotificationManagerCompat.from(this)
    .notify(notificationId, builder.build())

Then implement BroadcastReceiver to handle closing Intents

class CloseNotificationReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val id = intent.getIntExtra("ID", 0)
        NotificationManagerCompat.from(context).cancel(id)
    }
}
  • Related