19 January, 2022

A Complete Guide: Build Android Chat App with Kotlin using MirrorFly Chat SDK (Part 1)

Planning to build your chat app in Android? Thinking about moving with Kotlin but feel confused, as to how to execute further?

Then this is your space to explore! A complete guide that will help you to build android chat app with Kotlin.

Of course, I won’t stop here half way, I will also guide you as to how the entire technical process is carried over when there is a use of MirrorFly Chat SDK. This is to provide you a better understanding of the concept.

So, shall we move ahead to have a look

Kotlin: The Most On-demand Programming Language to Build a Real time Chat App in Android!

However, every android chat app development requires a programming language to get executed. These languages include Java, Kotlin, etc. We all know Java is the native one but do you know that Kotlin is the Google-endorsed programming language for Android chat app.

Kotlin is an official supportive language that combines both object oriented and functional programming features together.

According to GitHub’s Octoverse 2018 report and 2019 report, Kotlin was found to be the fastest and ‘first-class’ growing language

over the past few years when it comes to building the best chat app for website and mobiles. statistically, it has gained 1.1 million developers attention while building a chat app in Android.

Before unfolding the unrevealed technical part to create a chat app, let’s know about the need of kotlin in android.

Need of Kotlin in Creating Simple Chat App in Android

Chat, one of the most common and ever needed features to be included in any mobile app. However, it differs in quality of need as whether it’s needed for a simple one-to-one chat or many other advanced functionalities.

build android chat app in Kotlin

Let’s have a quick glance on the points that specifies the need of kotlin in build an android chat app.

  • Provides a speech bubbles drawables.
  • Allows different layout items
  • Help creating a DataUIModel holding all the UI attributes.
  • Allows creating multiple item ViewHolder
  • Building multiple item Type Adapter
  • Creating the ViewModel “From Android Jetpack”.
  • Implies as how to use LiveData”From Android Jetpack” to update the adapter.

Now, you would have got an idea as to why kotlin could be a good choice. And now let’s see how it will be implemented in the technical terms to build a secure chat app.

Are you interested in build chat app using kotlin?

Protocols to Develop Android Chat App using Kotlin with MirrorFly Chat SDK

As we all know that the demand for real time chat applications on mobile is touching the sky. Of course, building a mobile chat application doesn’t have to be that difficult to implement.

Let’s have a technical approach towards building a chat app for android with kotlin using MirrorFly SDK.

1. Initialize Chat SDK

To start with, for the initialization process there was a few data that were needed by the SDK. Further, we make use of the Chat SDK builder class to provide these data to SDK. In the application class on Create builds the Chat SDK Builder and provides the necessary data. Let’s clarify this with an example

GroupConfig groupConfiguration = new GroupConfig.Builder()
    .enableGroupCreation(true)
    .setMaximumMembersInAGroup(250)
    .onlyAdminCanAddOrRemoveMembers(true)
    .build();

ChatSDK.Builder()
    .useProfileName(true)
    .setDomainBaseUrl("https://www.contus.com/chat/api/v1/")
    .enableMobileNumberLogin(true)
    .setGroupConfiguration(groupConfiguration)
    .build(); 

If in case, when the name of a user is available with their country code (required only for mobile login), you can call them with the below mentioned syntex

ChatManager.setUserCountryISOCode("IN");
ChatManager.setUserProfileName("John Wick");

Whenever a user decides to use mobile number for login by setting this above mentioned flag as ‘true’ using enableMobileNumberLogin(true) method in Chat SDK, then must provide the country code for the SDK in the form of 2/3 letter code (ISO Alpha-2)

Chat Builder Function Description

Function Parameter Type Description
useProfileNamebooleanTo show whether contact’s profile name or nickname from sdk
setDomainBaseUrlStringurl needed for api calls provided by Chat team
enableMobileNumberLoginbooleantrue if mobile number is used as primary id for the user else false
setGroupConfigurationGroupConfigconfiguration for the group implementation
build n/a initialize the chat configuration

GroupConfig Builder Function Description

FunctionArgument TypeDescription
enableGroupCreation booleanenable/disable group creation
setMaximumMembersInAGroupintset the maximum number of members a group can have(cannot be greater than 300)
onlyAdminCanAddOrRemoveMembersboolean if true only group admin can add/remove members else members can add/remove other members
build n/a

build GroupConfig object
CAUTION: Base url must have http/https protocol and should end with / else an exception will be thrown

