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.

4.2 (22) · 1 Review

Download materials
Save for later
Share

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.

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.

Android Notifications

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:

  1. Create a notification channel.
  2. Register the notification channel.
  3. Create a notification.
  4. 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:

  1. Safety checked the OS version for API 26 and greater.
  2. Created a unique name for the notification channel. The name and description are displayed in the application’s Notification settings.
  3. 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:

  • PRIORITY_MIN
  • PRIORTY_MAX
  • PRIORITY_LOW
  • PRIORTY_HIGH
  • PRIORITY_DEFAULT
  1. Create the unique channelId for this app using the package name and app name.
  2. Use NotificationCompat.Builder to begin building the notification.
  3. Set a small icon to be display in the notification shade. This is the only required attribute.
  4. Set a title for the notification.
  5. Set content for the notification.
  6. Set the style of the notification style to NotificationCompat.BigTextStyle().
  7. 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:
  8. 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:

  1. Created an Intent to launch the MainActivity.
  2. Wrapped the Intent in a PendingIntent, created through the getActivity() method which returns a description of an Activity to be launched.
  3. Called setContentIntent() to attach it to the NotificationCompat.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:

  1. Used the app’s Context to get a reference to NotificationManagerCompat.
  2. Called notify() on the NotificationManager 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!

Taking it a step further with Alarms

Issuing a notification after an action is performed is cool, but you are building a reminder application to administer medicine to your pets based on a schedule. This requires you to issue the notifications at some point in the future. The AlarmManager system service allows you to do just that. Notice, each item in the list of reminders includes the days and time to administer the medicine. You will use this information to schedule the alarms in the next section.