Android PubNub Integration Tutorial (Setup and Basic Publish/Subscribe Usage)

PubNub is a lovely SaaS platform that helps us build realtime applications very fast without coding our own backend infrastructure. It has 60+ SDKs and can be used with JavaScript, Ruby, PHP, iOS, Android, Python, etc. In this specific article, we’ll deal with the Android SDK only. So in my Android application I had to code a small chat piece where multiple people could chat in groups (similar to WhatsApp groups). The idea of this article is to quickly show you how to install the PubNub Android SDK in your app and get started.

Download SDKs

First download the entire Java SDK bundle from Github that contains SDKs for Blackberry, Android, Java, J2ME – https://github.com/pubnub/java (clone it or download as zip file).

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

Install Essential Libraries

Now in the android folder you’ll see a file called Pubnub-Android-3.7.*.jar and in android/libs or android/examples/PubnubExample/libs you’ll find this jar file called bcprov-jdk15on-1.47.jar. We’ll need to add these 2 files to our project as libraries. For me, it was really simple. Just had to drag the files in the app/libs folder in Android Studio and right click -> Add as Library.

Start Using

To use it, we’ve to start off by first initializing a Pubnub object.

Pubnub pubnub = new Pubnub(
    "demo",  // PUBLISH_KEY   (Optional, supply "" to disable)
    "demo",  // SUBSCRIBE_KEY (Required)
    "",      // SECRET_KEY    (Optional, supply "" to disable)
    "",      // CIPHER_KEY    (Optional, supply "" to disable)
    false    // SSL_ON?
);

Next, sending and listening to events in the app is achieved using super simple publish and subscribe API calls.

// Subscribe

pubnub.subscribe("channel_name", new Callback() {
  @Override
  public void connectCallback(String channel, Object message) {
      Log.d("PUBNUB","SUBSCRIBE : CONNECT on channel:" + channel
                 + " : " + message.getClass() + " : "
                 + message.toString());
  }

  @Override
  public void disconnectCallback(String channel, Object message) {
      Log.d("PUBNUB","SUBSCRIBE : DISCONNECT on channel:" + channel
                 + " : " + message.getClass() + " : "
                 + message.toString());
  }

  public void reconnectCallback(String channel, Object message) {
      Log.d("PUBNUB","SUBSCRIBE : RECONNECT on channel:" + channel
                 + " : " + message.getClass() + " : "
                 + message.toString());
  }

  @Override
  public void successCallback(String channel, Object message) {
      Log.d("PUBNUB","SUBSCRIBE : " + channel + " : "
                 + message.getClass() + " : " + message.toString());
  }

  @Override
  public void errorCallback(String channel, PubnubError error) {
      Log.d("PUBNUB","SUBSCRIBE : ERROR on channel " + channel
                 + " : " + error.toString());
  }
});

No need to get overwhelmed by all those overridden methods. You can just live with successCallback() or that and errorCallback(). Next we’ll see how to publish data.

Pubnub Publish Method Options

// Publish

pubnub.publish("channel_name", jsonObject, new Callback() {

  @Override
  public void successCallback(String channel, Object response) {
    Log.d("PUBNUB", response.toString());
  }
  
  @Override
  public void errorCallback(String channel, PubnubError error) {
	Log.d("PUBNUB", error.toString());
  }
  
});

Oh and here’s how you leave a channel:

pubnub.unsubscribe("channel_name");

There are some other neat APIs they support like hereNow() that tells you about the clients already connected to a channel and presence() that listens for presence events (join/leave) on the specified channel. You’ll find more information about them here.

Pubnub has many SDKs to help you build realtime apps for mobile, desktop, web, servers, embedded systems, etc. It has many different features like push notifications, data storage (imagine storing your chat history), data syncing, realtime analytics, etc.

Firebase

There’s an alternative to Pubnub called Firebase (joined Google recently) that allows us to store and sync data across all the clients (again realtime apps). So you get it’s JS, Java, iOS or whichever SDK and connect to the firebase instance. Once connected you can start saving and retrieving (CRUD operations) data to your firebase instance. They provide you with a nice GUI (called Firebase Forge) where you can visualize and manipulate data in realtime. The GUI represents your data (like mongodb collections and documents) in a tree-like hierarchy fashion.

firebase data visualization

Every node has its own URL (like https://sizzling-heat-7133.firebaseio.com/android and https://sizzling-heat-7133.firebaseio.com/android/blog/users/alanisawesome) that you can connect to and manipulate. By default all the data is accessible by all the clients (scary!) but thankfully they’ve a nice module (file) where you can specify your security rules imposing access constraints. This is the first time I dealt with a backend as a service of this kind where most of the code is on the client-side and all the data is accessible to the world unless the security and rules (in their syntax) is applied. Personally I’m not very comfy with this but dealing with it for a longer time might make me more used to it.

Summary

So we saw how easy Pubnub makes implementing realtime facility with simple publish/subscribe call (reminds of socket.io. Hopefully this information should get you started with integrating your Android app with Pubnub (or even Firebase) and kick off with basic usage. For more information do check the Pubnub API 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.

Leave a Reply

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