package com.example.notificationdemo
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
class MainActivity : AppCompatActivity() {
private val CHANNEL_ID = "demo_channel"
private val NOTIFICATION_ID = 101
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel()
val sendButton: Button = findViewById(R.id.sendNotificationButton)
sendButton.setOnClickListener {
sendNotification()
}
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Demo Channel"
val descriptionText = "Channel for demo notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
private fun sendNotification() {
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Demo Notification")
.setContentText("This is a notification sent using a channel.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(this)) {
notify(NOTIFICATION_ID, builder.build())
}
}
}We first create a notification channel only if the Android version is Oreo or higher, because channels are supported from API 26 onwards. The channel has an ID, a user-visible name, and importance level.
We then set up a button click listener that sends a notification using NotificationCompat.Builder with the channel ID. This ensures the notification uses the created channel.
The notification has a small icon, a title, and a short message. We use NotificationManagerCompat to show the notification.