X CLOSE
With the fresh 1.0.0 release of our Android library, we thought we'd create a walkthrough of how to lightly build a mobile talk app with Pusher. As with our previous tutorial, Making ReactJS Realtime With Websockets, together we will build a group talk application, leading you through how to use Pusher to send and display realtime messages in your UI.
Once you've set up your application on Android Studio, or your preferred IDE, let's embark with installing Pusher as a dependency. In the build.gradle file of your application module, add:
Sync the gradle project and Pusher, as long as other modules we’ll need later, should now be installed! Be sure to keep your application credentials to palm when we commence adding some realtime magic. You can find your credentials when you create an app after signing up for a free account.
The flow of our app will be like so: the user will input a message in their app, which will send a POST request to our server. In this example, I will use a elementary NodeJS server to provide a single API endpoint, for which you can see the code. However, as we have a consistent top-level API across all our server libraries, what is shown here can be lightly applied to any other web framework you wish to use.
Once our server receives the POST request, they will trigger a plain Pusher message to all connected clients, which will showcase the messages in realtime. If you wish to download the demo Android app, you can do so on the Play Store, and this will permit you to talk with our web version to test things out.
If you get stuck at any point, feel free to browse the Android source code here and the NodeJS server code here.
Sending Messages
Client-Side
So to set up, create a fresh app with an initial blank activity, and use the default name of MainActivity . In activity_main.xml let's go and create the input bar for our talk messages.
This will stick to the bottom of our view, and have an input (i.e. an EditText ) for typing messages, and a Button for sending them, which we have given the respective IDs of message_input and send_button .
Now in our MainActivity.java class, let's set up the listener for pressing the ‘Send' button.
Now we'll have to implement the View.onClickListener interface. Here we'll simply get the text of messageInput and POST it to our server.
In this tutorial, I'll be using the AsyncHTTPClient library to send messages to our server.
So now, within our MainActivity ‘s postMessage method, we'll get the text of the messageInput , and POST it, along with a username and timestamp. In our example app, we've also implemented a LoginActivity to get the user's Twitter username, but in order to concentrate on the talk element itself we're going to skip this. But feel free to browse the source code; it should be fairly straightforward.
Let's go ahead with creating and sending our request parameters:
Set a MESSAGES_ENDPOINT string in MainActivity to point to the URL of your server. Then let's make it so that when the request is successful, it clears the messageInput , or when it fails it alerts the user that something went wrong:
Sweet – so now the client is set up to send an input to the server, let's implement our mini-API.
Server-Side
Install NodeJS and Express if you haven't already. Generate your talk backend with:
Now initialize the Pusher object in your server file with your application credentials:
Now create the endpoint that receives JSON from the client. Then we'll fire a Pusher event called new_message on a channel called messages , passing along the data we received from the client.
At this point, you may wish to store messages, or sanitize them with a library such as sanitize-html so that you can display them on a web view. But this should be enough to demonstrate our talk app at work.
So fire up your server, and run your mobile app either in an emulator or on your device. Meantime, open up the Pusher Debug Console for your app on your dashboard. On your emulator or device, you should see an input bar at the bottom of the app. Type in a message and touch the ‘Send' button, and you should see messages pop up in realtime on your Debug Console. Cool, huh?
Displaying Live Talk Messages
That might be cool – but it's not enough. Let's have our Android client listen for incoming talk messages, and display them in a list.
So in activity_main.xml , add a fresh ListView as the very first child of RelativeLayout and above the LinearLayout that wraps our input bar. Your layout XML should look like so:
In order to display each message within the ListView , we'll have to create an adapter that turns a list into a set of views. In our MainActivity#onCreate method, let's truss our ListView to this adapter:
Our Message.java class which comprises the list is very straightforward:
Now let's create our MessageAdapter , which is, as you can see above, initialized with our MainActivity ‘s context, and the resource (an ArrayList of Message s):
When you extend BaseAdapter , your IDE will ask you to implement getCount , getItem and getItemId , which we can do so:
Eventually we'll have to implement getView , which is needed to convert an item in the ArrayList of Message s to a view. Very first, we need to create a MessageViewHolder to encapsulate the views we need to be a part of the message. In this case, we're going to have a thumbnailImageView – for the user's Twitter avatar – a senderView to display who sent the message, and a bodyView to demonstrate the content of the message. Within our MessageAdapter , add a private nested class:
We must also describe the layout of our message view. Let's give the view of our thumbnail an ID of img_thumbnail , the view of the sender and ID of message_sender , and the content of the message an ID of message_sender :
Now that we have a MessageViewHolder to encapsulate the visual elements that comprise a message, and a message layout to inflate those elements into, we can go ahead and implement our MessageAdapter#getView method:
This method will either find or create a MessageViewHolder associated with the convertView at a certain position in the list. When it has done so, it will set the text of the bodyView , senderView , and – as in the demo app linked in our introduction – showcase the Twitter avatar of the sender.
When we listen for Pusher events we will want to add any fresh messages to our MessageAdapter . Let's do so now:
This will add the message to the messageList and notifyDataSetChange() will refresh the adapter, demonstrating the fresh message.
So now we can go back to MainActivity and embark listening for Pusher messages:
So now that we have initialized Pusher, connected to the API, and subscribed to the messages channel, we can now add our SubscriptionEventListener to execute when an event comes in. All we'll need to do is parse the JSON (in this example I have used the Gson library into a Message object and then add it to the MessageAdapter :
Now that whenever we have a new_message event come in, we can simply add it to our MessageAdapter , and fresh messages will show up in realtime! Run your app on an emulator or device, and give it a spin. If you encounter any issues, do consult the source code.
Get Pushing
Hopefully you have found this a straightforward example of how to build realtime mobile apps with Pusher. There are many ways you can extend this tutorial for an improved application:
- Use Pusher client events to send messages from one client to another. You could use our webhooks to notify your server when messages are sent, permitting you to persist them in your database.
- Use Pusher presence channels to create live user lists and display who’s online in realtime.
- Use our REST API to determine whether a user is connected to Pusher. If they are, go ahead and send them a message as normal. If not, send them a native thrust notification leading them back to your app.
Even with such a basic app, hopefully I have shown you how effortless and few lines of code it is to drop in Pusher to any Android app. Feel more than free to let us know what you end up building with Pusher and Android!