> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-rn-guide-message-privately.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Methods

> Use CometChatUIKit wrapper methods for initialization, authentication, user creation, and message sending.

<Accordion title="AI Integration Quick Reference">
  | Field         | Value                                                                                                         |
  | ------------- | ------------------------------------------------------------------------------------------------------------- |
  | Package       | `com.cometchat:chat-uikit-android`                                                                            |
  | Import        | `com.cometchat.chatuikit.CometChatUIKit`                                                                      |
  | Init          | `CometChatUIKit.init(context, uiKitSettings, callback)`                                                       |
  | Login (dev)   | `CometChatUIKit.login("UID", callback)`                                                                       |
  | Login (prod)  | `CometChatUIKit.loginWithAuthToken("AUTH_TOKEN", callback)`                                                   |
  | Other methods | `CometChatUIKit.logout()`, `CometChatUIKit.getLoggedInUser()`, `CometChatUIKit.createUser(user, callback)`    |
  | Send messages | `CometChatUIKit.sendTextMessage()`, `CometChatUIKit.sendMediaMessage()`, `CometChatUIKit.sendCustomMessage()` |
  | Note          | Use these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing                     |
</Accordion>

`CometChatUIKit` provides wrapper methods around the CometChat SDK for initialization, authentication, user creation, date formatting, and sending messages — while automatically managing internal UI Kit events so that components like Message List and Conversations stay in sync.

## When to use this

* You need to initialize the CometChat UI Kit and SDK before rendering any UI components.
* You need to log a user in or out of CometChat using an Auth Key (development) or Auth Token (production).
* You need to create a new CometChat user dynamically from your app.
* You need to send text, media, custom, or interactive messages through the UI Kit so that the Message List and Conversations components update automatically.
* You need to customize how dates and times are displayed across all UI Kit components.

## Prerequisites

