Open In App

Build a Chat App in Android using Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Almost all brands these days need an app with chat functionality so that users can interact with each other or connect to their customer support easily. In this article, we will show you how to build a chat app for Android devices. Throughout this tutorial, we use the most lightweight, clean, and Google’s preferred programming language for Android apps – Kotlin. The development environment is Android Studio and the third-party chat SDK is from MirrorFly Chat.

Step by Step Implementation

Step 1: Create a Project in Android Studio

In order to develop an Android app, you need to create a project in the Android Studio IDE. First, be sure to install the latest version of Android Studio IDE from their Official Website. After installation, launch the IDE. It will open the Welcome to Android Studio window. Here, you can create a New Project. 

 

On the next page, choose Empty Activity and click on Next. This will take you to the Configuration Window

 

In this step, you will have to enter a few details needed for the app. Enter your app’s name, save location, and choose Kotlin from the language’s dropdown menu as we will be using it to create this app. Since we will be using the latest version of Android, choose the minimum requirement for API level as Android 5.0 (Lollipop) and click on Finish. 

Step 2: Add Build Dependencies into Your Project’s Library

One of our favorite reasons for building an app in Android studio is that – it is easy to add third-party modules to our build as dependencies. And that’s what we will do now! In the main menu of the project, navigate to Gradle Scripts > build.gradle. In this location, you can find 2 gradle files – one for the project and another for the app. We will be dealing with the app gradle because this gradle is the key zone that allows us to add our chat features to our app. Now, we already have my downloaded AAR files from MirrorFly that contains all the chat feature modules we need for our app.

Note: If you’d like to download it, it is available for a free trial on their official website. You can create an account and get access to it. 

  • appbase.aar
  • flycommons.aar
  • flynetwork.aar
  • flydatabase.aar
  • videocompression.aar
  • xmpp.aar

Add these dependencies to the app/build.gradle. Once you complete this step, this is what the main menu of your project’s navigation section will look like:

 

Next, you need to build the below codes for your project:

Kotlin




plugins {
    ...
    id 'kotlin-android'
    id 'kotlin-kapt'
}
  
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
  
    kotlinOptions {
        jvmTarget = '1.8'
    }
  
    packagingOptions {
        exclude 'META-INF/AL2.0'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LGPL2.1'
                 exclude("META-INF/*.kotlin_module")
    }
  
}


Add the following dependencies to your project:

Kotlin




dependencies {
  
     ... // your app dependencies
  
     implementation files('libs/appbase.aar')
     implementation files('libs/flycommons.aar')
     implementation files('libs/flynetwork.aar')
     implementation files('libs/flydatabase.aar')
     implementation files('libs/videocompression.aar')
     implementation files('libs/xmpp.aar')
  
 }


 

Continue adding the following codes, that the SDK files will need to execute. 

Kotlin




dependencies {
  
     ... // your app dependencies
  
     configurations {
         all {
             exclude group: 'org.json', module: 'json'
             exclude group: 'xpp3', module: 'xpp3'
         }
     }
  
     // For lifecycle listener
     implementation 'android.arch.lifecycle:extensions:1.1.1'
     annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'
  
     // For GreenDao
     implementation 'de.greenrobot:greendao:2.1.0'
  
     // For gson parsing
     implementation 'com.google.code.gson:gson:2.8.1'
  
     // for smack implementation
     implementation 'org.igniterealtime.smack:smack-android:4.4.4'
     implementation 'org.igniterealtime.smack:smack-tcp:4.4.4'
     implementation 'org.igniterealtime.smack:smack-im:4.4.4'
     implementation 'org.igniterealtime.smack:smack-extensions:4.4.4'
     implementation 'org.igniterealtime.smack:smack-sasl-provided:4.4.4'
  
     implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
     implementation 'androidx.multidex:multidex:2.0.1'
     implementation 'com.google.android.gms:play-services-location:17.0.0'
  
     // Dagger Dependencies
     api 'com.google.dagger:dagger:2.40.5'
     kapt 'com.google.dagger:dagger-compiler:2.40.5'
     api 'com.google.dagger:dagger-android:2.40.5'
     api 'com.google.dagger:dagger-android-support:2.40.5'
     kapt 'com.google.dagger:dagger-android-processor:2.40.5'
  
     // coroutines
     implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8'
     implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'
  
     // apicalls
     implementation 'com.squareup.retrofit2:retrofit:2.6.1'
     implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
     implementation 'com.squareup.okhttp3:okhttp:4.2.0'
     implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
  
     // stetho interceptor
     implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'
  
     // okhttp interceptor
     implementation 'com.squareup.okhttp3:logging-interceptor:3.14.3'
  
     // shared preference encryption
     implementation 'androidx.security:security-crypto:1.1.0-alpha03'
  
 }


