Platform
Docs
Solutions
ContactLog In

Get started sending notifications with Courier in minutes, not days!

We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.

Sign up

Mastering Android Push Notifications header
GUIDE

Mastering Android Push Notifications: A Guide Using Courier’s SDK

Adam Searle

August 31, 2023

Push notifications play a critical role in our digital world. They’re an essential tool for driving user engagement, ensuring retention, and delivering real-time updates, but implementing them in Android can be a complex task. Engineering teams are tasked with not only the technical implementation but also the logic that encompasses the entire notification experience. This includes sequencing notifications across multiple devices, managing tokens, complying with regional regulations, localizing notifications, and respecting user preferences. The challenge is far greater than just triggering a message.

Enter Courier, a platform designed to streamline this process. Courier’s Android SDK provides a comprehensive solution for push notifications, simplifying the complex task of managing product-triggered communications across different platforms.

In this tutorial, we will focus on Courier's push notification capabilities within Android apps, covering the setup process, key features, and how to send a test push notification. By the end, you’ll see how Courier can make managing Android push notifications a more manageable task, leaving you with more time to focus on creating a great user experience.

You can find the finished project at this GitHub repo.

Setting up the development environment

Before diving into the code, make sure you have all the tools and accounts you need. To work with the Courier SDK, you’ll need:

  • A Courier account. If you don’t have one yet, you can sign up here. (Don’t worry, everything we are going to do in this tutorial is free!)
  • Android SDK version 23 or later. Your Android Studio project should be set to use a minimum Android SDK version of 23. Ensure that this is set in your project’s Gradle configuration. You can do this by navigating to your build.gradle.kts file at the app level and ensuring that android.defaultConfig.minSdk is set to 23.
  • A Firebase account. Firebase is a requirement for Courier’s push notifications, as it handles the delivery of notifications to your Android devices. Your Android Studio project will need to be set up to use the Firebase SDK. First, add an Android app to your project in Firebase, and then follow the steps provided. If you already have an Android project in Firebase you want to use, go to your Firebase Android project, and then go to Project Settings > See SDK instructions and follow the steps there to add the google-services.json file to your project and to add the Firebase SDK to your Gradle build files.

Note: This tutorial assumes you are using the official IDE for Android development, Android Studio (Giraffe or later versions), and writing in Kotlin. If you’re not already using Android Studio, you can download it from the official website. It comes bundled with the Android SDK that you’ll need for this tutorial. Covering the basics of Android Studio is not within the scope of this article, but if you need help getting started, check out the official Android Studio documentation.

With these prerequisites met, you can now install the Courier SDK in your Android project by following these steps.

  1. First, add JitPack repository support to your settings.gradle.kts file. JitPack is a repository where the Courier SDK package is located.
1
pluginManagement {
2
repositories {
3
..
4
maven { url = uri("https://jitpack.io") }
5
}
6
}
7
8
dependencyResolutionManagement {
9
repositories {
10
..
11
maven { url = uri("https://jitpack.io") }
12
}
13
}
  1. Next, add the Courier SDK as a dependency in your app-level build.gradle.kts file. This includes the SDK in your project, allowing you to use its classes and functions.
1
dependencies {
2
implementation("com.github.trycourier:courier-android:2.0.2")
3
}
  1. Lastly, initialize the SDK. This step grants Courier access to SharedPreferences, which is an Android class that allows you to store key-value pairs persistently. In this case, Courier uses SharedPreferences to keep track of the device token and other necessary information to manage push notifications effectively.

You can do this in your Application class. If you’re starting from scratch, create a Kotlin class called MyApplication and paste this code in:

1
package com.example.courierpush
2
3
import android.app.Application
4
import com.courier.android.Courier
5
import ...
6
7
class MyApplication: Application() {
8
override fun onCreate() {
9
super.onCreate()
10
Courier.initialize(this)
11
}
12
}

Make sure to use the correct package reference at the top and include any necessary imports. The Courier SDK initialization should occur before using other parts of the SDK.

Also, check that you have the name variable set correctly inside your AndroidManifest.xml, like so:

1
<application
2
android:name=".MyApplication"
3
android:allowBackup="true"
4
... >
5
</application>

With these steps complete, you’re ready to dive into the world of push notifications with Courier. We’ll now explain the basics and how to configure them in your app.

Push notification basics with Courier

In the world of Android app development, managing push notifications can be a complex endeavor. Courier’s Android SDK simplifies this process by automating the management of push notification device tokens, tracking user interactions with notifications, and streamlining how your application requests and checks push notification permissions.

