2016-07-26

Welcome to our series on Android development with Fabric! In previous tutorials, we’ve shown you how to create apps with technologies like Android or PhoneGap. In this blog entry, we highlight a new toolkit, Twitter Fabric, that accelerates mobile app development and helps you build an app with several realtime data features that you’ll be able to use “as-is” or employ easily in your own data streaming applications:

Log in with Twitter auth (Login): using the Twitter plugin for Fabric allowing easy user authentication.

Send chat messages to a PubNub channel (Chat): using the PubNub plugin for realtime messaging and Publish/Subscribe API.

Display current and historical chat messages (Chat): using the PubNub plugin and History API.

Display a list of what users are online (Presence): using the PubNub plugin and Presence API.



In recent years, the dominant trend of mobile applications has been towards realtime apps, given its clear wins for user experience and monetization. Would Twitter or Slack work if they were email-only and produced a daily digest (like email lists of the past)? How do you call Uber or Lyft with only an email API and a daily static list of drivers? As you can see, there’s a huge disruptive force that comes from seeing vehicle locations in realtime. And as time goes on, there will be more and more adoption of realtime messaging: it is critical for applications in the IoT (Internet of Things) space, where a thermostat must provide the temperature and ability to control right now, not even 5 or 10 minutes ago. Emerging applications in the commercial and industrial IoT space have even greater demands around realtime – there is little margin of error in robot and vehicle control.

Android, as we all know, has grown up a lot in the past 5 years. It can literally boast an installed base of billions of devices across everything from smartphones to tablets to wearables (glasses/watches) to automobiles.

PubNub provides a global realtime Data Stream Network with extremely high availability and low latency. You can exchange messages between devices (and/or sensors, servers… essentially anything that can talk TCP) in less than a quarter of a second worldwide. And of that 250ms, a large part comes from the last hop – the data carrier itself! As 4G LTE and cloud computing gain traction, those latencies will decrease even further.

Twitter Fabric is a dev toolkit for Android that gives developers a powerful array of options:

Familiar dev toolkit for iOS, Android and Web Applications: a unified developer experience that focuses on ease of development and maintenance.

Best-of-breed SDKs all in one place: taking the pain out of third-party SDK provisioning and using new services in your application.

Streamlined dependency management: Fabric plugin kits are managed together to consolidate dependencies and avoid “dependency hell.”

Rapid app development with task-based sample code on-boarding: You can access and integrate sample code use cases right from the IDE.

Automated Key Provisioning: sick of creating and managing yet another account ? So were we! Fabric will provision those API keys for you.

Open Source, allowing easier understanding, extension and fixes.

Okay, so admittedly, that was a lot to digest. How do all these things fit together exactly?

We are building an Android app because we want to reach the most devices worldwide.

We use the Fabric plugin for Android Studio, giving us our “mission control” for plugin adoption and app releases.

We adopt Best-of-Breed services ( like PubNub ) rapidly by quickly integrating plugin kits and sample code in Fabric.

We use PubNub as our Global Realtime Data Stream Network to power the Chat and Presence features.

In addition, we’ll use Twitter’s API for Fabric to provide user authentication (we could also easily use Twitter’s other APIs if that content is relevant to the application).



As you can see in the animated GIF above, once everything is together, we have built an application very quickly that provides a great feature set with relatively little code and integration pain. This includes:

Log in with Twitter (or your own alternative login mechanism).

Send & receive chat messages (or whatever structured realtime data you like).

Show a list of users online (or devices/sensors/vehicles, etc.).

This all seems pretty sweet, so let’s move on to the development side…

Sign up with Fabric

If you haven’t already, you’ll want to create a Fabric account like this:



You should be on your way in 60 seconds or less!

Android Studio

In Android studio, as you know, everything starts out by creating a new Project.

In our case, we’ve done most of the work for you – you can jump start development with the sample app by downloading it from GitHub ,or the “clone project from GitHub” feature in Android Studio if prefer. The git URL for the sample app is:

Once you have the code, you’ll want to create a Fabric Account if you haven’t already.

Then, you can integrate the Fabric Plugin according to the instructions you’re given. The interface in Android Studio should look something like this, under Preferences > Plugins > Browse Repositories:

Once everything’s set, you’ll see the happy Fabric Plugin on the right-hand panel:

Click the “power button” to get started, and you’re on your way!

Twitter SDK Integration

Adding Twitter is an easy 3-step process:

Click to Install from the list of Fabric kits

Integrate any Sample Code you need to get started

Launch the App to verify successful integration… and that’s it!

