Android Notifications Tutorial: Getting Started
In this Android Notifications tutorial, you will learn how to create an App that allows you to set reminders at different schedules. By Kyle Jablonski.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Android Notifications Tutorial: Getting Started
20 mins
- Getting Started
- Displaying your First Notification
- Create a Notification Channel
- Register the Notification Channel
- Create a Notification
- Pending Intents
- Notifying the Manager
- Taking it a step further with Alarms
- Creating an Alarm to send a Notification
- 1. Pet Type Notification Channel’s
- Channels & Importance
- 2. Alarm Time
- 3. Creating the PendingIntent
- 4. Scheduling the Alarm
- 5. Create a BroadcastReceiver
- 6. Create the Notification and Issue It
- 1. Create a Group Notification
- 2. Create a Notification
- 3. Add an Action to the Notification
- Where to Go From Here?
In this tutorial, you will be issuing Notifications to remind yourself to take care of those dearest to your heart: your pets.
Notifications are a handy way to add features and functionality to your application without your users directly interacting with them. For example, they can be used to add playback controls to a music app, provide quick actions to respond to sms or email and alert about breaking news stories among many others.
You will work with the Notification APIs to issue Notifications with the NotificationManager, schedule Alarms with the AlarmManager and enhance them by using groups, channels and actions.
Note: This tutorial assumes you have basic knowledge of Kotlin and Android. If you’re new to Android, check out our Android tutorials. If you know Android, but are unfamiliar with Kotlin, take a look at Kotlin For Android: An Introduction. I also assume you have knowledge of the compatibility libraries to backport functionality to an older version of the OS.
Note: This tutorial assumes you have basic knowledge of Kotlin and Android. If you’re new to Android, check out our Android tutorials. If you know Android, but are unfamiliar with Kotlin, take a look at Kotlin For Android: An Introduction. I also assume you have knowledge of the compatibility libraries to backport functionality to an older version of the OS.
Getting Started
Start by downloading the project materials by using the Download Materials button found at the top or bottom of this tutorial. Unzip the contents to a folder and remember the location. Open Android Studio and, at the splash page, choose Open an existing Android Studio Project, navigate to the recently downloaded folder and select PetMedicineReminder-Starter.
Once the starter project finishes loading and building, run the application on a device or emulator.
Once the app is running, load the sample data by selecting the overflow icon in the top right and tapping Load Sample Data. When the data loads, you should see a listing of reminders to administer medications to a few pets.
Not super exciting but here is where you will display your first notification.
Displaying your First Notification
In order to display a notification, you will have to do some setup work. You will need to:
- Create a notification channel.
- Register the notification channel.
- Create a notification.
- Send a notification using NotificationManager.
Create a Notification Channel
Notification channels provide a common visual and auditory experience for notifications of a similar type. Since their introduction in API 26, you are now required to set a channel for a notification, otherwise they will not display on newer versions of Android.
Open the NotificationHelper.kt file under the notif directory and add the following code to the createNotificationChannel()
method:
fun createNotificationChannel(context: Context, importance: Int, showBadge: Boolean, name: String, description: String) { // 1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 2 val channelId = "${context.packageName}-$name" val channel = NotificationChannel(channelId, name, importance) channel.description = description channel.setShowBadge(showBadge) // 3 val notificationManager = context.getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) } }
Here you:
- Safety checked the OS version for API 26 and greater.
- Created a unique name for the notification channel. The name and description are displayed in the application’s Notification settings.
- Created the channel using the NotificationManager.
Nice work! Now you need to call this method.
Register the Notification Channel
Open the PetRx.kt application file under the root package and add the following code to the onCreate()
method:
NotificationHelper.createNotificationChannel(this, NotificationManagerCompat.IMPORTANCE_DEFAULT, false, getString(R.string.app_name), "App notification channel.")
Now that the channel is created, you can send a notification to it when the sample data is loaded.
Create a Notification
Open the NotificationHelper.kt file and navigate to createSampleDataNotification()
. Add the following code:
// 1 val channelId = "${context.packageName}-${context.getString(R.string.app_name)}" // 2 val notificationBuilder = NotificationCompat.Builder(context, channelId).apply { setSmallIcon(R.drawable.ic_stat_medicine) // 3 setContentTitle(title) // 4 setContentText(message) // 5 setStyle(NotificationCompat.BigTextStyle().bigText(bigText)) // 6 priority = NotificationCompat.PRIORITY_DEFAULT // 7 setAutoCancel(autoCancel) // 8 }
Here you:
- Create the unique
channelId
for this app using the package name and app name. - Use
NotificationCompat.Builder
to begin building the notification. - Set a small icon to be display in the notification shade. This is the only required attribute.
- Set a title for the notification.
- Set content for the notification.
- Set the style of the notification style to
NotificationCompat.BigTextStyle()
. - Set the notifications priority to the default priority. Priority indicates how much of the user’s attention the notification should draw. You will see other usages later but acceptable values include:
- PRIORITY_MIN
- PRIORTY_MAX
- PRIORITY_LOW
- PRIORTY_HIGH
- PRIORITY_DEFAULT
- Set the notification to auto cancel when tapped.
So far you have created the notification channel and began building a notification but you want to direct the user somewhere when they tap on the notification. This requires adding a PendingIntent
to the notification calling setContentIntent
when building the notification. A PendingIntent is roughly described as an action to be taken at a later point in time.
Add the following lines to the createSampleDataNotification()
method inside the apply
lambda just after setAutoCancel(autoCancel)
:
// 1 val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK // 2 val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) // 3 setContentIntent(pendingIntent)
Here you:
- Created an
Intent
to launch theMainActivity
. - Wrapped the
Intent
in aPendingIntent
, created through thegetActivity()
method which returns a description of anActivity
to be launched. - Called
setContentIntent()
to attach it to theNotificationCompat.Builder
.
Notifying the Manager
The last piece to issuing a notification is getting a reference to the NotificationManagerCompat system service and calling notify()
.
Add the following code after the apply
lambda:
// 1 val notificationManager = NotificationManagerCompat.from(context) // 2 notificationManager.notify(1001, notificationBuilder.build())
Here you:
- Used the app’s
Context
to get a reference toNotificationManagerCompat
. - Called
notify()
on theNotificationManager
passing in an identifier and the notification.
Re-run the application, delete the data from the menu Delete Data and reload it from the menu Load sample data item. If everything was successful, you should now see a notification icon in the status bar! Pull down the notification shade and you will see the full notification issued from your application indicating your sample data has loaded. Great!