* The `cometchat-chat-uikit-android` dependency added to your project.
* Your CometChat App ID, Region, and Auth Key (or Auth Token) from the [CometChat dashboard](https://app.cometchat.com/).
* `CometChatUIKit.init()` called before invoking any other UI Kit method.

## API reference

### Initialization

#### Init

You must invoke this method before using any other methods provided by the UI Kit. This initialization ensures the UI Kit and Chat SDK function correctly in your application. Call this as one of the first lines of code in your application's lifecycle.

<Warning>
  Make sure you replace the `APP_ID`, `REGION` and `AUTH_KEY` with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely.
</Warning>

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.init(context: Context, authSettings: UIKitSettings, callbackListener: CometChat.CallbackListener<String>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.init(Context context, UIKitSettings authSettings, CometChat.CallbackListener<String> callbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `init()` method signature. It accepts a `Context`, a `UIKitSettings` configuration object, and a `CallbackListener` that reports success or failure.

The `UIKitSettings` is an important parameter of the `init()` function. It serves as the base settings object, housing properties such as `appId`, `region`, and `authKey`.

Here's the table format for the properties available in `UIKitSettings`:

| Method                               | Type                          | Description                                                                                                                           |
| ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **setAppId**                         | `String`                      | Sets the unique ID for the app, available on dashboard                                                                                |
| **setRegion**                        | `String`                      | Sets the region for the app ('us' or 'eu')                                                                                            |
| **setAuthKey**                       | `String`                      | Sets the auth key for the app, available on dashboard                                                                                 |
| **subscribePresenceForAllUsers**     | `String`                      | Sets subscription type for tracking the presence of all users                                                                         |
| **subscribePresenceForFriends**      | `String`                      | Sets subscription type for tracking the presence of friends                                                                           |
| **subscribePresenceForRoles**        | `String`                      | Sets subscription type for tracking the presence of users with specified roles                                                        |
| **setAutoEstablishSocketConnection** | `Boolean`                     | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default |
| **setAIFeatures**                    | `List<AIExtensionDataSource>` | Sets the AI Features that need to be added in UI Kit                                                                                  |
| **setExtensions**                    | `List<ExtensionsDataSource>`  | Sets the list of extension that need to be added in UI Kit                                                                            |
| **dateTimeFormatterCallback**        | `DateTimeFormatterCallback`   | Interface containing callback methods to format different types of timestamps.                                                        |

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val uiKitSettings: UIKitSettings = UIKitSettingsBuilder()
        .setRegion(your_region)
        .setAppId(your_appID)
        .setAuthKey(your_authKey)
        .subscribePresenceForAllUsers()
        .build()

    CometChatUIKit.init(context, uiKitSettings, object : CometChat.CallbackListener<String>() {
        override fun onSuccess(response: String) {
            Log.i(TAG, "CometChat init onSuccess: $response")
        }

        override fun onError(e: CometChatException) {
            Log.e(TAG, "CometChat init exception: $e")
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    UIKitSettings uiKitSettings = new UIKitSettings.UIKitSettingsBuilder()
        .setRegion(your_region)
        .setAppId(your_appID)
        .setAuthKey(your_authKey)
        .subscribePresenceForAllUsers().build();


    CometChatUIKit.init(context, uiKitSettings, new CometChat.CallbackListener<String>() {
        @Override
        public void onSuccess(String response) {
            Log.i(TAG, "CometChat init onSuccess: "+response);
        }

        @Override
        public void onError(CometChatException e) {
            Log.e(TAG, "CometChat init exception: "+e);
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `UIKitSettings` object with your app ID, region, and auth key, then initializes the CometChat UI Kit. On success, the SDK and UI Kit are ready for use. On error, the `CometChatException` provides failure details.

***

### Authentication

#### Login using Auth Key

Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, use [Auth Token](#login-using-auth-token) instead of Auth Key.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.login(uid: String, callbackListener: CometChat.CallbackListener<User>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.login(String uid, CometChat.CallbackListener <User> callbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `login()` method signature. It accepts a user ID string and a `CallbackListener` that returns the logged-in `User` object on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    CometChatUIKit.login(UID, object : CometChat.CallbackListener<User>() {
     override fun onSuccess(user: User) {
         Log.i(TAG, "CometChat Login Successful : $user")
     }

     override fun onError(e: CometChatException) {
         Log.e(TAG, "CometChat Login Failed : ${e.message}")
     }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    CometChatUIKit.login(UID, new CometChat.CallbackListener<User>() {
         @Override
         public void onSuccess(User user) {
             Log.i(TAG, "CometChat Login Successful : " + user.toString());
         }
         @Override
         public void onError(CometChatException e) {
             Log.e(TAG, "CometChat Login Failed : " + e.getMessage());
         }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Logs in a user by their `UID` using the Auth Key configured during initialization. On success, the `User` object is returned. On error, the `CometChatException` provides failure details.

***

#### Login using Auth Token

This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety.

1. [Create a User](/rest-api/chat-apis) via the CometChat API when the user signs up in your app.

2. [Create an Auth Token](/rest-api/chat-apis) via the CometChat API for the new user and save the token in your database.

3. Load the Auth Token in your client and pass it to the `loginWithAuthToken()` method.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.loginWithAuthToken(authToken: String, callbackListener: CometChat.CallbackListener<User>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.loginWithAuthToken(String authToken, CometChat.CallbackListener <User> callbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `loginWithAuthToken()` method signature. It accepts a server-generated auth token string and a `CallbackListener` that returns the logged-in `User` object on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.loginWithAuthToken(AuthToken, object : CometChat.CallbackListener<User>() {
     override fun onSuccess(user: User) {
         Log.i(TAG, "CometChat Login Successful : $user")
     }

     override fun onError(e: CometChatException) {
         Log.e(TAG, "CometChat Login Failed : ${e.message}")
     }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.loginWithAuthToken(AuthToken, new CometChat.CallbackListener<User>() {
         @Override
         public void onSuccess(User user) {
             Log.i(TAG, "CometChat Login Successful : " + user.toString());
         }
         @Override
         public void onError(CometChatException e) {
             Log.e(TAG, "CometChat Login Failed : " + e.getMessage());
         }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Logs in a user using a server-generated Auth Token instead of an Auth Key. This is the recommended approach for production apps because the Auth Key never appears in client code. On success, the `User` object is returned.

***

### Logout

The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `logout()` function.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.logout(callbackListener: CometChat.CallbackListener<String>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.logout(CometChat.CallbackListener <String> callbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `logout()` method signature. It accepts a `CallbackListener` that reports success or failure of the logout operation.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    CometChatUIKit.logout(object: CometChat.CallbackListener<String>() {
        override fun onSuccess(s: String) {
            // your action on logout
        }

        override fun onError(e: CometChatException) {
            // Error handling
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    CometChatUIKit.logout(new CometChat.CallbackListener<String>() {
        @Override
        public void onSuccess(String s) {
            // your action on logout
        }
        @Override
        public void onError(CometChatException e) {
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Logs out the current user, clears the session data, and tears down the internal event system. Call this before logging in a different user to avoid conflicts.

***

### Create User

You can dynamically create users on CometChat using the `createUser()` function. This is useful when users are registered or authenticated by your system and then need to be created on CometChat.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.createUser(user: User, callbackListener: CometChat.CallbackListener<User>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.createUser(User user, CometChat.CallbackListener <User> callbackListener);
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `createUser()` method signature. It accepts a `User` object (with UID, name, and optional avatar) and a `CallbackListener` that returns the created `User` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val user = User("user_uid", "user_name")
    user.setAvatar("user_avatar_url")

    CometChatUIKit.createUser(user, object : CometChat.CallbackListener<User>() {
        override fun onSuccess(user: User) {
            // Action on success
        }

        override fun onError(e: CometChatException) {
            // Action on error
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    User user = new User("user_uid","user_name");
    user.setAvatar("user_avatar_url");

    CometChatUIKit.createUser(user, new CometChat.CallbackListener<User>() {
        @Override
        public void onSuccess(User user) {
        }
        @Override
        public void onError(CometChatException e) {
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a new user on CometChat with the specified UID, name, and avatar URL. On success, the created `User` object is returned. On error, the `CometChatException` provides failure details.

***

### DateFormatter

By providing a custom implementation of the `DateTimeFormatterCallback`, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application.

Each method in the interface corresponds to a specific case:

`time(long timestamp)` → Custom full timestamp format

`today(long timestamp)` → Called when a message is from today

`yesterday(long timestamp)` → Called for yesterday's messages

`lastWeek(long timestamp)` → Messages from the past week

`otherDays(long timestamp)` → Older messages

`minute(long timestamp)` / `hour(long timestamp)` → Exact time unit

`minutes(long diffInMinutesFromNow, long timestamp)` → e.g., "5 minutes ago"

`hours(long diffInHourFromNow, long timestamp)` → e.g., "2 hours ago"

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    import java.text.SimpleDateFormat
    import java.util.*

    val uiKitSettings = UIKitSettings.UIKitSettingsBuilder()
        .setAppId(appId)
        .setRegion(region)
        .setDateTimeFormatterCallback(object : DateTimeFormatterCallback {

            private val fullTimeFormatter = SimpleDateFormat("hh:mm a", Locale.getDefault())
            private val dateFormatter = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())

            override fun time(timestamp: Long): String {
                return fullTimeFormatter.format(Date(timestamp))
            }

            override fun today(timestamp: Long): String {
                return "Today"
            }

            override fun yesterday(timestamp: Long): String {
                return "Yesterday"
            }

            override fun lastWeek(timestamp: Long): String {
                return "Last Week"
            }

            override fun otherDays(timestamp: Long): String {
                return dateFormatter.format(Date(timestamp))
            }

            override fun minutes(diffInMinutesFromNow: Long, timestamp: Long): String {
                return "$diffInMinutesFromNow mins ago"
            }

            override fun hours(diffInHourFromNow: Long, timestamp: Long): String {
                return "$diffInHourFromNow hrs ago"
            }
        })
        .setAuthKey(authKey)
        .subscribePresenceForAllUsers()
        .build()

    CometChatUIKit.init(context, uiKitSettings, object : CometChat.CallbackListener<String>() {
        override fun onSuccess(s: String?) {
            Log.d("CometChatInit", "Success: $s")
        }

        override fun onError(e: CometChatException?) {
            Log.e("CometChatInit", "Error: ${e?.message}")
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;

    UIKitSettings uiKitSettings = new UIKitSettings.UIKitSettingsBuilder()
        .setAppId(appId)
        .setRegion(region)
        .setDateTimeFormatterCallback(new DateTimeFormatterCallback() {

            private final SimpleDateFormat fullTimeFormatter = new SimpleDateFormat("hh:mm a", Locale.getDefault());
            private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());

            @Override
            public String time(long timestamp) {
                return fullTimeFormatter.format(new Date(timestamp));
            }

            @Override
            public String today(long timestamp) {
                return "Today";
            }

            @Override
            public String yesterday(long timestamp) {
                return "Yesterday";
            }

            @Override
            public String lastWeek(long timestamp) {
                return "Last Week";
            }

            @Override
            public String otherDays(long timestamp) {
                return dateFormatter.format(new Date(timestamp));
            }

            @Override
            public String minutes(long diffInMinutesFromNow, long timestamp) {
                return diffInMinutesFromNow + " mins ago";
            }

            @Override
            public String hours(long diffInHourFromNow, long timestamp) {
                return diffInHourFromNow + " hrs ago";
            }
        })
        .setAuthKey(authKey)
        .subscribePresenceForAllUsers()
        .build();

    CometChatUIKit.init(context, uiKitSettings, new CometChat.CallbackListener<String>() {
        @Override
        public void onSuccess(String s) {
            Log.d("CometChatInit", "Success: " + s);
        }

        @Override
        public void onError(CometChatException e) {
            Log.e("CometChatInit", "Error: " + e.getMessage());
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Configures a custom `DateTimeFormatterCallback` on `UIKitSettings` and passes it to `CometChatUIKit.init()`. This globally overrides how timestamps appear across all UI Kit components — today's messages show "Today", yesterday's show "Yesterday", recent messages show "X mins ago" or "X hrs ago", last week's show "Last Week", and older messages show the full date in "dd MMM yyyy" format.

***

### Base Message

#### Text Message

To send a text message to a single user or a group, use the `sendTextMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message.

> It's essential to understand the difference between `CometChatUIKit.sendTextMessage()` and `CometChat.sendTextMessage()`. When you use `CometChatUIKit.sendTextMessage()`, it automatically adds the message to the [MessagesListComponent](/ui-kit/android/message-list) and [ConversationsComponent](/ui-kit/android/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendTextMessage()` only sends the message and doesn't automatically update these components in the UI Kit.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendTextMessage(textMessage: TextMessage, messageCallbackListener: CometChat.CallbackListener<TextMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendTextMessage(TextMessage textMessage, CometChat.CallbackListener <TextMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendTextMessage()` method signature. It accepts a `TextMessage` object and a `CallbackListener` that returns the sent `TextMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val textMessage = TextMessage("receiver_uid", "your_text_message", CometChatConstants.RECEIVER_TYPE_USER)
    CometChatUIKit.sendTextMessage(textMessage, object : CometChat.CallbackListener<TextMessage>() {
        override fun onSuccess(message: TextMessage) {
            // Action on success
        }

        override fun onError(e: CometChatException) {
            // Action on error
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    TextMessage textMessage = new TextMessage("receiver_uid", "your_text_message", CometChatConstants.RECEIVER_TYPE_USER);
    CometChatUIKit.sendTextMessage(textMessage, new CometChat.CallbackListener<TextMessage>() {
        @Override
        public void onSuccess(TextMessage message) {
        }
        @Override
        public void onError(CometChatException e) {
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `TextMessage` targeting a user with the receiver type `RECEIVER_TYPE_USER`, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components.

***

#### Media Message

To send a media message to a single user or a group, use the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message.

> It's essential to understand the difference between `CometChatUIKit.sendMediaMessage()` and `CometChat.sendMediaMessage()`. When you use `CometChatUIKit.sendMediaMessage()`, it automatically adds the message to the [MessagesListComponent](/ui-kit/android/message-list) and [ConversationsComponent](/ui-kit/android/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendMediaMessage()` only sends the message and doesn't automatically update these components in the UI Kit.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendMediaMessage(mediaMessage: MediaMessage, messageCallbackListener: CometChat.CallbackListener<MediaMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendMediaMessage(MediaMessage mediaMessage, CometChat.CallbackListener <MediaMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendMediaMessage()` method signature. It accepts a `MediaMessage` object and a `CallbackListener` that returns the sent `MediaMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val mediaMessage = MediaMessage("receiver_uid", File("your_filePath"), CometChatConstants.MESSAGE_TYPE_FILE, CometChatConstants.RECEIVER_TYPE_USER)

    CometChatUIKit.sendMediaMessage(mediaMessage, object : CometChat.CallbackListener<MediaMessage>() {
        override fun onSuccess(mediaMessage: MediaMessage) {
            // Action on success
        }

        override fun onError(e: CometChatException) {
            // Action on error
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    MediaMessage mediaMessage = new MediaMessage("receiver_uid", new File("your_filePath"), CometChatConstants.MESSAGE_TYPE_FILE, CometChatConstants.RECEIVER_TYPE_USER);

    CometChatUIKit.sendMediaMessage(mediaMessage, new CometChat.CallbackListener<MediaMessage>() {
        @Override
        public void onSuccess(MediaMessage mediaMessage) {
        }
        @Override
        public void onError(CometChatException e) {
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `MediaMessage` with a file path and message type `MESSAGE_TYPE_FILE`, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components.

***

#### Custom Message

To send a custom message to a single user or a group, use the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message.

> It's essential to understand the difference between `CometChatUIKit.sendCustomMessage()` and `CometChat.sendCustomMessage()`. When you use `CometChatUIKit.sendCustomMessage()`, it automatically adds the message to the [MessagesList](/ui-kit/android/message-list) and [ConversationsComponent](/ui-kit/android/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendCustomMessage()` only sends the message and doesn't automatically update these components in the UI Kit.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendCustomMessage(customMessage: CustomMessage, messageCallbackListener: CometChat.CallbackListener<CustomMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendCustomMessage(CustomMessage customMessage, CometChat.CallbackListener <CustomMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendCustomMessage()` method signature. It accepts a `CustomMessage` object and a `CallbackListener` that returns the sent `CustomMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val customType = "your_message_type"
    val customData = JSONObject()

    customData.put("key1", "value1")
    customData.put("key2", "value2")
    customData.put("key3", "value3")
    customData.put("key4", "value4")

    val customMessage = CustomMessage("receiver_uid", CometChatConstants.RECEIVER_TYPE_USER, customType, customData)

    CometChatUIKit.sendCustomMessage(customMessage, object : CometChat.CallbackListener<CustomMessage>() {
        override fun onSuccess(customMessage: CustomMessage) {
            // Action on success
        }

        override fun onError(e: CometChatException) {
            // Action on error
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    String customType = "your_message_type";
    JSONObject customData = new JSONObject();

    customData.put("key1","value1");
    customData.put("key2","value2");
    customData.put("key3","value3");
    customData.put("key4","value4");

    CustomMessage customMessage = new CustomMessage("receiver_uid", CometChatConstants.RECEIVER_TYPE_USER,customType, customData);

    CometChatUIKit.sendCustomMessage(customMessage, new CometChat.CallbackListener<CustomMessage>() {
        @Override
        public void onSuccess(CustomMessage mediaMessage) {
        }
        @Override
        public void onError(CometChatException e) {
        }
    });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `CustomMessage` with a custom type string and JSON data payload, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components.

> Note: To display custom messages in the [MessageList](/ui-kit/android/message-list), you must create and register a new [MessageTemplate](/ui-kit/android/message-template) that defines how to render your custom message type.

***

### Interactive Message

#### Form Message

To send a Form message to a single user or a group, utilize the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that message.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendFormMessage(formmessage: FormMessage, disableLocalEvents: Boolean, messageCallbackListener: CometChat.CallbackListener<FormMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendFormMessage(FormMessage formmessage, boolean disableLocalEvents, CometChat.CallbackListener <FormMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendFormMessage()` method signature. It accepts a `FormMessage` object and a `CallbackListener` that returns the sent `FormMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val cometChatMessages = findViewById<CometChatMessages>(R.id.messages)
    cometChatMessages.setUser(user)

    val elementEntities = mutableListOf<ElementEntity>()
    val textInputElement1 = TextInputElement("element1", "Name")
    val textInputElement2 = TextInputElement("element2", "Last Name")
    val textInputElement3 = TextInputElement("element3", "Address").apply {
        maxLines = 5
    }
    elementEntities.add(textInputElement1)
    elementEntities.add(textInputElement2)
    elementEntities.add(textInputElement3)

    val urlNavigationAction = URLNavigationAction("https://www.cometchat.com/")

    val submitElement = ButtonElement("idSubmit", "submit", urlNavigationAction).apply {
        disableAfterInteracted = true
    }
    val formMessage = FormMessage("uid-1001", UIKitConstants.ReceiverType.USER, elementEntities, submitElement).apply {
        title = "Socity Survey"
        allowSenderInteraction = true
        sender = CometChatUIKit.loggedInUser
        sentAt = System.currentTimeMillis() / 1000
        receiver = user
    }

    CometChatUIKit.sendFormMessage(formMessage, false, object : CometChat.CallbackListener<FormMessage>() {
        override fun onSuccess(formMessage: FormMessage) {
            // Handle success
        }

        override fun onError(e: CometChatException) {
            e.printStackTrace()
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    CometChatMessages cometChatMessages = findViewById(R.id.messages);
           cometChatMessages.setUser(user);

            List<ElementEntity> elementEntities = new ArrayList<>();
    //here we have created the object to display the TextInput into the form
            TextInputElement textInputElement1 = new TextInputElement("element1", "Name");
            TextInputElement textInputElement2 = new TextInputElement("element2", "Last Name");
            TextInputElement textInputElement3 = new TextInputElement("element3", "Address");
            textInputElement3.setMaxLines(5);
            elementEntities.add(textInputElement1);
            elementEntities.add(textInputElement2);
            elementEntities.add(textInputElement3);


    //here we have created the navigation action which will executated on a click of button
            URLNavigationAction urlNavigationAction = new URLNavigationAction("https://www.cometchat.com/");

            ButtonElement submitElement = new ButtonElement("idSubmit", "submit", urlNavigationAction);
            submitElement.setDisableAfterInteracted(true);
            FormMessage formMessage = new FormMessage("uid-1001", UIKitConstants.ReceiverType.USER, elementEntities, submitElement);
            formMessage.setTitle("Socity Survey");
            formMessage.setAllowSenderInteraction(true); // this will confirm if sender can interact with that form or not
            formMessage.setSender(CometChatUIKit.getLoggedInUser());
            formMessage.setSentAt(System.currentTimeMillis() / 1000);
            formMessage.setReceiver(user); // set Receiver user/group object

            CometChatUIKit.sendFormMessage(formMessage, false, new CometChat.CallbackListener<FormMessage>() {
                @Override
                public void onSuccess(FormMessage formMessage) {

                }

                @Override
                public void onError(CometChatException e) {
                    e.printStackTrace();
                }
            });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `FormMessage` with three text input fields (Name, Last Name, Address) and a submit button that navigates to a URL. The form is sent to user `uid-1001` and allows the sender to interact with it. The message appears as an interactive form bubble in the Message List.

***

#### Card Message

To send a Card message to a single user or a group, utilize the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the message.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendCardMessage(cardMessage: CardMessage, disableLocalEvents: Boolean, messageCallbackListener: CometChat.CallbackListener<CardMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendCardMessage(CardMessage cardMessage, boolean disableLocalEvents, CometChat.CallbackListener <CardMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendCardMessage()` method signature. It accepts a `CardMessage` object and a `CallbackListener` that returns the sent `CardMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val elementEntities = mutableListOf<BaseInteractiveElement>()

    val urlNavigationAction = URLNavigationAction("https://www.cometchat.com/")

    val buttonElement = ButtonElement("idbtn", "submit", urlNavigationAction).apply {
        disableAfterInteracted = true
        text = "Learn more"
    }
    elementEntities.add(buttonElement)

    val cardMessage = CardMessage(receiverId, receivertype, "Decorative Text to show on Card", elementEntities).apply {
        imageUrl = "https://anyImageUrl.com"
        sender = CometChatUIKit.loggedInUser
        sentAt = System.currentTimeMillis() / 1000
        receiver = user
    }

    CometChatUIKit.sendCardMessage(cardMessage, false, object : CometChat.CallbackListener<CardMessage>() {
        override fun onSuccess(cardMessage: CardMessage) {
            // Handle success
        }

        override fun onError(e: CometChatException) {
            e.printStackTrace()
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    List<BaseInteractiveElement> elementEntities = new ArrayList<>();

    URLNavigationAction urlNavigationAction = new URLNavigationAction("https://www.cometchat.com/");

    ButtonElement buttonElement = new ButtonElement("idbtn", "submit", urlNavigationAction);
    buttonElement.setDisableAfterInteracted(true); // button will be disable after interacted
    buttonElement.setText("Learn more");

    elementEntities.add(buttonElement);
    // Create a new instance of CardMessage
    CardMessage cardMessage = new CardMessage(receiverId, receivertype, "Decorative Text to show on Card", elementEntities);

    cardMessage.setImageUrl("https://anyImageUrl.com"); // here you can set the Image url to the Card Message
    cardMessage.setSender(CometChatUIKit.getLoggedInUser());
    cardMessage.setSentAt(System.currentTimeMillis() / 1000);
    cardMessage.setReceiver(user); //here receiver user or group object need to be set
    CometChatUIKit.sendCardMessage(cardMessage, false, new CometChat.CallbackListener<CardMessage>() {
     @Override
       public void onSuccess(CardMessage cardMessage) {

       }

      @Override
        public void onError(CometChatException e) {
               e.printStackTrace();
         }
     });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `CardMessage` with decorative text, an image URL, and a "Learn more" button that navigates to a URL. The card is sent to the specified receiver and appears as an interactive card bubble in the Message List.

***

#### Scheduler Message

To send a Scheduler message to a single user or a group, use the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendSchedulerMessage(schedulerMessage: SchedulerMessage, disableLocalEvents: Boolean, messageCallbackListener: CometChat.CallbackListener<SchedulerMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendSchedulerMessage(SchedulerMessage schedulerMessage, boolean disableLocalEvents, CometChat.CallbackListener <SchedulerMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendSchedulerMessage()` method signature. It accepts a `SchedulerMessage` object and a `CallbackListener` that returns the sent `SchedulerMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val schedulerMessage = SchedulerMessage().apply {
        duration = 60
        allowSenderInteraction = true
        title = "Meet Dr. Jackob"
        bufferTime = 15
        avatarUrl = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRdRz0HEBl1wvncmX6rU8wFrRDxt2cvn2Dq9w&usqp=CAU"
        goalCompletionText = "Meeting Scheduled Successfully!!"
        timezoneCode = TimeZone.getDefault().id
        dateRangeStart = "2024-01-01"
        dateRangeEnd = "2024-12-31"
        receiverUid = "cometchat-uid-1"
        availability = hashMapOf(
            "monday" to listOf(TimeRange("0000", "1359")),
            "tuesday" to listOf(TimeRange("0000", "1559")),
            "wednesday" to listOf(TimeRange("0000", "0659")),
            "thursday" to listOf(TimeRange("0000", "0959")),
            "friday" to listOf(TimeRange("0000", "1059"))
        )
        scheduleElement = ButtonElement("21", "Submit",
            APIAction("https://www.example.com", "POST", "data")
        )
        receiverType = CometChatConstants.RECEIVER_TYPE_USER
        sender = CometChatUIKit.loggedInUser
        sentAt = System.currentTimeMillis() / 1000
        receiver = user
    }

    CometChatUIKit.sendSchedulerMessage(schedulerMessage, false, object : CometChat.CallbackListener<SchedulerMessage>() {
        override fun onSuccess(schedulerMessage: SchedulerMessage) {
            // SchedulerMessage sent successfully
        }

        override fun onError(e: CometChatException) {
            // Error occurred while sending SchedulerMessage
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    SchedulerMessage schedulerMessage = new SchedulerMessage();
            schedulerMessage.setDuration(60);
            schedulerMessage.setAllowSenderInteraction(true); // true to set the sender as the scheduler
            schedulerMessage.setTitle("Meet Dr. Jackob");
            schedulerMessage.setBufferTime(15);
            schedulerMessage.setAvatarUrl("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRdRz0HEBl1wvncmX6rU8wFrRDxt2cvn2Dq9w&usqp=CAU");
            schedulerMessage.setGoalCompletionText("Meeting Scheduled Successfully!!");

            TimeZone timeZone = TimeZone.getDefault();
            schedulerMessage.setTimezoneCode(timeZone.getID());
            schedulerMessage.setDateRangeStart("2024-01-01");
            schedulerMessage.setDateRangeEnd("2024-12-31");
            schedulerMessage.setReceiverUid("cometchat-uid-1");

            HashMap<String, List<TimeRange>> availability = new HashMap<>();
            availability.put("monday", Arrays.asList(new TimeRange("0000", "1359")));
            availability.put("tuesday", Arrays.asList(new TimeRange("0000", "1559")));
            availability.put("wednesday", Arrays.asList(new TimeRange("0000", "0659")));
            availability.put("thursday", Arrays.asList(new TimeRange("0000", "0959")));
            availability.put("friday", Arrays.asList(new TimeRange("0000", "1059")));
            schedulerMessage.setAvailability(availability);
            APIAction clickAction = new APIAction("https://www.example.com", "POST", "data");

            ButtonElement scheduleElement = new ButtonElement("21", "Submit", clickAction);
            schedulerMessage.setScheduleElement(scheduleElement);

    				schedulerMessage.setReceiverType(CometChatConstants.RECEIVER_TYPE_USER);
            schedulerMessage.setSender(CometChatUIKit.getLoggedInUser());
            schedulerMessage.setSentAt(System.currentTimeMillis() / 1000);
            schedulerMessage.setReceiver(user);

    				CometChatUIKit.sendSchedulerMessage(schedulerMessage,false, new 	CometChat.CallbackListener<SchedulerMessage>() {
                @Override
                public void onSuccess(SchedulerMessage schedulerMessage) {
                    // SchedulerMessage sent successfully
                }

                @Override
                public void onError(CometChatException e) {
                    // Error occurred while sending SchedulerMessage
                }
            });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `SchedulerMessage` configured with a 60-minute meeting duration, 15-minute buffer, weekly availability slots, and a submit button that posts to an API endpoint. The scheduler bubble lets the receiver pick a time slot and appears in the Message List.

***

#### Custom InteractiveMessage

To send a Custom Interactive message to a single user or a group, use the `sendCustomInteractiveMessage()` function. This function requires a `CustomInteractiveMessage` object as its argument.

**Signature:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChatUIKit.sendCustomInteractiveMessage(customInteractiveMessage: CustomInteractiveMessage, disableLocalEvents: Boolean, messageCallbackListener: CometChat.CallbackListener<CustomInteractiveMessage>)
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChatUIKit.sendCustomInteractiveMessage(CustomInteractiveMessage customInteractiveMessage, boolean disableLocalEvents, CometChat.CallbackListener <CustomInteractiveMessage> messageCallbackListener)
    ```
  </Tab>
</Tabs>

> **What this does:** Declares the `sendCustomInteractiveMessage()` method signature. It accepts a `CustomInteractiveMessage` object and a `CallbackListener` that returns the sent `CustomInteractiveMessage` on success.

**Usage:**

<Tabs>
  <Tab title="Kotlin">
    ```kotlin lines theme={null}
    val jsonObject = JSONObject()
    try {
        jsonObject.put("text", "custom Interactive message")
    } catch (e: JSONException) {
        throw RuntimeException(e)
    }

    val customInteractiveMessage = CustomInteractiveMessage(receiverId, receiverType, jsonObject) // receiverType could be user/group
    customInteractiveMessage.sender = CometChatUIKit.getLoggedInUser()
    customInteractiveMessage.receiver = user // set Receiver user/group object

    CometChatUIKit.sendCustomInteractiveMessage(customInteractiveMessage, false, object : CometChat.CallbackListener<CustomInteractiveMessage>() {
        override fun onSuccess(customInteractiveMessage: CustomInteractiveMessage) {

        }

        override fun onError(e: CometChatException) {
            e.printStackTrace()
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java lines theme={null}
    JSONObject jsonObject = new JSONObject();
     try {
       jsonObject.put("text", "custom Interactive message");
     } catch (JSONException e) {
       throw new RuntimeException(e);
     }

    CustomInteractiveMessage customInteractiveMessage = new CustomInteractiveMessage(receiverId,receiverType, jsonObject); //receiverType could be user/group
    customInteractiveMessage.setSender(CometChatUIKit.getLoggedInUser());
    customInteractiveMessage.setReceiver(user); // set Receiver user/group object

    CometChatUIKit.sendCustomInteractiveMessage(customInteractiveMessage, false, new CometChat.CallbackListener<CustomInteractiveMessage>() {
              @Override
              public void onSuccess(CustomInteractiveMessage customInteractiveMessage) {

               }
              @Override
              public void onError(CometChatException e) {
                    e.printStackTrace();
              }
        });
    ```
  </Tab>
</Tabs>

> **What this does:** Creates a `CustomInteractiveMessage` with a JSON payload and sends it through the UI Kit. The message is delivered to the specified receiver and can be rendered with a custom template.

> Note: To display custom messages in the [MessageList](/ui-kit/android/message-list), you must create and register a new [MessageTemplate](/ui-kit/android/message-template#new-templates) that defines how to render your custom message types

***

## Next steps

<CardGroup cols={2}>
  <Card title="Events Reference" icon="bolt" href="/ui-kit/android/events">
    Listen for real-time UI Kit events for users, groups, conversations, messages, and calls
  </Card>

  <Card title="Message List" icon="messages" href="/ui-kit/android/message-list">
    Display and customize the message list where sent messages appear
  </Card>

  <Card title="Conversations" icon="comments" href="/ui-kit/android/conversations">
    Display and customize the conversations list that updates when messages are sent
  </Card>
</CardGroup>