Here’s a visual overview of what that looks like:

PubNub SDK Integration

Adding PubNub is just as easy:

Click to Install from the list of Fabric kits.

Enter your PubNub keys or have Fabric create a new account.

Integrate any Sample Code you need to get started.

Launch the App to verify successful integration.

Look familiar? That’s the beauty of Fabric!

Using this same process, you can integrate over a dozen different toolkits and services with Fabric.

Navigating the Code

Once you’ve set up the sample application, you’ll want to update the publish and subscribe keys in the Constants class, your Twitter API keys in the MainActivity class, and your Fabric API key in the AndroidManifest.xml. These are the keys you created when you made a new account and PubNub application in previous steps. Make sure to update these keys, or the app won’t work!

Here’s what we’re talking about in the Constants class:

These values are used to initialize the connection to PubNub when the user logs in.

And in the MainActivity :

These values are necessary for the user authentication feature in the sample application.

And in the AndroidManifest.xml :

This is used by the Fabric toolkit to integrate features into the application.

As with any Android app, there are 2 main portions of the project – the Android code (written inJava), and the resource files (written in XML).

The Java code contains 2 Activities, plus packages for each major feature: Pub/Sub messaging, Presence, and Multiplexing.

The resource XML files include layouts for each activity, fragments for the 2 tabs, list row layouts for each data type, and a menu definition with a single option for “logout.”

Whatever you need to do to modify this app, chances are you’ll just need to tweak some Java code or resources. In rare cases, you might add some additional dependencies in the build.gradle file, or modify permissions or behavior in the AndroidManifest.xml.

In the Java code, there is a package for each of the main features:

chat: code related to implementing the realtime chat feature.

presence: code related to implementing the online presence list of users.

For ease of understanding, there is a common structure to each of these packages that we’ll dive into shortly.

Android Manifest

The Android manifest is very straightforward – we just need one permission (INTERNET), and have 2 activities: LoginActivity (for login), and MainActivity (for the main application).

Hopefully this all looks familiar – most of it was auto-generated, with a couple small additions from the Fabric code on-boarding.

Layouts

Our application uses several layouts to render the application:

Activity: the top-level layouts for LoginActivity and MainActivity.

Fragment: layouts for our 2 tabs, Chat and Presence.

Row Item: layouts for the 2 types of ListView , Chat and Presence.

These are all standard layouts that we pieced together from the Android developer guide, but we’ll go over them all just for the sake of completeness.

Activity Layouts

The login activity layout is super simple – it’s just a single button for the Twitter login:

It results in a layout that looks like this:

The Main Activity features a tab bar and view pager – this is pretty much the standard layout suggested by the Android developer docs for a tab-based, swipe-enabled view:

It results in a layout that looks like this:

Fragment Layouts

Ok, now that we have our top-level views, let’s dive into the tab fragments.

The chat tab layout features a bar for sending a new message (that’s what theRelativeLayout named “relativeLayout” is for, to create a “send message” section),with a scrolling ListView below.

Combined with the ChatListRowUi layouts, it will create a view that looks like this:

The presence tab layout is even simpler, just a list of presence rows.

( Presence tab layout omitted for brevity’s sake )

Combined with the ChatListRowUi layouts, it will create a view that looks like this:

Row Layouts

A chat row contains very few data attributes: just sender, timestamp, and the message itself:

Similarly, the presence row contains just a few data attributes: sender, timestamp, and the presence value.

( Presence item row layout omitted for brevity’s sake )

Hopefully that all wasn’t too crazy! Now we can dive into the Java code, where there’s more interesting stuff happening (or, at least we think so).

Java Code

In the code that follows, we’ve categorized things into a few areas for ease of explanation. Some of theseare standard Java/Android patterns, and some of them are just tricks we used to follow PubNub or other APIsmore easily.

Activity: these are the high-level views of the application, the Java code provides initialization and UI element event handling.

Pojo: these are Plain Old Java Objects representing the “pure data” that flows from the network into our application.

Fragment: these are the Java classes that handle instantiation of the UI tabs.

RowUi: these are the corresponding UI element views of the Pojo classes (for example, the sender field is represented by an TextView in the UI).

PnCallback: these classes handle incoming PubNub data events (for publish/subscribe messaging and presence).

Adapter: these classes accept the data from inbound data events and translate them into a form that is useful to the UI.

That might seem like a lot to take in, but hopefully as we go into the code it should feel a lot easier.

LoginActivity

The LoginActivity is pretty basic – we just include code for instantiating the viewand setting up Twitter login callbacks.

