IN THIS ARTICLE

    Subscribe to Our Newsletter

    Stay updated with the latest on web, mobile, and IoT, delivered weekly.
    Thanks for subscribing!

    Thanks for subscribing!

    Get ready for some great content.

    Welcome to our latest series on Android development using the Java v4 SDK. In case you missed it, PubNub released the official v4 SDK earlier this summer, which includes a ton of updates and improvements to make building realtime apps on Android even easier (which we’ll talk about shortly!).

    Along with that release, we published a series of articles about Android applications using Publish/Subscribe Data Streams. Each of these articles is a deep-dive into the sample application and how to get started with a different PubNub feature set:

    Now That We’re Out of Beta…

    We wanted to circle back and highlight all of the awesome v4 features now that the Android SDK is out of beta, and especially provide some support to developers who might be moving from v3 to v4 in the months ahead (especially as the v3 SDK moves towards end-of-life on March 1, 2017).

    We think the Android platform is pretty phenomenal because it gives developers the most power to release applications across a huge range of devices, from smartphones to TVs, and now even Google Home (hello Google Assistant!).

    And since Android is a Java-like platform, it means that developers don’t have to reinvent the wheel. Although there are definitely challenges (managing compatibility across previous versions of the operating system) and occasional hiccups, Android gives developers a unified development experience across billions of devices: phone, tablets, wearables, TV, Home, and Auto. We’ve been really impressed with the user experience in Marshmallow, and we’re looking forward to the wider release of Nougat in the weeks ahead.

    Android + PubNub

    PubNub allows you to build realtime applications that scale from one user to hundreds of millions of users, seamlessly. You may have previously heard of technologies like WebSocket and Socket.io. PubNub takes the essence of these technologies, adds dozens of value-added features, and deploys it across a global network that enables message delivery within a quarter of a second. That’s 250ms, much of which is taken up by the last hop from the mobile data carrier to the device itself.

    Can developers build realtime applications without PubNub? Yes, but they also then have to manage a secure and highly reliable global network that scales to massive audience sizes, not to mention creating dozens of SDKs to provide a unified API and connectivity to the full range of devices on the network. Oh, and did we mention BLOCKS?

    In case you missed it, here’s the GIF movie of the V4 sample app we’re talking about:

    Android App

     

    The app uses:

    • Publish/Subscribe messaging for a realtime sending and receiving of chat messages
    • Presence tracking for a buddy list that displays users’ online/offline status
    • Multiplexing to show the last message across a group of channels

    About the PubNub Android API

    PubNub plays together really well with Android because the PubNub Android SDK (part of the PubNub Java SDK family) is extremely robust and has been battle-tested over the years across a huge number of mobile and backend installations. As we said earlier, the SDK is currently on its 4th major release, which features a number of improvements such as fluent API, increased performance, sync/async operation, server-side filtering, streamlined logging & debugging, and more.

    The PubNub Java SDK is distributed via the Maven Central repository, so it’s easy to integrate with your application whether you’re using Maven or Gradle (hopefully Gradle!).

    Maven pom.xml dependency:

    <dependency>
      <groupId>com.pubnub</groupId>
      <artifactId>pubnub</artifactId>
      <version>4.0.14</version>
    </dependency>
    

    Groovy dependency:

    compile group: 'com.pubnub', name: 'pubnub', version: '4.0.14'
    

    Overview of PubNub APIs

    Here’s a quick recap of what you can do with PubNub on Android (and any of the other 70+ SDKs). If you’re fimiliar with the PubNub APIs, and want to skip to what’s new in v4, click here.

    If you’re familiar with the PubNub APIs, and want to hereskip to what’s new in v4, click here.

    Publish / Subscribe Messaging

    Publish / Subscribe messaging is the core of any realtime application. It allows devices to subscribe to named “channels”. When messages are published, they are delivered instantly to all connected devices. Publish/Subscribe data streams can transfer device positions, chat messages, or just about any kind of dynamic structured data (think “JSON”) you can think of.

    Presence

    Presence tracking is a tremendously useful feature for applications in gaming, social, collaboration, ride-hailing and IoT spaces. If you’re familiar with chat applications, you’ve seen the friendly “buddy list” before. PubNub generalizes this concept across all the applications of Publish/Subscribe messaging, making it easy to see which devices are online and connected to channels using its Presence API. This makes it easy to see which users are online for a chat application, which cars are available in the case of a ride-hailing app, or which sensors are currently transmitting or receiving in the case of an IoT app.

    As devices come online, leave or become disconnected from the network, PubNub sends the corresponding Presence events of “join”, “leave” and “timeout” to your application, allowing it to respond instantly to dynamic channel membership.

    Multiplexing and Channel Groups

    Multiplexing and Channel Groups gives developers the ability to create an unlimited number of channels. Using one connection for each channel subscription would quickly become unwieldy. Similarly, it’s often useful to give a group of channels a “nickname” to allow for easier subscription (for example, creating an alias for all the users on a given team, or all the component stocks of the Dow Jones or S&P 500 indexes).

    PubNub provides Multiplexing to allow one device connection to support dozens of channel subscriptions. For cases where it’s necessary to subscribe to hundreds or thousands of channels, PubNub provides a feature called Channel Groups to create a compound subscription.

    Android Push Notifications

    Mobile Push Notifications provides realtime message delivery when your application is active and running. But what about when it’s not? With Mobile Push Notifications on Android, iOS and Microsoft platforms, it’s possible to send updates to offline devices and activate the application.

    Storage & Playback

    The state of mobile connections changes drastically in real-world applications, which is the key reason for PubNub’s features for History, Storage and Playback. By activating the History add-on, the network can retain message history for a configurable time period. Devices can then retrieve just as much historical context as they need, or even replay messages exactly as they were sent (in the case of event re-broadcasting for example).

    Access Manager (PAM)

    As the world of connected devices grows exponentially, the security of devices and communications becomes even more important. PubNub Access Manager allows developers to set fine-grained permissions on network channels and API operations so that secret data stays secret and applications can do just what they’re allowed to do.

    Stream Filtering

    For applications that have an enormous message volume (or well-defined categories of messages such as multi-lingual use cases), Stream Filtering allows clients to receive a subset of messages from a channel based on server-side filter definitions.

    What’s New in V4

    So, you might be asking, “what’s new in this v4 SDK?” Here’s our take on it:

    Fluent APIs

    The first thing we noticed when we were getting started was the Fluent API. This means that instead of having a massive constructor argument list, objects can be built up incrementally using Builder objects.

    Here’s an example of fluent configuration of the PubNub Object:

    PNConfiguration pnConfiguration =
      new PNConfiguration()
          .setSubscribeKey("YourSubscribeKey")
          .setPublishKey("YourPublishKey");
          .setSecure(true);
       
    PubNub pubnub = new PubNub(pnConfiguration);
    

    Pretty sweet, right? Under the hood, it’s using the nifty Lombok framework for generated getters and setters.

    Here’s another example of fluent APIs in the channel subscribe operation:

    pubnub.subscribe()
        .channels(Arrays.asList("my_channel")) // subscribe to channels
        .execute();
    

    Overall, we’re a huge fan of these updates because they clean up a bunch of imperative code that would otherwise include a bunch of noise and duplication.

    Streamlined Callbacks

    The next thing we noticed were the vastly improved callback APIs. Here’s an example of adding an event listener:

    SubscribeCallback subscribeCallback = new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status) {
        }
     
        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
        }
     
        @Override
        public void presence(PubNub pubnub, PNPresenceEventResult presence) {
        }
    };
     
    pubnub.addListener(subscribeCallback);
    

    You may not recall it from before, but there used to be a single Callback class that required a lot of boilerplate for connection handling. With this update, SubscribeCallback instances are a lot cleaner and have explicit methods for presence and message events. Previously, these objects had less explicit Java structure, and more closely resembled raw JSON objects.

    Stream Filters

    Another major addition is the Stream Filtering API. We think it’s pretty awesome because it can filter through a ton of messages on the server side to avoid client overload. It just requires a little extra code around the publish and subscribe operations. Here’s a quick peek of the publish side:

    Map<String, Object> meta = new HashMap<>();
    meta.put("my", "meta");
    meta.put("name", "PubNub");
    pubnub.publish().channel("ch1").meta(meta).message("hello").async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult result, PNStatus status) {
        }
    });
    

    And the subscribe side is as follows:

    PNConfiguration config = new PNConfiguration();
    config.setSubscribeKey("myKey");
    config.setFilterExpression("name == 'PubNub'");
    PubNub pubnub = new PubNub(config);
    

    There’s a bunch more you can do with Stream Filters, but hopefully that’s a good taste.

    Synchronous and Async APIs

    It’s always difficult to craft APIs for connected mobile applications, in large part because of the disconnect between parts of the application that need synchronous versus async operations. With this new API release, there are both synchronous and async interfaces in each class.

    Here’s an example of async publish:

    pubnub.publish()
        .message(Arrays.asList("hello", "there"))
        .channel("my_channel")
        .async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
            }
        });
    

    And synchronous publish is quite similar… Nice!

    PNPublishResult result = pubnub.publish()
        .message(Arrays.asList("hello", "there"))
        .channel("my_channel")
        .sync();
    

    Improved Logging

    Just to make life that much easier, it’s possible to configure logging as follows (instead of the old debug jar dance we had to do):

    pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
    

    Wait, what?! That’s way too easy!

    Improved Networking Stack

    Even though it’s under the hood, we love this update because it uses the tried-and-true OkHTTP and Retrofit libraries from Square. If you haven’t checked it out yet (where have you been?), OkHTTP is the best-of-breed HTTP client for Java and Android that supports TLS, HTTP/2, and synchronous/async operation.

    Retrofit is a really, really clean framework for creating API clients. Most of the API operation configuration is separated into annotations, allowing clean separation of concerns between the API definition and client implementation.

    No more Bouncycastle

    Save the bouncycastle for another occasion! The SDK now uses the Java native crypto stack, so we’re able to make the JAR that much slimmer (and crypto performance that much faster).

    Unified JAR

    Speaking of JAR files, the new SDK is packaged as a single JAR file for Java and Android, making it that much easier to integrate.

    Overall, there’s a ton of great stuff in there, and we heartily recommend checking out the source if you’d like to learn more about how to create high-performance API client libraries.

    OK, now that we have those details out of the way, let’s show you how to get started!

    Obtaining your PubNub developer keys

    The first things you’ll need before you can create a realtime application with PubNub are publish and subscribe keys. If you haven’t already, you can create an account and get your keys.

    Create PubNub Account

    • Step 2: create a new application, including publish and subscribe keys

    pubnub-account-app-keys

    The publish and subscribe keys look like UUIDs and start with “pub-c-” and “sub-c-” prefixes respectively. Keep these handy – you’ll need to plug them in when initializing the PubNub object in your Android application.

    PubNub Android SDK V3 and V4 Sample Applications

    There are several sample Android applications you can refer to when migrating between PubNub API v3 and v4. If you use these codebases, make sure to substitute in your own publish and subscribe keys from the last section – otherwise, they won’t work!

    In future articles, we’ll dive into the first 2 codebases listed above and see exactly how to migrate between the API versions.

    Running the code

    If you downloaded the code from this GitHub link  into Android Studio, then running the code should be as easy as clicking the play button in the Android Studio toolbar. You can use a connected device or an AVD in the emulator to run the application.

    As you sign into the application from multiple devices, you can exchange chat messages in the Pub/Sub tab, the Presence tab will show an updated member list, and the Multi tab will show the latest message sent by each device to a random channel. Here’s what you’ll find:

    android-app-all

    Wrapping Up

    Thanks so much for stopping by and checking out our overview of the V4 Android SDK updates. Hopefully this gives you an idea of what’s possible! In the next articles in the series, we’ll dive deeper into the nitty gritty details of Publish/Subscribe messaging, Presence tracking, and Multiplexing and channel groups in v4 versus v3.

    Stay tuned, and please reach out anytime if you feel especially inspired or need any help!

    Resources
    Resources
    Building a HIPAA-compliant App
    Everything You Need to Know About Developing and Scaling a HIPAA-compliant App
    Download Now
    Building a HIPAA-compliant App