Step 3: Prepare the Manifest

A manifest is an essential part of development. It defines every component of the app and will define what your app is about. First, to avoid conflicts in the imported library, we need to add the below line in the gradle.properties file. 

Kotlin




android.enableJetifier=true


Now, to prepare the manifest, navigate to app > manifests > AndroidManifest.xml

Kotlin




<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 4: Configure the App Builder

In the builder configuration, update the License Key acquired from your MirrorFly account.

Kotlin




buildTypes {
  debug {
    buildConfigField 'String', 'SDK_BASE_URL', '"https://api-preprod-sandbox.mirrorfly.com/api/v1/"'
    buildConfigField 'String', 'LICENSE', '"xxxxxxxxxxxxxxxxxxxxxxxxx"'
    buildConfigField 'String', 'WEB_CHAT_LOGIN', '"https://webchat-preprod-sandbox.mirrorfly.com/"'
    buildConfigField "String", "SUPPORT_MAIL", '"contussupport@gmail.com"'
  }
}


Once you update the key, you need to perform the Gradle sync operation. This task is done to sync the dependencies with the project. Identify the Gradle sync icon to do this. Else, go to File > Sync Project with Gradle Files.

Note: Restart Android Studio to see the changes in effect

Step 5: Initialize the SDKs

To initialize the Chat SDK, we need to add the builder class ChatSDK. In the Application Class, call the onCreate() method to start the SDK

 

Next, add the following code:

Kotlin




// For chat logging
LogMessage.enableDebugLogging(BuildConfig.DEBUG)
   
ChatSDK.Builder()
    .setDomainBaseUrl(BuildConfig.SDK_BASE_URL)
    .setLicenseKey(BuildConfig.LICENSE)
    .setIsTrialLicenceKey(true)
    .build()


Step 6: Register a User

To register a user based on the sandbox live mode, add the following code

Kotlin




FlyCore.registerUser(USER_IDENTIFIER) { isSuccess, throwable, data ->
        if(isSuccess) {
            val responseObject = data.get("data") as JSONObject
            // Get Username and password from the object
        } else {
            // Register user failed print throwable
            // to find the exception details.
      }       
}


Step 7: Connect to Chat Server

When apps across devices need to send/ receive messages, it needs to be connected via a central server. We’ll use the below code to connect our app to the chat server.

Kotlin




ChatManager.connect(object : ChatConnectionListener {
          override fun onConnected() {
          // Write your success logic here to navigate Profile Page or
          // To Start your one-one chat with your friends
          }
  
          override fun onDisconnected() {
          // Connection disconnected
          // No need implementations
         }
  
        override fun onConnectionNotAuthorized() {
        // Connection Not authorized
        // No need implementations
       }
})


Step 8: Send a Message

With the features added, the connection established, we are now left with only a few steps to deploy a feature-rich chat app. Let’s set up the app to send a message now! Add the below code: 

Kotlin




FlyMessenger.sendTextMessage(TO_JID, TEXT, listener = object : SendMessageListener {
        override fun onResponse(isSuccess: Boolean, chatMessage: ChatMessage?) {
        // you will get the message sent success response         
        }
})


Step 9: Receive a Message

Let’s now add the functionality to receive a message in the app

Kotlin




@Override
public void onMessageReceived(@NonNull ChatMessage message) {
        super.onMessageReceived(message);
        // received message object
}


Step 10: Submit your app to Playstore

We’ve now added chat features to the app. Once the steps are complete, check if you’ll need further chat features for the app and add them from here. Now, we’ll have to debug and run the app in the sandbox live mode. Once done, we are ready to launch the app in the Playstore.

The Complete Step by Step Process in Video

Conclusion

So there you have it! The app is all ready to hit the world. This is a quick and easy way to build a chat app, provided it has a good number of interactive features. It is a low code method to implement a native chat app – as we’ve built it from scratch in Android Studio using Kotlin. 



Last Updated : 18 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads