August 31, 2020

Build a simple video chat app for Android

Nabil Kazi

Introduction

It’s been a long working day. You are sitting on a chair thinking about your friends. You take out WhatsApp or Zoom or Skype and start a video call with them.

But… But…, Have you ever wondered of making one yourself? You must be thinking it must be pretty difficult, lot’s of code, lot’s of integration, etc. etc.

Trust me. It’s pretty easy. Well, to be honest, CometChat makes it easy.

In this tutorial, we would be building a video chat app. I’ll walk you through the basics of integrating CometChat in your app. We’ll then see step by step what do we need to build a simple video chat app in minutes!


CometChat

First, let’s introduce you to CometChat if you have never heard of it. The headline on its website sums up nicely in one line. Text chat & video calling for your website and apps. It has 2 variants, CometChat Go and CometChat Pro.

  • Go is used for drag and drop chat plugin for your websites and no-code solutions.
  • Pro gives you access to its APIs, SDKs, Components to build your solution with bare minimum development. You can read more about CometChat Pro here.


What we’ll cover in this article?


We’ll be building a simple video chat application on Android in Kotlin. We’ll start from a clean slate, then add CometChat SDK and then move on to implement live video chatting!

Below is the overview of what we’ll be doing -

  • Adding the CometChat SDK and configuring our project.
  • Implementing user registration & login
  • Setting up calling history & details page
  • Setting up listeners to handle calling events
  • Live video chat in action!

We would be leveraging CometChat Android UI Kit to build our video chat app. I’ll show you, how this makes the development a breeze!

Let’s start building…

Step 1 - Setting up CometChat


Before starting with CometChat, it is important to understand how CometChat works! The Key Concepts page of CometChat documentation can help you with that.

Before diving into the code, we’ll need to setup CometChat in our application. CometChat Quick Start document does a wonderful job explaining the steps in detail.  


We’ll outline the steps from the above document -

  1. Create your CometChat Pro account
  2. Get your Application API Keys
  3. Add the CometChat Dependency in your Application
  4. Add the CometChat Android UI Kit Library
  5. Add Application API Keys, App ID and region and initialize CometChat SDK


Step 2 - Registering / Logging User into our app


CometChat key concepts page states that -

    CometChat does not handle user management. You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat programmatically. So the user does not ever directly login to CometChat.


It means, in the production environment, you’d either be using your custom back-end application or Firebase for user management. This is where you’d store all the registered users of your app.


So, a typical flow would be →

The user opens your app’s registration page. When the user clicks submit →

  1. You would call your back-end API to register the User in your database.
  2. After a successful response from your API, you would then create the user in CometChat using its createUser() SDK method.


But, for the sake of simplicity, In this tutorial, we would not be using any back-end service or Firebase. We would proceed with the CometChat’s default user creation.


Our Registration page asks for the user’s name and mobile. We’ll consider the mobile number as the user’s unique identifier - uid.

Now that we have our user’s name and uid, we’ll use CometChat’s createUser()  SDK method to create the user in our CometChat’s database. Then in the final step, we’ll call CometChat’s login()  SDK method to log the user into our app.


You can also view your registered users in the CometChat Dashboard.


Let’s see the entire process in code…

{% c-block language="javascript" %}
class RegistrationActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_register)
       createUserBtn?.setOnClickListener {
           
signUpTapped(
   }
   private fun signUpTapped() {
       val user = User()
       user.uid = etMobile.text.toString()
       user.name = etName.text.toString()
       registerUser(user)
   }
   private fun registerUser(user: User) {
       progressBar.visibility = View.VISIBLE
       CometChat.createUser(user, AppConfig.AppDetails.API_KEY, object : CometChat.CallbackListener<User>() {
               override fun onSuccess(user: User) {
                   progressBar.visibility = View.GONE
                   login(user)
               }
               override fun onError(e: CometChatException) {
                   progressBar.visibility = View.GONE
                   createUserBtn.isClickable = true
                   Toast.makeText(this@RegistrationActivity, e.localizedMessage, Toast.LENGTH_LONG).show()
               }
           })
   }
   private fun login(user: User) {
       progressBar.visibility = View.VISIBLE
       CometChat.login(user.uid, AppConfig.AppDetails.API_KEY, object : CometChat.CallbackListener<User?>() {
               override fun onSuccess(user: User?) {
                   progressBar.visibility = View.GONE
                   startActivity(Intent(this@RegistrationActivity, CallHistoryActivity::class.java))
               }
               override fun onError(e: CometChatException) {
                   progressBar.visibility = View.GONE
                   Toast.makeText(this@RegistrationActivity, e.localizedMessage, Toast.LENGTH_LONG).show()
               }
           })
   }
}
{% c-block-end %}


