Omnichannel Services – Send Push Notifications to Android Devices

Today I’m going to show you how to create an omnichannel service that send push notifications to Android devices like phones and tablets. This an important feature in any app as it allows the user to be made aware of any important updates.

To make push notifications work, you first (1) need to enable the Google Cloud Messaging Service (GCM) on your Google account, and then create a project number, which is the same as the sender ID to be used in your code (2). You also need to create an API Key, and you can find more details on the Android Developer site. With the sender ID, the app will request a registration ID for the device (3), and when it’s returned (4), it’s usually shared with an omnichannel service (5), to be used when sending push notifications. When something happens in the back-end (6), the service is either notified or has to poll, and sends a push notification message to the GCM (7). The GCM sends it to the device, which usually forwards it to the app (8), and the app then typically requests new information from the service (9).

Let’s have a look at the third and fourth steps of this process, and this is the code in the app’s main activity…

…where the app get the GCM instance (line 1), and then request the registration ID (line 2). Please note that the app doesn’t have to retrieve the registration ID on every launch, only one time for each update.

Now it’s time to create a service that sends a push notification, and even if I’m using PHP, the same functionality can be achieved on all major platforms, like those from IBM and Microsoft…

…and first I define a registration ID for a device (line 3), the API key (line 4), and a test message (line 5). Then the payload is created (line 6) as a part of the data to post to the GCM (line 7), as well as the headers (line 8). The HTTP POST request context is created (line 9) and made (line 10), with the result shown (line 11). To deploy this code to a cloud server, please see my previous videos.
This is the code you need to add to show a notification of the message in the app…

…and there are two classes needed. The first class (GcmBroadcastReceiver) link to the second class, and makes sure that the device doesn’t go to sleep until the message is handled. The second class (GcmIntentService) picks up the message (line 16), get the GCM instance (line 17), and if the message is not empty (line 18) and the message is of the correct type (line 20), a notification is created and sent (line 22-27).

There you have an omnichannel service that sends push notifications to Android devices.