For this tutorial, we’ll be using Firebase Cloud Messaging (FCM) as the push notification provider. FCM is a widely adopted platform for push notifications known for its reliability and scalability. To set up FCM with Courier, follow the instructions provided in Courier’s FCM setup documentation. Note that this is separate from the implementation of the Firebase SDK within your application. You must both set up FCM as a provider under Channels in the Courier dashboard and implement the SDK into your project (step 3 from “Setting Up the Development Environment” above). Setting up FCM as a provider establishes the connection between Courier and FCM, while implementing the Firebase SDK allows your app to receive and handle push notifications sent through FCM.

Once you’ve set up FCM with Courier, you’ll be able to easily send push notifications to your app, customizing their content and appearance as per your requirements. In the next sections, we will delve deeper into how to configure your Android app to receive push notifications via Courier and FCM and demonstrate how to send a test push notification.

Configuring Courier for push notifications

Configuring your Android app for push notifications using the Courier Android SDK involves two key steps: creating the CourierService file and adding the CourierService entry to your app’s AndroidManifest.xml file.

Create the CourierService file

Firstly, create a CourierService file. This file will extend the FirebaseMessagingService and is responsible for handling the received push notifications.

Create a Kotlin class file called MyCourierService and paste in the following code:

1
package com.example.courierpush
2
3
import com.courier.android.service.CourierService
4
import com.courier.android.notifications.presentNotification
5
import com.google.firebase.messaging.RemoteMessage
6
7
class MyCourierService : CourierService() {
8
9
override fun showNotification(message: RemoteMessage) {
10
super.showNotification(message)
11
// This is where you can customize the notification shown to your users
12
// message.presentNotification(...) is used to get started quickly and not for production use.
13
message.presentNotification(
14
context = this,
15
handlingClass = MainActivity::class.java,
16
icon = android.R.drawable.ic_dialog_info
17
)
18
}
19
}

Update the AndroidManifest.xml file

Next, you need to declare the CourierService in your AndroidManifest.xml file. This is necessary so that the Android system knows that this service exists and can start it when a new push notification arrives. Here’s an example of what you need to add:

1
<application>
2
3
<service
4
android:name=".MyCourierService"
5
android:exported="false">
6
<intent-filter>
7
<action android:name="com.google.firebase.MESSAGING_EVENT" />
8
</intent-filter>
9
</service>
10
11
</application>

In this code snippet, replace .MyCourierService with your CourierService file. The intent filter with the action com.google.firebase.MESSAGING_EVENT ensures that this service will be started by the system when a new FCM message is received.

(It’s not part of this example, but if you’re interested in how to handle a user’s interaction with a push notification, your main activity or any activity that you want to open from a push notification click should extend CourierActivity. This allows Courier to handle notification clicks and track deliveries effectively.)

In the next section, we will dive into sending push notifications and examine the processes of user authentication with Courier and registration for notifications.

Sending push notifications using the Android SDK

Sending push notifications with Courier involves two main steps:

  1. Registering a user’s device with Courier
  2. Making a request to the Courier API to send a notification

Register a user’s device with Courier

After setting up your Android application to receive notifications, the next step is to register your device with Courier. This automatically gets the FCM token from Firebase and then sends it to Courier.

In your application, wherever you want to start registering the device for push notifications (for example, at user login or app start), use the signIn() function to connect your user with Courier.

1
class MyApplication : Application() {
2
override fun onCreate() {
3
super.onCreate()
4
5
// initialize Courier
6
Courier.initialize(this)
7
8
// Sign in to Courier
9
CoroutineScope(Dispatchers.Main).launch {
10
Courier.shared.signIn(
11
accessToken = "<YOUR_AUTH_KEY>",
12
clientKey = "nil",
13
userId = "<YOUR_USER_ID>"
14
)
15
}
16
}
17
}

This code fetches the FCM registration token and then sends it to Courier. As you’re not using Courier Inbox, you don’t need to set the clientKey for this example, and can leave it as nil. Replace <YOUR_AUTH_KEY>with your API key, and replace <YOUR_USER_ID> with your Courier user ID, found in the users area of the Courier app.

This step is simple, but this is where all the magic happens. By signing a user in like this, Courier takes care of all the tricky token management behind the scenes. At this point, everything should be set up and good to go. All you need to do now is send the notification.

Send a notification

With the device registered, you can now send a notification. This is done via a POST request to the Courier Send API. The Courier Send API allows you to define the content of the notification and specify the recipient(s).

Before sending, perform the following steps:

  1. Make sure you have connected a physical device.
  2. Ensure developer options are turned on for the device. This will vary for each device, but here is an example of how to do it.
  3. In Android Studio, run your app on your Android device.

Run Android on your device from Android studio

  1. Once you’re running your new app on your device, you may need to go to the settings for the new app and allow notifications.

You can make the POST request using any HTTP client of your choice. Here’s an example using cURL.