We’ll also create a Login screen for the already registered users. They would be entering their mobile numbers to log in. We would use CometChat’s login() SDK method to accomplish this.

Here’s the code -


{% c-block language="javascript" %}
class LoginActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_login)
       loginBtn?.setOnClickListener {
           
signInTapped()
       }
       
signUpBtn?.setOnClickListener {
           
startActivity(Intent(this@LoginActivity, RegistrationActivity::class.java))
       }
   
}
   private fun signInTapped() {
       val user = User()
       user.uid = etMobile.text.toString()
       login(user)
   }
   private fun login(user: User) {
       progressBar.visibility = View.VISIBLE
       CometChat.login(user.uid, AppConfig.AppDetails.API_KEY, object : CometChat.CallbackListener<User?>() {
               override fun onSuccess(user: User?) {
                   progressBar.visibility = View.GONE
                   startActivity(Intent(this@LoginActivity, CallHistoryActivityy::class.java))
               }
               override fun onError(e: CometChatException) {
                   progressBar.visibility = View.GONE
                   Toast.makeText(this@LoginActivity, e.localizedMessage, Toast.LENGTH_LONG).show()
               }
           })
   }
}
{% c-block-end %}


Note: I have skipped the validation part from the scope of this tutorial. But in a production app, you should add validations on the fields to avoid crashes and unexpected behaviours. Also you would need to store current logged in user in shared preferences or local database and check whether the user is already logged in and appropriately skip the login page.

On both the screens, in the Login onSuccess method, I am routing the screen to CallHistoryActivity. We’ll be setting this screen up next…


Step 3 - Setting up Calls List View

Once the user logs in the app, we would be showing the screen with the user’s call history. To implement this, we would be using CometChatCallListScreen from CometChat UI Kit.

This would give us a ton of functionality pre-loaded with bare minimum code to write!

Following is the list of features that we’d get once we add this screen -  

  • List view with user’s call history
  • The quick call button on the list view item that’d initiate a direct call with the user
  • User details view which lists an entire call history with that user.
  • Video, Audio and Text chat options

So, let’s go ahead and see the code that we need to write to get all these features into our app -


We would first create an activity. I’ll name it -  CallHistoryActivity.  


{% c-block language="javascript" %}
class CallHistoryActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_call_history)
   }
}
{% c-block-end %}


In our layout file - activity_call_history.xml, add the following snippet to leverage all the features that come preloaded with CometChatCallListScreen within CometChat UI Kit.


{% c-block language="javascript" %}
<fragment
 android:id="@+id/conversationList"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 class="screen.call.CometChatCallListScreen"/>
{% c-block-end %}


CometChatCallListScreen is a part of CometChat UI Kit. We won’t have to create RecyclerView, Adapter or any custom development of any sorts to display our call history list. We won’t even have to call the API ourselves! CometChat UI Kit would handle it all for us.


Tapping on any user item displayed would take the user to its Details screen. This screen displays the entire call history between the logged in user and the selected user.

The screen also provides an option to initiate Video, Audio or Text chat!

Isn’t this great? All these features by just adding a few lines of code!

Next, we’ll see how to make your first call…


Step 4 - Selecting a new user to initiate the call.

In a practical scenario, when you first sign-up into your app, this list is going to be empty. It would start populating when you make a few calls. To make your first call, you need to select a user from your contacts list. We’ll see the code to implement this feature.



Wait! There’s no code needed. Remember the CometChatCallListScreen that we added to display the user’s call history? That screen comes with a default “+” button at the top right corner. Tapping on that takes you to the User selection screen!

