Android Push Notifications via Rails

technical, java, android, google, ruby, rails

I needed to display a notification on Android devices pushed from a Rails server for a particular app. There’s lots of documentation about it but there’s almost too much. I thought I’d summarise it for this specific purpose here.

Get API keys

Register the app with the Google Cloud Messaging (GCM)

Send the registration id to the (in this case Ruby on Rails) server so that it can push a message to the GCM

On the app, handle the pushed data from the GCM and display a notification

Step 1 - API keys

Getting the API key for your rails application to talk to the GCM.

Get your project number from the Google Developers Console, e.g. 1234567891011, to use as the GCM sender ID.
Enable GCM under APIs & auth.
Under credentials, create a Server key in the Public API access section. You can put server 0.0.0.0/0 while testing. The API key will look something like this ABCdefGHIjklm_Abcde_abcdEFghij123-A12

Step 2 - Implementing the client side code

Here’s the extensive Implementing a GCM Client. You’ll need to check it out, but here’s a summary. After adding the dependencies, the important lines are these:

It has to be run in a background process (AsyncTask) because it can be quite slow. I ended up implementing a version similar to the one in the guide but I had to do the AsyncTask a little differently.

Step 3 - Server side

After storing the registration id on the server side, it can be used to push data to devices. Android sends generic data as opposed to message notifications. This could be used for anything, not limited to message notifications.

This will send the data to the GCM which will subsquently send the data to the device.

Step 4 - Handling reception of data

The data comes in and the app has to have a way of handling it. This part was IMO easier than the Step 2.

Receiving a message is done through a WakefulBroadcastReceiver and an IntentService. The WakefulBroadcastReceiver listens out for the GCM and launches the IntentService. The IntentService can then handle building up of a notification and show that to the user.