How to implement notifications in android studio?

top banner

How to implement notifications in android studio?

Notifications are an essential part of a mobile application that provides an effective means of unplanned communication with the user. It does not matter whether the user is inside or outside the application; notifications inform the user about new events, news, messages, etc. Notifications provide valuable added functionality that can create a great user experience. In this article, we will discuss how to implement notifications in an Android application using Android Studio.There are two types of notifications available on Android:

  • Heads-up: These notifications appear at the top of the screen and take over the screen, interrupting any ongoing activity, to inform the user about an important event or message.
  • Notification tray: These notifications appear in the notification tray, and the user can check them later.

Now, let’s jump into the code implementation.

Step 1: Creating a new project

To begin, we need to create a new Android Studio project. Follow the below steps.1. Open Android Studio
2. Click “Start a new Android Studio project”
3. Select “Empty Activity”
4. Give the project a name and package name of your choice.
5. Select the language as java or Kotlin, whichever you prefer.
6. Click on finish.
Once done, you will have a base template of your Android application.

Step 2: Adding Permissions

Before we can create any notifications in our application, we need to add some permissions to the app manifest. Add the following permissions to the AndroidManifest.xml file.

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

• VIBRATE permission is required to enable vibration in our notifications.
• INTERNET permission is required to receive notifications over the internet.
• RECEIVE_BOOT_COMPLETED permission is required to start the app automatically once the device is booted up.

Step 3: Creating notification channels

Notifications are grouped according to notification channels. You can think of a notification channel as a group of notifications that are related to each other in some way. For example, if your app sends notifications for new messages, you might have a notification channel for each conversation.
So, let’s create a notification channel. Create a method createNotificationChannel() to create a notification channel.

private fun createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Channel 1",
            NotificationManager.IMPORTANCE_HIGH
        )
        channel.description = "This is Channel 1"
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }
}

Here, we create a notification channel with some basic details like its name and description. We also set its importance level to high, which means the notification will pop up on the screen immediately.

Step 4: Creating notification with NotificationCompat.Builder

Now that we have created a notification channel let’s create a notification with the help of NotificationCompat.Builder class.

private fun createNotification() {
    val intent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)

    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Notification from app")
        .setContentText("Hello! This is a notification from your application.")
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)

    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Channel name",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        notificationManager.createNotificationChannel(channel)
    }

    notificationManager.notify(0, notificationBuilder.build())
}

Here, we have created a notification with basic details like title and message. We have also provided the PendingIntent to open the main activity from the notification.

Step 5: Display notification on button click event

Now that we have created a notification let’s display it on a button click event. Add a button in the activity_main.xml file.

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Create Notification"
    android:layout_centerInParent="true"/>
In the MainActivity, get the button reference and attach a click listener to it.
private lateinit var button: Button
private val CHANNEL_ID = "Channel_id"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    createNotificationChannel()

    button = findViewById(R.id.button)

    button.setOnClickListener {
        createNotification()
    }
}

Step 6: Custom Notifications

Android allows us to create custom notifications using RemoteViews. RemoteViews let you use custom layouts for your notifications.

private fun createCustomNotification() {
    // Create an Intent for tapping the notification and set the appropriate flags
    val intent = Intent(this, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)

    // Create a NotificationCompat builder
    val contentView = RemoteViews(packageName, R.layout.notification_layout)
    contentView.setImageViewResource(R.id.image, R.drawable.ic_notification)
    contentView.setTextViewText(R.id.title, "Custom Title")
    contentView.setTextViewText(R.id.text, "Custom notification text")

    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setCustomContentView(contentView)
        .setAutoCancel(true)
        .setContentIntent(pendingIntent)

    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Channel name",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        notificationManager.createNotificationChannel(channel)
    }

    notificationManager.notify(0, notificationBuilder.build())
}
Here, we created a notification with a custom layout using RemoteViews. We have also set the image, title and message to the custom layout.

Step 7: Displaying Progress Bar

We can also display a progress bar in a notification to indicate the progress of a task. Here is how you can add progress bar notification in your app.

private fun createProgressNotification() {
    val CHANNEL_ID = "Channel_id2"
    val maxProgress = 100

    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Downloading")
        .setContentText("Download in progress")
        .setAutoCancel(true)
        .setOngoing(true)
        .setOnlyAlertOnce(false)

    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Channel name 2",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        notificationManager.createNotificationChannel(channel)
    }

    Thread {
        var progress = 0
        while (progress <= 100) {
            notificationBuilder.setProgress(maxProgress, progress, false)
            notificationManager.notify(1, notificationBuilder.build())
            try {
                Thread.sleep(1000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            progress += 10
        }
        notificationBuilder.setContentText("Download complete")
            .setProgress(0, 0, false)
            .setOngoing(false)
        notificationManager.notify(1, notificationBuilder.build())
    }.start()
}

Here, we added progress bar in the notification with the help of setProgress() method. We set the progress to update every second and notify the user that the download is completed once the progress reaches 100%.

Step 8: Big Picture Style Notification

We can also create a notification with Big Picture Style. Big picture style notification are used when our app needs to show an image in the notification, such as a wallpaper app. Here is how you can create a Big Picture Style Notification.

private fun createBigPictureNotification() {
    val CHANNEL_ID = "Channel_id3"

    val bigPictureStyle = NotificationCompat.BigPictureStyle()
        .bigPicture(BitmapFactory.decodeResource(resources, R.drawable.background))
        .bigLargeIcon(null)

    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Big Picture Style Notification")
        .setContentText("This is a big picture style notification")
        .setAutoCancel(true)
        .setStyle(bigPictureStyle)

    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Channel name 3",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        notificationManager.createNotificationChannel(channel)
    }

    notificationManager.notify(2, notificationBuilder.build())
}

Here, we added an image to the notification using the Big Picture Style so that the user can see the full-sized image when they expand the notification.

Conclusion

In this tutorial, we discussed how to implement notifications in an Android application with the help of a NotificationCompat.Builder class. We also saw how to create Notification Channels, handle button clicks, and create custom notifications using RemoteViews. We explored creating progress bar notifications and Big Picture Style Notifications. Implementing notifications is an essential part of an android developer’s daily routine, and we hope this tutorial has helped you learn how to display notifications in your Android application.

Leave a Reply

Your email address will not be published. Required fields are marked *