1
curl --request POST \
2
--url https://api.courier.com/send \
3
--header 'Authorization: Bearer YOUR_AUTH_KEY' \
4
--header 'Content-Type: application/json' \
5
--data '{
6
"message": {
7
"to": {
8
"user_id": "YOUR_USER_ID"
9
},
10
"content": {
11
"title": "Hey there 👋",
12
"body": "Have a great day 😁"
13
},
14
"routing": {
15
"method": "all",
16
"channels": [
17
"firebase-fcm"
18
]
19
}
20
}
21
}'

In the request above, replace YOUR_AUTH_KEY with your Courier auth key and YOUR_USER_ID with the ID of the user you want to send the notification to. This will be the same user that you signed in previously, likely your own user ID.

That’s it! Your Android app is now set up to send and receive push notifications using Courier and FCM.

Remember, the actual process of making a request to the Courier API can be handled in many ways, not just through cURL. For instance, you could make this request from a server-side script or from within your mobile app using an HTTP client library. The cURL example above is just a simple demonstration. The best practice is to trigger these requests on the server side and not from the client to ensure your Courier auth key is kept secure.

You can also use the Courier dashboard to design a notification, then send that notification. There are various ways to do this, but one way could be via cURL, like so: \

1
curl --request POST \
2
--url https://api.courier.com/send \
3
--header 'Authorization: Bearer YOUR_AUTH_KEY' \
4
--data '{
5
"message": {
6
"to": {
7
"user_id": "YOUR_USER_ID"
8
},
9
"template": "YOUR_NOTIFICATION_TEMPLATE_ID",
10
"data": {}
11
}
12
}'

Advantages of the Courier Android SDK

Having gone through the process of setting up push notifications with Courier, let’s dive deeper into the specific features that make the Courier Android SDK a powerful tool for developers.

Efficient management of tokens

One of the significant advantages of the Courier Android SDK is its ability to handle tokens effectively.

Push notification tokens are unique identifiers assigned to each mobile device by push notification services like Firebase Cloud Messaging (FCM) for Android. These tokens are essential for routing push notifications to specific devices, ensuring the right users receive the intended messages.

When not handled automatically, token management can become complex as the user base grows. Manually storing tokens in databases and managing token refreshes can lead to errors and inconsistencies. Additionally, handling tokens separately from other application data can result in data discrepancies and time-consuming development efforts.

The Courier Android SDK addresses these challenges by automatically synchronizing FCM tokens with Courier. This approach saves development time, ensures data consistency, and provides a more robust and error-free system for push notification delivery. With automated token management, developers can focus on other critical aspects of the application while still delivering notifications reliably to users.

User tracking

Another advantage is the ability to track user status with ease. The SDK can seamlessly track when a user signs in or out, providing you with more insights about your user base. This could help you to tailor your app’s user experience based on user behavior.

1
// When a user signs in
2
Courier.identify(userId);
3
4
// When a user signs out
5
Courier.logout();

These are just a couple of examples of the benefits of the Courier Android SDK. It’s designed to streamline push notification management, making it easier to focus on what matters: building great app experiences for your users.

Conclusion

Throughout this article, we have explored the process of setting up and sending push notifications in an Android app using the Courier Android SDK. We also touched on some of the unique features of the SDK that make managing notifications easier and more efficient.

By leveraging Courier, you can send push notifications to your users directly and manage user engagement in a more streamlined manner. Courier can also handle FCM tokens automatically and track user status, giving you more time to focus on the core functionalities of your app.

Remember, this guide provides a basic setup. The Courier Android SDK has much more to offer, including customizing notifications and tailoring them to your app’s specific needs.

Whether you’re looking to improve an existing application or starting a new project, we hope this guide has provided you with a clear understanding of how to implement and optimize push notifications using Courier.

For more detailed information about all the features of the Courier Android SDK, take a look at the Courier Android SDK GitHub documentation or sign up for Courier. Happy coding!

Get started sending notifications with Courier in minutes, not days!

We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.

Sign up

More from Guide

Best Practices for SMS Tools and Text Message API Implementation thumbnail
GUIDE

Best Practices for SMS Tools and Text Message API Implementation

Courier delivers easy access to the messaging providers you use, all in a familiar language and with documentation that’s comprehensive and easy to follow. This page will give you an overview of the SMS providers supported by Courier’s text messaging API, so that you can assess if moving towards a messaging management tool is right for you.

Oleksii Klochai

Oleksii Klochai

November 14, 2023

push-notification-api-thumbnail
GUIDE

How to Use a Push API to Send Notifications from your Mobile App

This article dives into the topic of push notifications and explains how to use Courier’s push API to deliver simple, one-time push notifications to Android or iOS systems.

Oleksii Klochai

Oleksii Klochai

November 08, 2023

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.