In Android app development, informing users or providing alerts about important events is a crucial feature. In this process, notifications can be utilized to maximize interaction with users. This course will provide a detailed introduction to creating basic notifications using Kotlin and the various modifications of notifications.
Overview of Notifications
A notification is a UI element used to convey important information when users interact with the app. Notifications consist of the following components:
- Title: Summarizes the main message of the notification.
- Content: Provides detailed information about the notification.
- Icons: Icons that help visually identify the notification.
- Action: Defines what action to take when the notification is clicked.
Preparation Steps for Implementing Notifications
Several preparatory steps are required to create notifications. The following are the steps to implement notifications.
- Create an Android project: Start a new project in
Android Studio
. - Set necessary permissions: Since notifications are controlled by the system by default, you need to grant notification permissions in the app settings.
Creating Notifications with Kotlin
1. Project Setup
Create a new project in Android Studio and set up the following basic configurations.
- Project Language: Kotlin
- Target SDK: Android 8.0 (API 26) or higher
2. Adding Gradle Dependencies
No special libraries are required to use notification features, but it is always good to rely on the latest SDK. Add the following configuration to the build.gradle
file.
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
}
3. Notification Creation Code
The basic code to create a notification is as follows. This code is a simple example that shows a notification when a button is clicked.
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.core.app.NotificationCompat
class MainActivity : AppCompatActivity() {
private lateinit var notificationManager: NotificationManager
private val CHANNEL_ID = "example_channel"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
createNotificationChannel()
val notifyButton: Button = findViewById(R.id.notifyButton)
notifyButton.setOnClickListener {
showNotification()
}
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Example Channel"
val descriptionText = "Channel for example notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
notificationManager.createNotificationChannel(channel)
}
}
private fun showNotification() {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Hello, World!")
.setContentText("This is a sample notification!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notificationManager.notify(1, builder.build())
}
}
4. XML Layout Configuration
You need to add the button called in the above example to the layout. The following is the content of the activity_main.xml
file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/notifyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:layout_centerInParent="true"/>
</RelativeLayout>
Various Notification Options
In addition to basic notifications, various options allow you to customize the style of notifications.
1. Big Text Style
Using big text style allows you to convey more information.
private fun showBigTextNotification() {
val bigTextStyle = NotificationCompat.BigTextStyle()
.bigText("This is a more detailed description of the notification. More text can be added here to give users detailed contextual information.")
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Big Text Notification")
.setStyle(bigTextStyle)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
notificationManager.notify(2, builder.build())
}
2. Image Notifications
You can enhance the visual effect by adding images to the notification.
private fun showImageNotification() {
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Image Notification")
.setContentText("This notification contains an image!")
.setLargeIcon(bitmap)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(bitmap))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
notificationManager.notify(3, builder.build())
}
Defining Actions for Notifications
You can add various actions to notifications to allow users to perform multiple tasks. The following example adds ‘Accept’ and ‘Decline’ buttons.
private fun showActionNotification() {
val acceptIntent = Intent(this, AcceptActivity::class.java)
val acceptPendingIntent = PendingIntent.getActivity(this, 0, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val declineIntent = Intent(this, DeclineActivity::class.java)
val declinePendingIntent = PendingIntent.getActivity(this, 1, declineIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Action Required")
.setContentText("Please accept or decline.")
.addAction(R.drawable.ic_accept, "Accept", acceptPendingIntent)
.addAction(R.drawable.ic_decline, "Decline", declinePendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
notificationManager.notify(4, builder.build())
}
Deleting and Updating Notifications
You can delete or update notifications while running. Users can update images or overwrite existing content.
private fun updateNotification() {
val updatedBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Updated Notification")
.setContentText("This notification has been updated!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
notificationManager.notify(4, updatedBuilder.build())
}
Managing Notifications
To allow users to manage multiple notifications, you need to assign a unique ID to each notification. Using unique IDs allows you to remove or update specific notifications.
private fun removeNotification() {
notificationManager.cancel(4)
}
Android Notification Channels
On Android O (API 26) and higher, you can use notification channels to define the nature of notifications created by the app. Depending on user settings, the visual and auditory characteristics of notifications can be modified. Through channels, users can set the priority, sound, vibration, and more for each notification.
Conclusion
If you have learned the basics of using notifications based on the content presented in this article, you can now utilize various notification types and designs to enhance user experience. Use notifications appropriately to increase the value of your app and strengthen communication with users!