2. Connect to the Chat Server

To establish a connection to the server, there is a need for chat SDK messaging for which the below method needs to be initiated. This is the process that can store all the details about the connection into it, that will work further automatically

Argument Type Description
USERNAME StringuserName for making connection to the server
SECRET_KEYStringpassword used to authenticate to the xmpp server
XMPP_DOMAINStringdomain name which will be used in jid
XMPP_HOSTStringxmpp server url
XMPP_PORT intport of the xmpp server
ChatConnectionManager.initialize(USERNAME, SECRET_KEY,
XMPP_DOMAIN, XMPP_HOST, XMPP_PORT); 

Once you have initialized the connection details, for the first time you need to call the below mentioned method to get connected to the chat server immediately. Once you are done with this, now you don’t have to call this method again, in future the SDK will handle the connection and disconnection process automatically on your behalf.

ChatManager.makeXMPPConnection() 

3. Set IV and Token

Once you have registered successfully, you can call the below method and pass the IV and auth token to SDK

ChatManager.setIvAndAuthToken(IV, TOKEN);
ArgumentTypeDescription
IVStringInitialization vector for data encryption and decryption
TOKENStringAuth token received during registration for making api calls

4. Contact Sync

As here the mobile number is used as a primary id communication with chat SDK to have sync between user and server. The following code block initiates the contact sync so that the user can communicate with their contacts.

FlyCore.syncContacts(IS_FIRST_TIME, (isSuccess, throwable, data) -> {
           
            if (isSuccess) {
               // Contact Sync Success Reload Contact list
            } else {

            }

});
ArgumentTypeDescription
IS_FIRST_TIMEbooleantrue for first time and false after when synchronising contacts
CALLBACK FlyCallbackFlyCallback implemented as lambda expression

Further, to avoid unnecessary multiple contact sync calls observe the status of the contact sync before calling syncContacts.

FlyCore.getContactSyncState().observe(getViewLifecycleOwner(), result -> {

         if (result instanceof Result.Success) {}
          else if (result instanceof Result.Error) {} 
          else if (result instanceof Result.InProgress) {  }

});

Here, the value of the contactSyncState can also be accessible by directly calling the ‘get value method’ as it’s a live data variable.

Result<Boolean> contactSyncStateResult = FlyCore.getContactSyncState().getValue();

5. Single Chat Module

Prerequisites

As we know that to establish a connection to the server, we have to send messages to the chat SDK. To go with that we have to follow the below initialization procedure,

Preparing Single chat Jid

Here, almost all of the methods except jid acts as an input parameter, so the SDK provides the below method to prepare the jid. This method prepares the single chat jid from the given string by using chat config provided via [com.contusflysdk.api.ChatConnectionManager.initialize] method.

Note: The below characters is not allowed in uniqueId: U+0022 (“) U+0026 (&) U+0027 (‘) U+002F (/) U+003A (:) U+003C (<) U+003E (>) U+0040 (@).)
Argument Type Description
UNIQUE_USER_ID String unique userId for preparing JID
ls.getJid(UNIQUE_USER_ID)

6. Group Chat Module

Groups is the simplest way to chat with multiple users at any given time.

Preparing Group Chat

Most of the sdk methods expect jid acts as an input parameter, so sdk provides below utility method to prepare the group jid from the group id. The method prepares the group chat jid from the given string by using the chat config provided via [com.contusflysdk.api.ChatConnectionManager.initialize] method

Note:The below characters is not allowed in groupId: U+0022 (“) U+0026 (&) U+0027 (‘) U+002F (/) U+003A (:) U+003C (<) U+003E (>) U+0040 (@)
String groupJid = FlyUtils.getGroupJid(GROUP_ID)
Argument Type Description
GROUP_ID String Id of the group

Conclusion

Well, the above described are the beginning of some technical insights that takes place while build android chat app using Kotlin Chat SDK.There is much more that still exists. I hope to get back to you soon with the rest of the technical process in my another blog , and take you to complete the entire session of  how to create a simple chat app in android.

If you already have an idea about creating build chat app using Kotlin, Schedule a free demo and we’ll help you implement it!

Demo Button


Parthiba is a Product Marketer, helping providers of the various industries like healthcare, education, etc., to elevate their conversation value with the help of powerful communication solutions to drive better communication experience.

Leave a Reply

Your email address will not be published. Required fields are marked *