27 September, 2021

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 chat app.

Are you interested in build chat app using kotlin?

Protocols to Develop Android Chat App in 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 are planning to build chat app using Kotlin,

Schedule a free demo and we’ll help you get started right from scratch!

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.

24 Comments

  1. Daniel Reply

    I’m looking for Voice and Video calls API’s to integrate with my existing chat app using kotlin, I just wanted to know MirrorFly supports cross platform integration. Can you please give me an estimate for the price? Thank you.

  2. Suhail Reply

    Hi, I need to know about how to use Mirrorfly Kotlin Messaging SDK? Is it easy to customize the behavior and build any type of chat experience. Do you have samples? Kindly get back to me, as I need a solution fast.

  3. Charles Reply

    Please tell me what is the pricing? I want to use your kotlin chat messaging SDK includes both a low-level chat SDK and reusable UI components together in a android app.

  4. Malik Reply

    Hi, so i have an application called KidsBook it’s for education department, developed with kotlin as frontend and Laravel (php) as backend, need to integrate chat and video calling api to create a virtual class room for our schools from our application.

  5. Jidpungtum Reply

    Dear Mirror Fly Business Development Manager, I am currently looking for the licenses based server for the collaboration software for the private own server here as requirements:- 1) 1024 Slots supporting maximum 25000 users at the same times. 2) install to the primary server and the redundancy server supporting maintenance, upgrade, bug fixed error for the whole continuous 5years. 3 ) need Server software of the Mirror Fly to run on our own cloud server 4) must provide Mobile iOS/android apps as well as the PC window client dispatches. Mobile Apps must support Thai language supporting API of the existing dbases 5) Mobile APIs supporting Std call, VoIP, Video Call, Chat, GPS of the subscribers, Emergency button, sharing data of the users such as images, voice clips, video clip, location 6) Dispatch Center can provide “Public Warning/Notification” in Broadcast or in specific area and present location of the users, In addtion, alert with the safety tip warning of emergency tip message in broadcast to the subscribers. 7) that subscriber who notify incidents can check history and results via Mobile API 8) those of Mobile APPs android/iOS shall be uploaded to the google Play store or apple store by our own end user name. 9) Several of API SDK will be required to interoperate with our existing Thai dbase including but not limited with the unified communication system platform 10) Mobile iOS/android and window PC shall have Push-to-talk button soft key 11) Unified Communication System – consist of the IP PBX enterprise w/licenses CDR and SIP Trunk incorporated, RoIP Gateways to connect with two-way radios supporting multi-brand radios e.g. Motorola, Kenwood, Huawei eLTE mobiles, others. Also IP Phones. If you feel that the above criterias and conditions you can do please feel free to correspond to me in ASAP. Thank you! Best Regards,

  6. Arnas Reply

    Hi, I work as a developer at Strike. We are an Estate Agent that allows you to sell your house online. I’m currently looking for a chat solution that can replace our in-house messaging system. To start with we need to allow our customers to start a chat with a given person depending on where they are in the journey. We also need to integrate this with our CRM to display a chat log for each customer. The chat will need to live in our customer portal and mobile app. Your chat SDK for react and kotlin looks like something we could use. Can you please give me an estimate for the price and what’s involved to achieve current requirements? Thank you, Arnas

  7. Jason Reply

    i have a chat platform where business build their own website using my CMS feature. I also provide SMS Marketing and other digital marketing add on via my chat platform. I want to expand the add on and give them Video conference and so on. Expected to reach 1,000 business to register in my platform for a start. My platform is MyBizSites

  8. john Reply

    Hi, I am developing a chat app with kotlin and need chat support. do you have any real time messaing api for kotlin?

  9. Jimmy Reply

    Hello MirrorFly team. i have a dating app build by kotlin language We use chat extensively in our dating app and would like to upgrade our services of it. i want to see your product demo version .thanks in advance

  10. Dipal Reply

    We are developing an App that could integrate with Slack, have an ability to send meeting invitation to other(s), once accepted, can join the quick video call for max a minute. Also have an ability to record the video during the meeting. The App would have a user interface to start the meeting, however, the meeting would end after a minute (does not have any interface to end the meeting – the meeting would end after a minute automatically – possibly can show reverse ending time) – Please let me know which API’s and tool can help us to develop this application.

  11. Fouad Reply

    We are interested in licensing your product as part of our offering and would like to know more about your licensing terms and integration Kotlin Chat SDK possibilities. Can we arrange a call this week? Thanks

  12. Miko Reply

    Hi, We are 917 Ventures, the largest corporate incubator in the Philippines. We are fully supported by Globe Telecom to generate, test, and develop new business ideas that have the potential to grow and scale fast. Currently, we are looking for a chat platform to support one of our upcoming business ventures in the medical field. We are looking for the following features: 1. Has a readily available SDK for iOS, Android, and web platforms 2. Has readily available REST APIs for easy integration. Having webhook functionality is a plus. 3. Readily available web interface that handles ticketing, routing to agents/doctors, queueing, ticket transfer, etc. 4. Ability to send and receive files (images, pdf, documents) and location 5. Ability to set canned messages (start and end of chat) We’re targeting to build and launch the product within the next 3-9 months, and are looking to have an MAU of 68,000 by year 5. Here’s to hearing back from you with a proposed solution and possible pricing. Thanks!

  13. Alessandro Reply

    Im interested to know how many cost the access to api for chat & messaging. We are starting a new project and we neeed to found a solution releiable and performant. Reading your specs seems that your products can be integrated in our app. Also i want know if i can try before the purchase.

  14. Eisenbeiss Reply

    We’d like to build a videochat iPad app for a sales team of approximately 20 users who want to video chat in-app.

  15. Rao Reply

    I need a video and messaging app in which we could share our on going screen to the other one on the chat to show them the things on their phone….screen sharing…nd use of stickers to make the app interesting for usage.

  16. Jagat Reply

    Need for integrating in xamarin application. Can you please please trial sdk or ready to use plugin? Also provide costing plans as per features available?

  17. Mohammed Reply

    I am currently building a new mobile banking application and i want to have the ability to conduct video calling with potential and existing clients. Will need to integrate video calling capability in an app that is being built using a low-code development platform “Outsystems” so ideally would need to embed video chat SDKs for Android/ios

  18. preethi Reply

    i am developing a doctor website, where my patient can fix appointments and can go for for a voice, video and text chat option on the scheduled time. what would be cost for the same and how many concurrent users can use it? Thanks, preethi

  19. Deepak Reply

    Please call want to understand pricing for implementing one to one chat ,group chat ,Video call and screensharing functionality in one of our android Mobile App, From this app customer can connect with our backend support team.

  20. Ooi Reply

    I want to import the chat messaging package in my kotlin project, where the chat messaging feature is allowed for customer service, eg. a customer can only chat with the customer service person. May I roughly know the pricing for this particular requirement and whether or not support in kotlin chat app?

  21. Amassy Reply

    I need to use your chat API in my android chat app, can you give me more detail about pricing and chat API details how I can test before purchase

  22. Mithun Reply

    Good day… I want pricing plan and SDK integration and implementation documentation for web and mobile app. Thanks in advance.

  23. Ramesh Reply

    We need to establish a feature for our doctors and patients to have video consultation and also have chat enabled during the video consultation. I would like to know the pricing and other features that surround your chat api

Leave a Reply

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