We attach the login event to a callback with two outcomes: the success callback,which extracts the username and Twitter ID and moves on to the MainActivity todisplay a Toast message; and the error callback, which does nothing but Log (for now).

MainActivity

There’s a lot more going on in the MainActivity. This makes sense, since it’s the place where the application is initialized and where UI event handlers live. Take a moment to glance through the code and we’ll talk about it below.

The 2 main UI event handlers are:

logout() : which processes a logout menu item click.

publish() : which handles a message send button click.

The onCreateOptionsMenu() and onOptionsItemSelected() should look familiar toAndroid developers, it’s just initializing and handling menu clicks.

Similarly, onStop() and onDestroy() are handling the Android lifecycle events.

Ok, now that that’s out of the way, we can dive into the onCreate() method. Ittakes care of:

Initializing the Twitter auth config.

Initializing Fabric with the Twitter plugin.

Ensuring that we are coming from the LoginActivity (or other activity) with the username preference set.

Instantiating Adapter instances and Callback instances for Chat and Presence features.

Creating the Tab layout with Chat and Presence tabs.

Initializing PubNub.

Connecting our app to the PubNub Chat channel.

Handling message publish events coming from the chat UI.

Cleanly destroying resources during the important lifecycle events (or logout).

There are a couple of things worth mentioning in this code.

We call hereNow() and history() to bootstrap the presence and chatfeatures respectively. Make sure your PubNub application keys are configuredwith the Presence and Chat add-ons, or these features won’t work!

The last note is that Twitter auth uses a web view which doesn’t reset easily -we include some code to reset the web view CookieManager in the disconnectAndCleanup()code above.

ChatPojo

The Pojo classes are the most straightforward of the entire app – theyare just immutable objects that hold data values as they come in. We makesure to give them toString() , hashCode() , and equals() methods sothey play nicely with Java collections.

The ChatPojo contains three fields: sender, message and timestamp.

PresencePojo

The PresencePojo contains three fields: sender, presence value and timestamp.

In our case, we use the value of the three main PubNub presence event types for the presence value: “join”, “leave”, and “timeout.” We’ll translate these events to corresponding status (online/offline/etc) strings in the PresenceListAdapter .

( +PresencePojo+ code omitted for brevity’s sake )

ChatListRowUi

The ChatListRowUi object just aggregates the UI elements in achat list row. Right now, these just happen to be TextView instances.

PresenceListRowUi

The PresenceListRowUi object just aggregates the UI elements in achat list row. Right now, these just happen to be TextView instances.

( +PresenceListRowUi+ code omitted for brevity’s sake )

ChatTabFragment

The ChatTabFragment object takes care of instantiating the Chat taband hooking up the ChatListAdapter.

PresenceTabFragment

Similarly, the PresenceTabFragment object takes care of instantiating the Presencetab and hooking up the PresenceListAdapter.

( +PresenceTabFragment+ code omitted for brevity’s sake )

ChatListAdapter

The ChatListAdapter follows the Android Adapter pattern, which is used to bridgedata between Java data collections and ListView user interfaces. In the case of PubNub,messages are coming in all the time, unexpected from the point of view of the UI. Theadapter is invoked from the ChatPnCallback class: when a chat message comes in, thecallback invokes ChatListAdapter.add() with a ChatPojo object containing the relevantdata.

In the case of the ChatListAdapter , the backing collection is a simple ArrayList ,so all the add() method has to do is:

Add the item to the collection (actually prepend by doing insert(0, value) ).

Notify the UI thread that the data set changed (this must happen on the UI thread only!).

The getView() method is also straightforward – it uses View Tags to memorize the objects already instantiated. So within the body of the getView() method, we just need to:

Find the Pojo for the specified list position.

Create a new RowUi object if necessary, or find the one already associated with the object.

Populate the RowUi object with the new data.

Not too bad!

PresenceListAdapter

The PresenceListAdapter also follows the Android Adapter pattern. This adapter is invoked from the PresencePnCallback class: when a presence event comes in, the callback invokes PresenceListAdapter.add() with a Presence Pojo object containing the relevant data.

In the case of the PresenceListAdapter , the backing collections are a little different. We use a simple ArrayList to hold the list of user names, and a Map<String, PresencePojo>to store a map of user names to PresencePojo values. We do this because there may be cases (such as tapping on a username) where we want to lookup the presence of a given username quickly, sothe Map instance will save us a lot of work.

One other aspect of presence is that we only store one line per user; in this application, it just makes sense to display the latest presence status in the presence tab. (You might imagine creating a more complex UI that has historical presence information.)

