Chat with Android and Java
As the Programmable Chat API is set to sunset in 2022, we will no longer maintain these chat tutorials.
Please see our Conversations API QuickStart to start building robust virtual spaces for conversation.
Programmable Chat has been deprecated and is no longer supported. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here.
If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.
Ready to implement a chat application using Twilio Programmable Chat Client? Here is how it works at a high level:
- Twilio Programmable Chat is the core product we'll be using to handle all the chat functionality
- We use a server side app to generate a user access token which contains all your Twilio account information. The Programmable chat Client uses this token to connect with the API
Properati built a web and mobile messaging app to help real estate buyers and sellers connect in real time. Learn more here.
For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.
Initialize the Client - Part 1: Fetch access token
The first thing you need to create a client is an access token. This token holds information about your Twilio account and Programmable Chat API keys. We have created a web version of Twilio chat in different languages. You can use any of these to generate the token:
We use Volley to make a request to our server and get the access token.
Now it's time to use that token to initialize your Twilio Client.
Initialize the Client - Part 2: Build the client
Before creating a Programmable Chat Client instance we need to decide the region it will connect to and the synchronization strategy used to initialize it.
We can then pass this information along with the access token generated in the previous step and wait for the client to be ready.
The next step will be getting a channel list.
Get the Channel List
ChannelManager class takes care of everything related to channels. The first thing we need to do when the class is initialized, is to store a list of channels of type
Channel. To do this we call the method
getChannels from the Programmable Chat Client and extract a
Channel object from each
Let's see how we can listen to events from the chat client so we can update our app's state.
Listen to Client Events
The Programmable Chat Client will trigger events such as
onChannelDeleted on our application. Given the creation or deletion of a channel, we'll reload the channel list in the sliding panel. If a channel is deleted, but we were currently on that same channel, the application will automatically join the general channel.
You must set your
ChatClient to listen to events using a ChatClientListener. In this particular case,
MainChatActivity implements ChatClientListener, but it's methods are called from the
ChannelManager class that also implements ChatClientListener (who is the client's listener).
ChannelManager is used as an event handler proxy. Twilio chat sets the listener when loading the channels.
Next, we need a default channel.
Join the General Channel
This application will try to join a channel called "General Channel" when it starts. If the channel doesn't exist, it'll create one with that name. The scope of this example application will show you how to work only with public channels, but the Programmable Chat Client allows you to create private channels and handle invitations.
Notice we set a unique name for the general channel as we don't want to create a new general channel every time we start the application.
Now let's listen for some channel events.
Listen to Channel Events
We set a channel's listener to
MainChatFragment that implements
ChannelListener, and here we implemented the following methods that listen to channel events:
onMessageAdded: When someone sends a message to the channel you are connected to.
onMemberAdded: When someone joins the channel.
onMemberDeleted: When someone leaves the channel.
As you may have noticed, each one of these methods include useful objects as parameters. One example is the actual message that was added to the channel.
We've actually got a real chat app going here, but let's make it more interesting with multiple channels.
Join Other Channels
The application uses a Drawer Layout to show a list of the channels created for that Twilio account.
When you tap on the name of a channel, from the sidebar, that channel is set on the
setCurrentChannel method takes care of joining to the selected channel and loading the messages.
If we can join other channels, we'll need some way for a super user to create new channels (and delete old ones).
Create a Channel
We use an input dialog so the user can type the name of the new channel. The only restriction here is that the user can't create a channel called "General Channel". Other than that, creating a channel is as simple as using the
channelBuilder as shown and providing at the very least a channel type.
You can provide additional parameters to the builder as we did with general channel to set a unique name. There's a list of methods you can use in the client library API docs.
Cool, we now know how to create a channel, let's say that we created a lot of channels by mistake. In that case, it would be useful to be able to delete those unnecessary channels. That's our next step!
Delete a Channel
Deleting a channel is easier than creating one. The application lets the user delete the channel they are currently joined to through a menu option. In order to delete the channel from Twilio you have to call the
destroy method on the channel you are trying to delete. But you still need to provide a
StatusListener to handle the success or failure of the operation.
That's it! We've built an Android application with the Twilio Chat SDK. Now you are more than prepared to set up your own chat application.
Where to Next?
If you're a Java developer working with Twilio, you might want to check out these other tutorials:
Two-Factor Authentication with Authy
Learn to implement two-factor authentication (2FA) in your web app with Twilio-powered Authy. 2FA helps further secure your users' data by validating more than just a password.
Learn how to build a server notification system that will alert all administrators via SMS when a server outage occurs.
Did this help?
Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.
Need some help?
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.