Kotlin Android app development course, sound and vibration notifications

Written on: October 4, 2023

1. Overview

This tutorial explains how to implement sound and vibration notifications in Android apps using Kotlin. The notification system is a crucial element that allows interaction with users in Android apps, and through this course, you will understand and implement basic notification functionalities.

Sound and vibration notifications can be utilized in various situations to grab the user’s attention. For example, they are used when a message or notification arrives or when a specific event occurs.
This tutorial will cover not only the basic usage of notifications but also how to create custom notification channels to apply various sounds and vibration patterns.

2. Setting Up the Development Environment

This tutorial is based on Android Studio. Android Studio is the most widely used integrated development environment (IDE) for Android app development. You can set up the environment by following the steps below.

  1. Install Android Studio: Download and install the latest version of Android Studio. Make sure to select the option to include all necessary components during installation.
  2. Kotlin Support: Android Studio natively supports Kotlin, so you don’t need to install a Kotlin plugin. Just select the Kotlin option when creating a new project.
  3. Create a Project: Start a new project by selecting the ‘Empty Activity’ template. Choose the project name and package name according to your preference.

3. Understanding the Notification System

The notification system in Android allows users to receive information about specific events and displays notifications in the top status bar. Notifications can take various forms and can include sound, vibration, text, and images.

To use notifications, you need to use the NotificationCompat.Builder class. This class allows you to set the details of the notification, which is displayed through the NotificationManager.

4. Implementing Basic Notifications

First, let’s look at a simple example of implementing a basic notification. In this example, we will create a simple app that displays a notification when a button is clicked.
Use the code below to add to your MainActivity.kt file.

4.1 MainActivity.kt


                package com.example.soundvibrationnotification

                import android.app.NotificationChannel
                import android.app.NotificationManager
                import android.content.Context
                import android.os.Build
                import android.os.Bundle
                import android.view.View
                import android.widget.Button
                import androidx.appcompat.app.AppCompatActivity
                import androidx.core.app.NotificationCompat

                class MainActivity : AppCompatActivity() {

                    private val channelId = "default_channel_id"
                    private val notificationId = 1

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

                        createNotificationChannel()

                        val button: Button = findViewById(R.id.button_notify)
                        button.setOnClickListener { sendNotification() }
                    }

                    private fun createNotificationChannel() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            val channel = NotificationChannel(
                                channelId,
                                "Default Channel",
                                NotificationManager.IMPORTANCE_DEFAULT
                            )
                            val notificationManager: NotificationManager = getSystemService(
                                Context.NOTIFICATION_SERVICE
                            ) as NotificationManager
                            notificationManager.createNotificationChannel(channel)
                        }
                    }

                    private fun sendNotification() {
                        val builder = NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.drawable.ic_notification)
                            .setContentTitle("Sound and Vibration Notification")
                            .setContentText("This is a default notification.")
                            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

                        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                        notificationManager.notify(notificationId, builder.build())
                    }
                }
            

Explanation of the example code:

  • Channel Creation: For Android version 8.0 (API 26) and above, you need to create a notification channel. This allows users to group notifications and control them according to their preferences.
  • Sending Notification: Using NotificationCompat.Builder, set the title, content, and icon of the notification, then send the notification via the notify() method.

If you run the above code along with the activity_main.xml file, you will see that a notification appears when you click the ‘Sound and Vibration Notification’ button.

5. Adding Sound Notifications

Now, let’s add sound to the notifications. Add a sound file to the res/raw folder and dynamically assign the sound when setting up the notification.
Modify the example code below to implement sound notifications.

5.1 Adding Sound Files

Add a sound file to the res/raw folder. For example, let’s assume you added a sound file named ‘notification_sound.mp3’.

5.2 Modify MainActivity.kt


                private fun sendNotification() {
                    val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                    val builder = NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle("Sound and Vibration Notification")
                        .setContentText("This is a sound notification.")
                        .setSound(soundUri) // Add sound
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

                    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                    notificationManager.notify(notificationId, builder.build())
                }
            

Now, a default notification sound will play when the notification is displayed.

6. Adding Vibration Notifications

To add a vibration feature to the notifications, let’s learn how to set a vibration pattern and configure it using NotificationCompat.Builder.

6.1 Adding Vibration Permission

You need to add vibration permission to the AndroidManifest.xml file. Please declare the permission in the test code as shown below.


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

6.2 Modify MainActivity.kt


                private fun sendNotification() {
                    val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                    val vibratePattern = longArrayOf(0, 200, 100, 300)
                    
                    // Set vibration
                    val builder = NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_notification)
                        .setContentTitle("Sound and Vibration Notification")
                        .setContentText("This is a vibration notification.")
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) // Add sound
                        .setVibrate(vibratePattern) // Add vibration pattern
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

                    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                    notificationManager.notify(notificationId, builder.build())
                    
                    // Start vibration
                    vibrator.vibrate(vibratePattern, -1)
                }
            

In this code, the vibration pattern is set, and it vibrates along with the notification.

7. Custom Notification Channels

Now let’s create a custom notification channel with various options. Each channel can have sound, vibration, and notification importance settings.

7.1 Adding a Channel


                private fun createNotificationChannel() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val channel = NotificationChannel(
                            channelId,
                            "Custom Channel",
                            NotificationManager.IMPORTANCE_HIGH
                        )
                        channel.description = "Description of Custom Channel"
                        channel.enableLights(true)
                        channel.lightColor = Color.RED
                        channel.enableVibration(true)
                        channel.vibrationPattern = longArrayOf(0, 400, 200, 400)

                        val notificationManager: NotificationManager = getSystemService(
                            Context.NOTIFICATION_SERVICE
                        ) as NotificationManager
                        notificationManager.createNotificationChannel(channel)
                    }
                }
            

The above code creates a custom channel that adds various functionalities to notifications.

8. Conclusion

In this tutorial, we learned the basic methods for implementing sound and vibration notifications in Android apps using Kotlin.
Through the notification system, users can respond in real-time to events occurring in the application.
We learned about the importance of notifications, how to implement them, and various configuration methods to enhance user experience.
Based on this tutorial, try implementing a complex notification system.

Additionally, explore and experiment with various notification features such as personalized notifications, actionable notifications, and notification grouping.
I hope you can develop excellent Android applications that utilize a variety of features in the future.