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:
Data Streams Overview – getting started with realtime apps for Android.
Publish/Subscribe Deep Dive – building applications that use data stream channels.
Presence Features – adding buddy list and/or device status to Android applications.
Multiplexing and Channel Groups – advanced techniques for dealing with many channels and/or large message volume.
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:
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:
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 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.
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:
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:
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:
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.
The next thing we noticed were the vastly improved callback APIs. Here’s an example of adding an event listener:
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.
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:
And the subscribe side is as follows:
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:
And synchronous publish is quite similar… Nice!
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):
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).
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.
Step 1: Sign up on the signup form
Step 2: create a new application, including publish and subscribe 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!
Demo App using v4. The entry point for this code is the Data Streams Overview mentioned earlier.
Chat App using v3 and Fabric SDK. The entry point for this code is the Android, PubNub and Fabric blog.
Chat App using v3. There’s a free on-demand webinar available to register here.
Lollipop Group Chat. The entry point for this code is the Android Group Chat Application tutorial.
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:
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!
The post Realtime Android Mobile Apps with the New PubNub SDK (v4) appeared first on PubNub.