Most Popular
We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.
Sign up
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.
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:
build.gradle.kts
file at the app level and ensuring that android.defaultConfig.minSdk
is set to 23.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.
settings.gradle.kts
file. JitPack is a repository where the Courier SDK package is located.1pluginManagement {2repositories {3..4maven { url = uri("https://jitpack.io") }5}6}78dependencyResolutionManagement {9repositories {10..11maven { url = uri("https://jitpack.io") }12}13}
build.gradle.kts
file. This includes the SDK in your project, allowing you to use its classes and functions.1dependencies {2implementation("com.github.trycourier:courier-android:2.0.2")3}
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:
1package com.example.courierpush23import android.app.Application4import com.courier.android.Courier5import ...67class MyApplication: Application() {8override fun onCreate() {9super.onCreate()10Courier.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<application2android:name=".MyApplication"3android: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.
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 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.
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:
1package com.example.courierpush23import com.courier.android.service.CourierService4import com.courier.android.notifications.presentNotification5import com.google.firebase.messaging.RemoteMessage67class MyCourierService : CourierService() {89override fun showNotification(message: RemoteMessage) {10super.showNotification(message)11// This is where you can customize the notification shown to your users12// message.presentNotification(...) is used to get started quickly and not for production use.13message.presentNotification(14context = this,15handlingClass = MainActivity::class.java,16icon = android.R.drawable.ic_dialog_info17)18}19}
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<service4android:name=".MyCourierService"5android: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 with Courier involves two main steps:
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.
1class MyApplication : Application() {2override fun onCreate() {3super.onCreate()45// initialize Courier6Courier.initialize(this)78// Sign in to Courier9CoroutineScope(Dispatchers.Main).launch {10Courier.shared.signIn(11accessToken = "<YOUR_AUTH_KEY>",12clientKey = "nil",13userId = "<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.
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:
You can make the POST request using any HTTP client of your choice. Here’s an example using cURL.
1curl --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: \
1curl --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}'
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.
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.
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 in2Courier.identify(userId);34// When a user signs out5Courier.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.
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!
We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.
Sign up
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
November 14, 2023
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
November 08, 2023
Free Tools
Comparison Guides
Send up to 10,000 notifications every month, for free.
Get started for free
Send up to 10,000 notifications every month, for free.
Get started for free
© 2024 Courier. All rights reserved.