Android Push Notifications via Rails

13 February
  • technical, java, android, google, ruby, rails

android logo 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.

  1. Get API keys
  2. Register the app with the Google Cloud Messaging (GCM)
  3. Send the registration id to the (in this case Ruby on Rails) server so that it can push a message to the GCM
  4. 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:

gcm = GoogleCloudMessaging.getInstance(context);
reg_id = gcm.register(SENDER_ID); // SENDER_ID from Step 1

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.

I’m using the gcm gem to push data. It made it nice and easy.

gcm = GCM.new("my_api_key") # Server key from Step 1
registration_ids = ["123456789"]
gcm.send(registration_ids, {data: {message: "Hello World"}})

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.

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.some_nots_image)
                .setContentTitle("My Notification")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(msg))
                .setContentText(msg);

That’s it! You’ll want to spend some time working this out for yourself through the documentation but I hope this is a helpful starting point.