Creating and sending push notifications to Android mobile using Event Notifications
Create an Event Notifications service, add a push destination for Firebase Cloud Messaging (FCM), and send messages to Android devices.
What is Event Notifications?
Event Notifications is an event notification routing service that notifies you of critical events that occur in your IBM Cloud account or triggers automated actions by using webhooks. You can filter and route event notifications from IBM Cloud services like Availability Monitoring, to email, SMS, push notifications, and webhooks.
How do clients use Android Push Notifications?
The following diagram shows you how clients use Android Push Notifications.
Objectives
This tutorial shows you how to send push notifications as follows:
- Create a mobile app with Event Notifications.
- Get FCM credentials.
- Download the code and complete the notifications setup.
- Configure and send Android Push Notifications to a mobile device.
Before you begin
You must have the following prerequisites in place:
- Download and install Android Studio so that you can import and enhance your code.
- A Google account to log in to Firebase console to get your
project_id
,private_key
, andclient_email
. - An IBM Cloud account. If you do not have one, create an IBM Cloud account.
The instructions used in this document uses FCM's HTTP v1 API. The HTTP v1 API has advantages such as secure access tokens, efficient customizations, and future proof as well as more extendable client platform versions. For more information on migrating from FCM legacy HTTP API to the HTTP v1 API, see Migrating FCM legacy HTTP API to HTTP v1 API.
Create an Event Notifications service instance
- Log in to your IBM Cloud account.
- In the IBM Cloud catalog, search and select
Event Notifications > Event Notifications
. - Select a
Region
from the list of supported regions and select apricing plan
. - Provide a
Service name
. - Select a
resource group
. - Accept the licensing agreements and terms by clicking the checkbox.
- Click
Create
.
Get FCM credentials
Firebase Cloud Messaging (FCM) is the gateway that delivers push notifications to Android devices. To set up the Android Push destination on the console, you must get your FCM credentials project_id
, private_key
, and
client_email
.
-
Go to the Firebase Console. A Google user account is required.
-
Click
Create a project
. If you are already having a project, then clickAdd Project
. -
In the
Create a project window
, enter a project name, and accept the terms and enable or disable Google analytics (optional) by selecting the toggle switch and clickContinue
. -
If Google analytics is enabled, then in the
Configure Google Analytics
window, choose theAnalytics location
, and accept the terms. -
Click
Create Project
. -
Click
Continue
when the new project is ready. -
In the navigation panel, select the
settings
icon next to theProject Overview
and selectSettings > Project settings
. -
Click the
Service Accounts
tab. -
Click Generate new private key to generate your project credentials. The downloaded file will contain:
project_id
,private_key
, andclient_email
.
Generate google-services.json
You also need to generate the google-services.json
file. Complete the following steps:
-
In the Firebase console Project overview section, under
Get started by adding Firebase to your app
section click theAndroid
icon. -
In the
Add Firebase to your Android app
window, addcom.ibm.cloud.eventnotifications.destination.android
as the Package Name. TheApp nickname
field is optional. -
Click Register app.
-
Include the package name of your application. Enter the package name in
Add Firebase to your Android app
window. TheApp nickname
field is optional. -
Click Register app. See the following example:
-
The
google-services.json
file is generated. -
Download the latest config file
google-services.json
under Your apps.
Add a generic API source
Take the following steps:
- Go to the
Sources
section of the Event Notifications dashboard. - Click
Add
and select an API Source. - Type a name and an optional description and click
Add
.
Create an Event Notifications destination
Click Destinations
in the Event Notifications console and add the following destination details:
Name
: add a name for the Destination.Description
: add an optional description for the destination.Type
: selectAndroid Push Notifications (FCM)
type from the dropdown list.- Select a destination plan: Pre-production destination or Production destination.
Pre-production destination
- select this destination as low-cost push destination, for your development and test environments.Production destination
- use the full capability of this destination. Unlimited devices and outbound messages allowed.
- Update the FCM Push Credentials with the
project_id
,private_key
, andclient_email
from the file downloaded earlier. - Click Add.
Create an Event Notifications topic
Select Topics
in the Event Notifications console and click Create
. Enter the following topic details:
Name
: enter a name for the topic.Description
: add an optional description for the topic.Source
: select a source from the dropdown list.Event type
: select event type from the dropdown list.Event sub type
: select event sub type from the event sub type dropdown list.Severity
: select severity from the severity dropdown list.Advanced conditions
: write your own custom conditions, which must follow jsonpath specifications.
Create an Event Notifications subscription
Click Subscriptions
in the Event Notifications console. Enter the following subscription details:
Click
Create to display subscription wizard.- Complete the following subscription details:
Subscription name
: name of the subscription.Subscription description
: add an optional description.
- Under the
Subscribe to a topic
section, select a topic from the drop-down list and select a destination from the destination drop-down list. Destination type
: select type underDestination
and click Add.
Set up Event Notifications Android SDK
The Android SDK enables Android apps to receive push notifications. Complete the following steps to install Event Notifications Android SDK, initialize the SDK, and register for notifications for your Android app.
-
Install Event Notifications by using Gradle.
compile 'com.ibm.cloud:eventnotifications-destination-android:0.0.1'
-
Follow event-notifications-destination-android-sdk to install the SDK.
-
When Gradle is installed, import and initialize the SDK.
import com.ibm.cloud.eventnotifications.destination.android.ENPush; String instanceGUID = "<instance_guid>>"; String destinationID = "<instance_destination_id>"; String apiKey = "<instance_apikey>"; ENPush enPush = ENPush.getInstance(); enPush.setCloudRegion(ENPush.REGION_US_SOUTH); // Set your region enPush.initialize(getApplicationContext(),instanceGUID,destinationID, apiKey);
-
When the SDK is initialized, register for push notifications.
// Register the device to Event Notifications enPush.registerDeviceWithUserId("userId",new ENPushResponseListener<String>() { @Override public void onSuccess(String deviceId) { //handle successful device registration here } @Override public void onFailure(ENPushException ex) { //handle failure in device registration here } });
-
Optionally if you can also create push tag subscription, subscribeToPushTag for push device. The subscribe API subscribes the device for a particular tag. After the device is subscribed to a particular tag, the device can receive notifications that are sent for that tag. Add the following code snippet to your Android mobile application to subscribe to a list of tags.
// Subscribe to the given tag, if tagname is not available it will first get create then push device will get subscribe to it. enPush.subscribe(tagName, new ENPushResponseListener<String>() { @Override public void onSuccess(String arg) { System.out.println("Succesfully Subscribed to: "+ arg); } @Override public void onFailure(ENPushException ex) { System.out.println("Error subscribing to Tag1.." + ex.getMessage()); } });
-
Add the notifications listener for receiving the notification in your application.
//Handles the notification when it arrives ENPushNotificationListener notificationListener = new ENPushNotificationListener() { @Override public void onReceive (final ENSimplePushNotification message){ // Handle Push Notification } };
if(enPush != null) { enPush.listen(notificationListener); }
-
When the setup is complete, run your application and register for push notifications.
Send notifications to the Android device
Use the Send notification API to send the push notification for the Android device. You can use the Node or Go admin SDK instead of calling the API directly.
Migrating FCM legacy HTTP API to HTTP v1 API
Apps using the FCM legacy HTTP API should consider migrating to the HTTP v1 API using the instructions in this section. The HTTP v1 API has advantages such as secure access tokens, efficient customizations, and future proof as well as more extendable client platform versions.
In Event Notifications, you can create an android destination by following FCM norms. For legacy HTTP API we have been providing support via two required parameters server_key
and sender_id
. For the v1 HTTP API, FCM
introduced three new parameters: project_id
, client_email
, and private_key
. The important point to observe here is both legacy and v1 HTTP APIs are mutually exclusive and we have taken care of that in
Event Notifications.
Here's how you can migrate from an old configuration to a new one.
-
Under your existing FCM Android destination configuration you will find
server_key
andsender_id
provided. Now you just need to update the existing destination by providingproject_id
,client_email
, andprivate_key
USING the PATCH /destinations/{id} API call.Existing Android destination configuration:
{ "name": "Existing android destination", "description": "Android destination with legacy parameters", "type": "push_android", "config": { "params": { "sender_id": "xxxxxx", "server_key": "xxxxxx" } } }
New Android destination configuration:
{ "name": "New android destination", "description": "Android destination with V1 HTTP parameters", "type": "push_android", "config": { "params": { "project_id": "xxxxx", "private_key": "xxxxx", "client_email": "abc@xyz.pqr" } } }
Examples of FCM payload changes
-
FCM Legacy HTTP API
{ "notification": { "title": "Incidunt qui porro sequi iste assumenda esse animi.", "body": "Minus reprehenderit ut nisi. Aut earum qui est iure eos fuga." }, "data": { "name": "Willie Greenholt", "description": "Voluptas voluptatem sed quia expedita error a at sit rerum. Numquam unde debitis incidunt qui impedit et necessitatibus. Cupiditate exercitationem enim ut laborum itaque et." } }
-
FCM HTTP v1 API
{ "message": { "android": { "notification": { "title": "Incidunt qui porro sequi iste assumenda esse animi.", "body": "Minus reprehenderit ut nisi. Aut earum qui est iure eos fuga." }, "data": { "name": "Willie Greenholt", "description": "Voluptas voluptatem sed quia expedita error a at sit rerum. Numquam unde debitis incidunt qui impedit et necessitatibus. Cupiditate exercitationem enim ut laborum itaque et." } } } }