What? Does this require no code? Yes… No extra code needed. The CometChat UI Kit internally handles this behaviour for you.

You can then select from the displayed user list to initiate the call.


Step 5 - Implementing listeners to handle incoming Calls!

Initiating a call was pretty straight forward. We hardly wrote any code and got a ton of functionality built-in. Now we would look into some scenarios which we need to handle when a user initiates the call.


Consider a scenario where User A places a call to User B →

There are 6 specific cases that we need to handle in a video or an audio chat app.

  1. Notify User B when User A initiates the call
  2. Start the call on User A’s side when User B accepts the call
  3. End the call on User A’s side when User B declines the call
  4. End the call on User B’s side when User A cancels the call before starting.
  5. End the call on User A’s side when User B hangs up.
  6. End the call on User B’s side when User A hangs up.


On top of handling these scenarios, we would also need to implement the UIs for these specific scenarios. For example -

  • The UI screen when someone initiates the call
  • The Incoming Call Screen
  • The Ongoing Call Screen


Wow, that sounds like a lot of work, doesn’t it?  So lets deep dive and get straight into the code…

CometChatCallListener.addCallListener(listenerID,this)


Where’s the rest of the code?

Oh! wait, I forgot to mention, adding this single line of code handles everything for us! The Notifications, the UIs, the API calls, everything, just everything!!!

But where exactly do we need to add this beautiful piece of code?

We’ll be creating an Application class and adding this code over there. This will implement the listener on an Application level scope and would work irrespective of the activity or the fragment, the user is on. It also works if our app is in the background!


Here’s the entire code -

{% c-block language="javascript" %}
class ChatApp : Application() {
   private val listenerID: String = "999"
   override fun onCreate() {
       super.onCreate()
       val appSettings = AppSettings.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(AppConfig.AppDetails.REGION).build()
       CometChat.init(this, AppConfig.AppDetails.APP_ID, appSettings, object : CometChat.CallbackListener<String?>() {
           override fun onSuccess(s: String?) {
           }
           override fun onError(e: CometChatException) {
           }
       })
       CometChatCallListener.addCallListener(listenerID,this);
   }
   override fun onTerminate() {
       CometChatCallListener.removeCallListener(listenerID)
       super.onTerminate()
   }
}
{% c-block-end %}

We are initiating CometChat first (like you’d have seen in Step 1 of this article). Then, we add the CometChat call listener. Also, do note that we are removing the listener in the onTerminate method to avoid any memory leaks.


The last piece of the puzzle, don’t forget to add the name of this Application class in your manifest. We need to add it in the android:name property of the application tag.

{% c-block language="javascript" %}
<application
 android:name=".ChatApp"
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:roundIcon="@mipmap/ic_launcher_round"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
{% c-block-end %}


That’s it! You have your working Video Chat application ready in minutes! Select a user from the New Call Screen and enjoy your video chat!

You can find the entire source code of this app on GitHub.

If you need to implement your custom views for calling, user list, call history etc. - CometChat has the components ready for you. You’d need to implement these functions and components manually for call initiating, accepting, rejecting & ending. You can find the detailed documentation with all these methods and their parameters here.  

Conclusion

Woah! We started from scratch and implemented a functioning basic Video chat app in minutes. All thanks to CometChat to make the development - easy peasy pie!

The UI Kit gives us all the predefined screens with all the functionalities, the user interface, API calls and everything. No need to call APIs to fetch the call history or users.

If you need more detailed information on CometChat’s Android UI Kit, the 3 different ways in which you can leverage it to make a chat app. You can take a look at the official documentation page here.


If you want to explore building a simple chat app using CometChat - Here you go.

The best thing that I like about the CometChat UI Kit? We can leave the working and logic of Video, Audio, Text chat to CometChat and spend more time working on our business logic instead. It strips away all the complexity of the chat back-end and even the front-end. We just need to plug the components and get our app ready.


Feel free to reach out if you face issues in the implementation or have some quick ideas. We’ll be happy to discuss. We can’t wait to see what’s the next big thing you build using CometChat.