Creating Custom Notifications in Android: A Step-by-Step Guide
Custom notifications in Android can add an extra layer of personalization and functionality to your app. With custom notifications, you can…
Custom notifications in Android can add an extra layer of personalization and functionality to your app. With custom notifications, you can display information in a unique way and even include interactive elements. In this blog, we’ll explore the steps involved in creating custom notifications in Android.
Step 1: Create a Notification Channel
Before we dive into creating custom notifications, we need to create a notification channel. Notification channels allow users to customize how they receive notifications from your app. To create a notification channel, add the following code to your app’s onCreate method:
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "My Notification Channel"
val descriptionText = "This is my custom notification channel"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel("myChannelId", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Make sure to change the name and description to fit your app’s needs. The channel ID can also be changed, but make sure to use the same ID when creating your custom notification.
Step 2: Create a Custom Layout for Your Notification
To create a custom notification layout, create an XML layout file in your app’s res/layout folder. For this example, we’ll create a layout that displays a title and a message:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:textSize="14sp" />
</RelativeLayout>
Step 3: Create a Notification Builder
Now that we have our notification channel and custom layout, we can create a notification builder. The notification builder is responsible for constructing the notification and setting its content. Here’s an example notification builder:
private fun createNotification() {
val notificationBuilder = NotificationCompat.Builder(this, "myChannelId")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("My Custom Notification")
.setContentText("This is a custom notification in Kotlin!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
val notificationManager = NotificationManagerCompat.from(this)
notificationManager.notify(1, notificationBuilder.build())
}
This code creates a notification builder and sets the small icon, title, and text of the notification. We also set the priority to high so that the notification will appear as a heads-up notification. Finally, we use NotificationManagerCompat to notify the user with the custom notification.
Step 3: Trigger the Notification
Now that we have created the notification, we need to trigger it. We can do this by calling the createNotification() function from a button click or any other trigger event. Add the following code to your MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel()
button.setOnClickListener {
NotificationManagerImpl(requireContext()).createNotification()}
}
The full Code for this class is here
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
interface INotification {
fun createNotification()
}
class NotificationManagerImpl(private val context: Context) : INotification {
fun createNotificationChannel(): NotificationManager {
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "My Notification Channel"
val descriptionText = "This is my custom notification channel"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("myChannelId", name, importance).apply {
description = descriptionText
}
notificationManager.createNotificationChannel(channel)
}
return notificationManager
}
override fun createNotification() {
val view = RemoteViews(context.packageName, R.layout.notification_layout)
// Create expanded view if required
val expandedView = RemoteViews(context.packageName, R.layout.notification_layout_expanded)
view.setTextViewText(R.id.title, "Custom Title")
expandedView.setTextViewText(R.id.title, "Custom Title")
expandedView.setTextViewText(R.id.message, "Custom Message")
val notificationBuilder = NotificationCompat.Builder(context, "myChannelId")
// Custom Decoration for Notification
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
// Mandatory fields
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("My Custom Notification")
.setContentText("This is a custom notification in Kotlin!")
// end of mandatory fields
// setting the custom collapsed and expanded views
.setCustomContentView(view)
.setCustomBigContentView(expandedView)
.setPriority(NotificationCompat.PRIORITY_HIGH)
val notificationManager = createNotificationChannel()
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
notificationManager.notify(1, notificationBuilder.build())
}
}
Conclusion In this blog post, we walked through the steps to create a custom notification in Kotlin. We first created a notification channel, then created a notification using NotificationCompat.Builder, and finally triggered the notification from a button click. With these steps, you can create custom notifications that enhance the user experience of your Android app.
Setup your Push Notification Server using Firebase
In today’s digital age, push notifications play a crucial role in engaging users and driving user retention for mobile…medium.com