Google Cloud Messaging

Overview

Google Cloud Messaging (GCM) for Android is a service that allows you to send data from your server to your users' Android-powered device and also to receive messages from devices on the same connection. It is now known as Firebase Cloud Messaging (FCM) after a new site launched during the Google's I/O 2016 conference that unifies analytics and messaging into one platform. Review this slide deck for more context.

How it works

Much of the heavy lifting in supporting push notifications on Android is facilitated by Google-powered connection servers. These Google servers provide an API for messages to be sent from your server and relay these messages to any Android/iOS devices authorized to receive them.

An Android device with Google Play Services will already have FCM client support available. For push notifications to be received, an app must first obtain a token by registering with a Google server:

This token then must be passed along to your server so that it can be used to send subsequent push notifications:

Push notifications can be received assuming your app has registered to listen for FCM-based messages:

In other words, in order to implement FCM, your app will need both a Google server and your own server. When your app gets a token from Google, it needs to forward this token to your server. This token should be persisted by the server so that it can be used to make API calls to the Google server. With this approach, your server and the Android device do not need to create a persistent connection and the responsibility of queuing and relaying messages is all handled by Google's servers.

Setup

In order to use FCM, we need to go through the following steps:

Signup with Firebase console.

Associate an existing app or create a new one.

Provide the app name and SHA-1 signature of debug key used to sign your app.

Endpoint for sending a push notification to a specified set of registration tokens

Step 1: Register with Firebase Developers Console

In order to use FCM, you need to login to https://console.firebase.google.com/. You should be given a choice on the right-hand side as to whether to create a new project or import an existing Google app into Firebase.

Creating a new project

Click on Create New Project. You should see the window pop up:

Using an existing project

If you have existing app that used to be using FCM, click on Import Google Project. Make sure to click on Add Firebase when you're done.

After you've created or imported an existing project into Firebase, you need to add the package name and add the SHA-1 signing certificate (see link to obtain):

Click on Add Firebase to your Android app:

Click on Add App and then copy the google-services.json file that will get downloaded into yourapp/ dir. This file includes the project information and API keys needed to connect to Firebase. Make sure to preserve the filename, since it will be used in the next step.

Import Firebase Messaging Library

Create a InstanceID ListenerService

According to this Google official documentation, the instance ID server issues callbacks periodically (i.e. 6 months) to request apps to refresh their tokens. To support this possibility, we need to extend from InstanceIDListenerService to handle token refresh changes. We should create a file called MyInstanceIDListenerService.java that will send this token to our back-end:

Listening for push notifications

Let's define FCMMessageHandler.java that extends from FirebaseMessagingService that will process the message received:

importcom.google.firebase.messaging.FirebaseMessagingService;importcom.google.firebase.messaging.RemoteMessage;importandroid.app.NotificationManager;importandroid.content.Context;importandroid.os.Bundle;importandroid.support.v4.app.NotificationCompat;publicclassFCMMessageHandlerextendsFirebaseMessagingService{publicstaticfinalintMESSAGE_NOTIFICATION_ID=435345;@OverridepublicvoidonMessageReceived(RemoteMessageremoteMessage){Map<String,String>data=remoteMessage.getData();Stringfrom=remoteMessage.getFrom();Notificationnotification=remoteMessage.getNotification();createNotification(notification);}// Creates notification based on title and body received
privatevoidcreateNotification(Notificationnotification){Contextcontext=getBaseContext();NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher).setContentTitle(notification.getTitle()).setContentText(notification.getBody());NotificationManagermNotificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(MESSAGE_NOTIFICATION_ID,mBuilder.build());}}

We need to register the receiver class with FCM in the AndroidManifest.xml tagging the type of request (category) of the push:

In certain cases when receiving a push, you want to update an activity if the activity is on the screen. Otherwise, you want to raise a notification. The solutions to this are outlined in this post with a code sample here.

Testing

