Android Push Notifications with PubNub Data Streams (via GCM)

PubNub is a SaaS platform that lets us build realtime applications fairly quick by taking implementing websockets and a neat pub/sub API based model along with several other nice features. It’s supported across all sorts of platforms that you can think of like PHP, Ruby, Python, Android, iOS, Java, embedded systems, etc. I’ve covered how to setup it’s Android SDK and the basic usage before. In this tutorial I’d like to cover how we can use it to send Push Notifications via its own REST APIs as well as Google Cloud Messaging (GCM). I’ve already covered Android messaging (showing up as Notifications) via GCM before.

Setup GCM

So once you’ve completed creating your PubNub application, you’ll need to setup Google Cloud Messaging first. For this you should definitely go through my previous post or atleast through the Getting Started section there. If you read the entire article (that might take you quite some time as there are a lot of links to the Android documentation too that you’ll have to read in turn) then you’ll atleast have a good grasp over how the entire messaging mechanism works. Then understanding this PubNub Push Notifications through GCM will be a piece of cake for you.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Enable Push Notification in Your PubNub App

In your PubNub admin portal, select your application and Add/Enable the Push Notifications addon. They provide us with a 30 day free trial. When you add it or configure it, it’ll ask you for your GCM API Key that you’ll find in Google Developers Console → YOUR_APP_NAME → Credentials → Public API Access → Server Key Operations → API Key. So just copy your API Key from developers console and paste it there.

Setup PubNub Android SDK

Next, you’ll need the PubNub Android SDK. In their Github repository here – https://github.com/pubnub/java – you’ll find the entire Java SDK bundle. In the android folder you’ll find the Android SDK for PubNub. It should have a name like this – Pubnub-Android-3.*.jar. Add that to your project as libraries. Infact you’ll need about four libraries that you can see here:

  • Pubnub-Android-3.7.1.jar
  • bcprov-jdk15on-1.47.jar
  • android-support-v4.jar
  • google-play-services.jar

You’ll notice here that there’s the PubnubExample app that already has code for push notifications (via GCM) and all other Pubnub APIs like publish, subscribe, presence, etc. So definitely go through its source code if you’d like to.

Modifying Manifest and Adding Receiver and Service

You’ll need to make some modifications in the manifest file as well as add a Broadcast Receiver and an Intent Service. For more information you should definitely go thoroughly through my previous article or just copy paste relevant code from the PubnubExample sample application.

Sending/Receiving Messages

If you’re testing PubnubExample then their documentation has enumerated the steps involved in order to register the app on GCM and then send messages that show up as notifications from their web dev console. Note you might have to set the appropriate publish and subscribe keys (will find them in under the app details in the admin portal) as well as the channel name.

Here’s a sample JSON message that you can send from the web dev console to be received by the sample app that eventually gets converted into a Notification:

{
"pn_gcm": {
        "data" : {
            "summary": "Game update 49ers touchdown",
            "teams" : ["49ers", "raiders"],
            "score" : [7, 0],
            "lastplay" : "5yd run up the middle"
        }
    }
}

But let’s also see how we can send/receive messages right from the Android app (or any Java code) using Pubnub Data Streams. First we’ll see how to subscribe to a particular channel so that we can receive messages:

final Pubnub pubnub = new Pubnub(
  MyApplication.PUBNUB_PUB_KEY,
  MyApplication.PUBNUB_SUB_KEY,
  MyApplication.PUBNUB_SECRET_KEY
);

String REG_ID = "APP_REGISTRATION_ID";
String channel = "demo";

pubnub.enablePushNotificationsOnChannel(channel, REG_ID, new Callback() {
    @Override
    public void successCallback(String channel, final Object message) {
        // Success handler
    }

    @Override
    public void errorCallback(String channel, PubnubError pubnubError) {
        // Error handler
    }
});

Once you’ve registered your app on GCM, you use it to subscribe to a particular channel on Pubnub. Let’s see how to send a message now (really simple):

final Pubnub pubnub = new Pubnub(
  MyApplication.PUBNUB_PUB_KEY,
  MyApplication.PUBNUB_SUB_KEY,
  MyApplication.PUBNUB_SECRET_KEY
);

// Create GCM Message

PnGcmMessage gcmMessage = new PnGcmMessage();

// Create the payload.

JSONObject jso = new JSONObject();
try {
    jso.put("Pub", "Nub");
    jso.put("Foo", "Bar");
} catch (JSONException e) {

}

// By setting the payload on the gcmMessage object, this effectively populates
// the payload as a value of the required GCM "data" key.

gcmMessage.setData(jso);

Callback callback = new Callback() {
    @Override
    public void successCallback(String channel, Object response) {
        System.out.println(response);
        pubnub.shutdown();
    }

    @Override
    public void errorCallback(String channel, PubnubError error) {
        System.out.println(error);
        pubnub.shutdown();
    }
};

PnMessage message = null;

String channel = "demo";
message = new PnMessage(pubnub, channel, callback, gcmMessage);

try {
    message.publish();
} catch (PubnubException e) {
    switch (e.getPubnubError().errorCode) {
        case PubnubError.PNERR_CHANNEL_MISSING:
            System.out.println("Channel name not set");
            break;
        case PubnubError.PNERR_CONNECTION_NOT_SET:
            System.out.println("Pubnub object not set");
            break;
    }

}

This piece of code will send the JSON Object to the "demo" channel to which all the registered device apps will get the messages. Based on the reception on messages in the Broadcast Receiver and then the Service you can choose to do certain things like showing up a Notification. You’ll find the Receiver and Service samples in the PubnubExample or my previous post.

Pubnub also has a REST API for mobile push gateway that you may want to use from your server side component or the app itself.

Reference:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

One thought on “Android Push Notifications with PubNub Data Streams (via GCM)”

  1. Hello Sir,

    I am trying to send push notifications using PubNub in my android app but I am facing some issues.
    Can you please inbox me a complete sample code of the same.

    Thank You.

Leave a Reply

Your email address will not be published. Required fields are marked *