Notification Channel in Android Kotlin
Step 1: Create AppController class and extends from Application class then declared this class name into the application tag of the android manifest file
AppController.kt
class AppController : Application() {
companion object {
var CHANNEL_1_ID = "chennal1"
val CHENNEL_2_ID = "ServiceChannel"
}
override fun onCreate() {
super.onCreate()
createNotificationChennal()
}
fun createNotificationChennal() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
CHANNEL_1_ID,
"CHANNEL 1",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationChannel.description = "Channel 1 description"
notificationChannel.enableLights(true)
notificationChannel.enableVibration(true)
notificationChannel.lightColor = Color.GREEN
notificationChannel.setShowBadge(true)
val notificationChennal2 =
NotificationChannel(CHENNEL_2_ID, "CHENNAL 2", NotificationManager.IMPORTANCE_HIGH)
notificationChennal2.description = "Notification from service"
notificationChennal2.setShowBadge(true)
val manager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// manager.createNotificationChannel(notificationChannel)
// manager.createNotificationChannel(notificationChennal2)
var list: List =
arrayListOf(notificationChannel, notificationChennal2)
manager.createNotificationChannels(list)
}
}
}
Step 2: Create a notification method in MainActivity file with the notification channel
MainActivity.kt
button2.setOnClickListener {
createNotification()
}
//Create location notification using channel id
fun createNotification() {
count++
val intent = Intent(this, MainActivity::class.java)
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 1, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notification: Notification = Notification.Builder(this, CHANNEL_1_ID)
.setContentTitle("Notification Title $count")
.setContentText("Notification text")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(
BitmapFactory.decodeResource(
this.resources,
R.drawable.ic_launcher_foreground
)
)
.setContentIntent(pendingIntent)
.build()
val manager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
manager.notify(1, notification)
}
}
You can see full source code from below link
https://github.com/AndroidManikandan5689/Notification-in-Foreground-Service-Android
Demo screenshots:
Comments
Post a Comment