You can use the Grow -> Notifications to send test messages to verify that your app is correctly receiving messages. Select the User segment and choose the app to receive the notifications. If you want to pass custom data, you will need to select Advanced options to send custom data.

Step 3: Setup Web Server

Now we just need a web server to keep track of the different device tokens and manage the pushing of messages to different devices.

This sending code can be exposed as an endpoint or utilized on the server-side to notify users when new items are created or available. Note that the registration_ids parameter is synonymous with device tokens. if you only need to send a message to one device, you can use to instead of registration_ids:

{"data":{"title":"Test Title","body":"Test Body"},"to":"token1"}

Sample Ruby Server Implementation

A simple Sinatra-based ruby application that supports these endpoints is included below. The key point is that there is a /register endpoint, which is needed to record the registration token for a particular example. In a production environment, these POST requests should be sent by an authenticated user, so the token can be associated with that individual. In this example, the user_id must be specified.

Setup

First, let's install a few packages that will be used for this sample application.

gem install sinatra
gem install rest-client
gem install sequel

Sample web server

require'sinatra'require'rest-client'require'sequel'# Create a SQLite3 database
DB=Sequel.connect('sqlite://gcm-test.db')# Create a Device table if it doesn't exist
DB.create_table?:Devicedoprimary_key:reg_idString:user_idString:reg_tokenString:os,:default=>'android'endDevice=DB[:Device]# create the dataset
# Registration endpoint mapping reg_token to user_id
# POST /register?reg_token=abc&user_id=123
post'/register'doifDevice.filter(:reg_token=>params[:reg_token]).count==0device=Device.insert(:reg_token=>params[:reg_token],:user_id=>params[:user_id],:os=>'android')endend# Ennpoint for sending a message to a user
# POST /send?user_id=123&title=hello&body=message
post'/send'do# Find devices with the corresponding reg_tokens
reg_tokens=Device.filter(:user_id=>params[:user_id]).map(:reg_token).to_aifreg_tokens.count!=0send_gcm_message(params[:title],params[:body],reg_tokens)endend# Sending logic
# send_gcm_message(["abc", "cdf"])
defsend_gcm_message(title,body,reg_tokens)# Construct JSON payload
post_args={# :to field can also be used if there is only 1 reg token to send
:registration_ids=>reg_tokens,:data=>{:title=>title,:body=>body,:anything=>"foobar"}}# Send the request with JSON args and headers
RestClient.post'https://fcm.googleapis.com/fcm/send',post_args.to_json,:Authorization=>'key='+AUTHORIZE_KEY,:content_type=>:json,:accept=>:jsonend

Testing

We can startup this Sinatra server and register the token granted to our Android client with it:

Easy Local Testing with Ruby

We can also easily send messages to FCM registered devices using the ruby GCM gem. First we must have ruby installed (default on OSX) and then we can install GCM with:

gem install gcm

and send test pushes by running irb in the command-line:

require'gcm'gcm=GCM.new("YOUR-SERVER-KEY-HERE")reg_tokens=["YOUR-DEVICE-TOKEN","ANOTHER-DEVICE-TOKEN"]options={:data=>{:title=>"foobar",:body=>"this is a longer message"}}response=gcm.send(reg_tokens,options)

This will send messages to the devices specified.

Subscribing clients to Topic-Based Messages

FCM also supports opt-in topic-based subscriptions for clients, which does not require passing along the device token to your server. On the client side, we can also subscribe to this topic simply with two lines. The getInstance() call automatically makes a call to grab an Instance ID, so if we do not wish to pass along our device token, we can subscribe to a topic using the subscribeToTopic() method:

FirebaseMessaging.getInstance().subscribeToTopic("/topics/"+"dogs");

Inside your custom FCMListenerService, you will also need to check for these topic-based messages by checking the from String:

Rate Limits

FCM is free to use. In Jan. 2015, Google announced new rate limits in this blog post for FCM. There is a per minute / per device limit that can be sent. More technical details are included in this Stack Overflow posting.