Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Chat with Android and Java

Download the Code

Ready to implement a chat application using Twilio Programmable Chat Client? Here is how it works at a high level:

  1. Twilio Programmable Chat is the core product we'll be using to handle all the chat functionality
  2. 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
  3. Twilio Access Manager is the part of the SDK that handles access tokens and refreshes them upon token expiration

Properati built a web and mobile messaging app to help real estate buyers and sellers connect in real time. Learn more here.

Let's get started!

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.

Loading Code Sample...
      
      
      
      
      app/src/main/java/com/twilio/twiliochat/chat/accesstoken/AccessTokenFetcher.java

      Fetch Access Token

      app/src/main/java/com/twilio/twiliochat/chat/accesstoken/AccessTokenFetcher.java

      Now it's time to use that token to initialize your Twilio Client.

      Initializing the Client - Part 2: Build the 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.

      Loading Code Sample...
          
          
          
          
          app/src/main/java/com/twilio/twiliochat/chat/ChatClientBuilder.java

          Build the Chat Client

          app/src/main/java/com/twilio/twiliochat/chat/ChatClientBuilder.java

          The next step will be getting a channel list.

          Get the Channel List

          Get the Channel List

          Our 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 ChannelDescriptor returned.

          Loading Code Sample...
              
              
              
              
              app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

              Get Channel List

              app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

              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

              Listen to Client Events

              The Programmable Chat Client will trigger events such as onChannelAdded or 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.

              Loading Code Sample...
                  
                  
                  
                  
                  app/src/main/java/com/twilio/twiliochat/chat/MainChatActivity.java

                  Listen for Client Events

                  app/src/main/java/com/twilio/twiliochat/chat/MainChatActivity.java

                  Next, we need a default channel.

                  Join the General 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.

                  Loading Code Sample...
                      
                      
                      
                      
                      app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                      Join or Create a General Channel

                      app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                      Now let's listen for some channel events.

                      Listen to 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.

                      Loading Code Sample...
                          
                          
                          
                          
                          app/src/main/java/com/twilio/twiliochat/chat/MainChatFragment.java

                          Listen to Channel Events

                          app/src/main/java/com/twilio/twiliochat/chat/MainChatFragment.java

                          We've actually got a real chat app going here, but let's make it more interesting with multiple channels.

                          Join Other 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 MainChatFragment. The setCurrentChannel method takes care of joining to the selected channel and loading the messages.

                          Loading Code Sample...
                              
                              
                              
                              
                              app/src/main/java/com/twilio/twiliochat/chat/MainChatFragment.java

                              Join Other Channels

                              app/src/main/java/com/twilio/twiliochat/chat/MainChatFragment.java

                              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

                              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.

                              Loading Code Sample...
                                  
                                  
                                  
                                  
                                  app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                                  Create a Channel

                                  app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                                  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

                                  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.

                                  Loading Code Sample...
                                      
                                      
                                      
                                      
                                      app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                                      Delete a Channel

                                      app/src/main/java/com/twilio/twiliochat/chat/channels/ChannelManager.java

                                      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?

                                      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.

                                      SMS and MMS Notifications

                                      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.

                                      Mario Celi Jose Oliveros Agustin Camino David Prothero Andrew Baker  Jeff Linwood

                                      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 browsing the Twilio tag on Stack Overflow.

                                      Loading Code Sample...