So given all the above, the add() method has to:

Remove the existing items from the collections as appropriate (since we’re only keeping the latest value).

Add the item to the collections (actually prepend by doing insert(0, value) ).

Notify the UI thread that the data set changed (this must happen on the UI thread only!).

The getView() method is similarly straightforward – it uses View Tags to memorize the objects already instantiated. So within the body of the getView() method, we just need to:

Find the Pojo for the specified list position.

Create a new RowUi object if necessary, or find the one already associated with the object.

Populate the RowUi object with the new data.

For an extra level of usefulness, we include 2 methods for getting a human-friendly presence status (online/offline/idle) and color. In a real-world Android app, the actual values would probably be better stored in the appropriate externalized XML resource file.

ChatPnCallback

The ChatPnCallback is the bridge between the PubNub client and our application logic. In this application, we omit the handlers for error, connect, disconnect and reconnect events that a real-world application would want to pay attention to. In the callback below, the most interesting code is in the successCallback() code.It takes an inbound messageObject object and turns it into a Pojo value that is forwarded on to the ChatListAdapter instance.

In the case of PubNub publish/subscribe messaging (our example chat), that message may take one of two forms: a single JSONObject message (in the event of channel subscription),or a JSONArray of message objects (in the event of a PubNub history() call).

In either case, we extract the relevant fields from the structured data object and pass along one or more ChatPojo objects to our trusty ChatListAdapter .

PresencePnCallback

The PresencePnCallback is the other bridge between the PubNub client and our application logic. In this application, we omit the handlers for error, connect, disconnect and reconnect events that a real-world application would want to pay attention to. In the callback below, the most interesting code is in the successCallback() code.It takes an inbound message object and turns it into a Pojo value that is forwarded on to the PresenceListAdapter instance.

In the case of PubNub presence events (our example buddy list), that message may take one of two forms: a JSONObject message that contains a single “uuid” field(in the case of presence events), or a “uuids” field with a JSONArray of String uuids(in the case of a PubNub hereNow() call).

In either case, we extract the relevant fields from the structured data object and pass along one or more PresencePojo objects to our trusty PresenceListAdapter .

And… that’s about it! Hopefully this gives a good idea of what all the code in the sample application is for. There’s just a few more code snippets we’ll pass along for advanced users who want to dive deeper intoTwitter Authentication using Fabric.

Using Fabric for Twitter Auth

With Fabric, integrating the Twitter API was super simple. Just in case you want to learn more, we’ll outline some of the additional code snippets you can use with Twitter Auth in your Android application.

Login

We’ve already seen the code for setting up the login button in the LoginActivity .

If you’d prefer to trigger the login from a different event (not the Twitter button),you can do so as follows:

In the code above:

activity is the Activity context (the parent Android activity).

callback is a Callback instance (to receive the result of the auth flow).

This code will instantiate a new web view that goes through the auth flow and gives control to the callback method as appropriate.

Getting the TwitterSession

If your app ever needs to examine the active session, it can do so as follows:

This information can be used to make Twitter API requests from the application. In addition, Twitter supports OAuth Echoto send user credentials to your backend services in a trustworthy way.

Logout

Logout is easy, we just clear the Twitter auth session via the session manager. Clearing out the attributes is a little trickier though (since the Twitter auth feature uses a web view that can save cookies, preventing login as a different user).

Hopefully that code will get easier in a future SDK release!

Validate

One thing worth mentioning – the Twitter code will return a user session,but how can we trust the results? In a malicious case, the app may be running in a debugger where the user is tinkering with values. We wouldn’t want our backend to get “tricked” by bad information coming from malicious spoofed user requests! To cover this case, the Twitter API provides authHeaders that can be used to validate the OAuth token on the user side and retrieve the user’s profile details directly from Twitter for cross-checking. For any app with an important backend, you’ll want to do something as follows:

Phew! That’s a lot better. And safer!

Conclusion

Thank you so much for staying with us this far! Hopefully it’s been a useful experience. The goal was to hopefully convey our experience in how to build an app that:

Log in with Twitter auth.

Send chat messages to a PubNub channel.

Display current and historical chat messages.

Display a list of what users are online.

If you’ve been successful thus far, you shouldn’t have any trouble extending the app to any of your realtime data processing needs.

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

If you are interested in more information about using Twitter Fabric with PubNub please see the recording of our Twitter Fabric webinar with a member of the Fabric team at Twitter.

The post Accelerating App Delivery with Android, Fabric and PubNub appeared first on PubNub.

Show more