# Android (/en/api-reference/api-ref/signaling/android)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

The Signaling SDK API reference is divided into the following sections:

* [Setup](#setup)
* [User authentication](#user-authentication)
* [Channels](#channels)
* [Topics](#topics)
* [Messages](#messages)
* [Presence](#presence)
* [Storage](#storage)
* [Lock](#lock)
* [Enumerated types](#enumerated-types)
* [Troubleshooting](#troubleshooting)

## Setup [#setup]

The API reference for the Signaling SDK documents interface descriptions, methods, basic usage, and return values of the Signaling APIs.

### RtmConfig [#rtmconfig]

#### Description [#description]

Use the `RtmConfig` to set additional properties for Signaling initialization. These configuration properties will take effect throughout the lifecycle of the Signaling client and affect the behavior of the Signaling client.

#### Method [#method]

You can create `RtmConfig` instances as follows:

```java
RtmConfig rtmConfig = new RtmConfig.Builder("appid", "userId")
    .areaCode(EnumSet.of(RtmConstants.RtmAreaCode.NA, RtmConstants.RtmAreaCode.EU))
    .eventListener(eventListener)
    .protocolType(protocolType)
    .presenceTimeout(300)
    .heartbeatInterval(5)
    .reconnectTimeout(60)
    .useStringUserId(true)
    .ispPolicyEnabled(false)
    .proxyConfig(proxyConfig)
    .logConfig(logConfig)
    .encryptionConfig(encryptionConfig)
    .privateConfig(privateConfig)
    .build();
```

|      Properties     |          Type         | Required |  Default  | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| :-----------------: | :-------------------: | :------: | :-------: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|       `appId`       |         string        | Required |     -     | App ID obtained when creating a project in the Agora Console.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|       `userId`      |         string        | Required |     -     | User ID for identify a user or a device. To distinguish each user or device, you need to ensure that the `userId` parameter is globally unique and remains unchanged throughout the user or device's lifecycle.                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
|      `areaCode`     |     `RtmAreaCode`     | Optional |   `GLOB`  | Service area code, you can choose according to the region where your business is deployed. See [`RtmAreaCode`](#enumvareacod-e).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
|   `eventListener`   |   `RtmEventListener`  | Required |     -     | Signaling event notification listener settings. See [Event listeners](#event-listeners).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|    `protocolType`   |   `RtmProtocolType`   | Optional | `TCP_UDP` | Protocol types for message transmission. By default, Signaling utilizes one-way TCP and one-way UDP protocols for transmission. You have the flexibility to modify the protocol types based on your requirements. See [`RtmProtocolType`](#enumvprotocoltyp-e).                                                                                                                                                                                                                                                                                                                                                                                                                     |
|  `presenceTimeout`  |          int          | Optional |   `300`   | Presence timeout in seconds, and the value range is \[5,300]. This parameter refers the delay imposed by the Signaling server before sending a `REMOTE_TIMEOUT` event notification to other users once it determines that a client has timed out. If the client reconnects and returns to the channel within the specified time, the Signaling server does not send the `REMOTE_TIMEOUT` event notification to other participants or delete the temporary user data associated with the user.                                                                                                                                                                                       |
| `heartbeatInterval` |          int          | Optional |    `5`    | Heartbeat interval in seconds, and the value range is \[5,1800]. This parameter refers to the time interval at which the client sends heartbeat packets to the Signaling server. If the client fails to send heartbeat packets to the Signaling server within the specified time, the Signaling server determines that the client has timed out. Please note that this parameter affects the PCU count, which in turn affects billing.                                                                                                                                                                                                                                              |
|  `reconnectTimeout` |          int          | Optional |    `0`    | SDK connection timeout in seconds. The value range is \[15,3600]. The default value is `0` which means no timeout; the SDK keeps retrying until successful. This parameter applies to both the initial login to thee Signaling service and reconnection after disconnection: <br />- If the initial login times out, the SDK triggers the `onFailure` callback with `errorInfo` as `LOGIN_TIMEOUT`, and also triggers the `onLinkStateChanged` callback with `currentState` as `FAILED` and `reason` as `LOGIN_TIMEOUT`. <br />- If reconnection times out, the SDK triggers the `onLinkStateChanged` callback with `currentState` as `FAILED` and `reason` as `RECONNECT_TIMEOUT`. |
|  `useStringUserId`  |          Bool         | Optional |   `true`  | Whether to use string-type user IDs:<br />- `true`: Use string-type user IDs. <br />- `false`: Use number-type user IDs. The SDK automatically converts string-type user IDs to number-type ones. In this case, the `userId` parameter must be a numeric string (for example, `"123456"`), otherwise initialization fails.When using Agora RTC and Signaling products at the same time, it is necessary to ensure that the `userId` parameter is consistent.                                                                                                                                                                                                                        |
|  `ispPolicyEnabled` |          Bool         | Optional |  `false`  | Whether to enable the ISP domain policy restriction. In IoT scenarios, devices may be restricted by Internet Service Providers (ISPs). Use this field to set the SDK's connection mode to connect to servers with domains registered with the operator or those in the IP whitelist: <br />- `true`: Enable the ISP domain policy restriction. This setting applies to scenarios where IoT devices use IoT SIM cards for network access. The SDK will only connect to servers with domains registered with the operator or those in the IP whitelist. <br />- `false`: (Default) Disable the ISP domain policy restriction. This setting applies to most common scenarios.          |
|     `logConfig`     |     `RtmLogConfig`    | Optional |     -     | Log configuration properties such as the log storage size, storage path, and level.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
|    `proxyConfig`    |    `RtmProxyConfig`   | Optional |     -     | When using the Proxy feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
|  `encryptionConfig` | `RtmEncryptionConfig` | Optional |     -     | When using the client-side encryption feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|   `privateConfig`   |   `RtmPrivateConfig`  | Optional |     -     | When using the private deployment feature of Signaling, you need to configure this parameter.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

##### RtmLogConfig [#rtmlogconfig]

Use the `RtmLogConfig` instance to configure and store local log files named `agora.log`. During the debugging phase, you can greatly improve efficiency by storing and tracking the running status of the app through logs. If you encounter complex problems and need Agora technical support to assist with the investigation, you need to provide the log information. `RtmLogConfig` contains the following properties:

|   Properties   |      Type     | Required | Default | Description                                                                                                                                                                                                                |
| :------------: | :-----------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `filePath`   |     String    | Optional |    -    | Log file storage paths.                                                                                                                                                                                                    |
| `fileSizeInKB` |      int      | Optional |  `1024` | Log file size in KB, with a value range of \[128,1024].<br />- If the value you enter is less than 128, the SDK sets the value to 128.<br />- If the value you enter is greater than 1024, the SDK sets the value to 1024. |
|     `level`    | `RtmLogLevel` | Optional |  `INFO` | Output level of log information. See [`RtmLogLevel`](#enumvlogleve-l).                                                                                                                                                     |

##### RtmProxyConfig [#rtmproxyconfig]

Use the `RtmProxyConfig` instance to set properties related to the client Proxy service. In some restricted network environments, you might need to use this feature.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

  <CalloutDescription>
    You need to keep your Proxy username and password safe. The Signaling SDK does not parse, store, or forward your username and password in any way. In addition, if you modify the Proxy settings during the app running process, the settings will take effect only after restarting the Signaling client.
  </CalloutDescription>
</CalloutContainer>

`RtmProxyConfig` contains the following properties:

|  Properties |      Type      | Required | Default | Description                                                  |
| :---------: | :------------: | :------: | :-----: | ------------------------------------------------------------ |
| `proxyType` | `RtmProxyType` | Optional |  `NONE` | Proxy protocol type. See [`RtmProxyType`](#enumvproxytyp-e). |
|   `server`  |     String     | Optional |    -    | Proxy server domain name or IP address.                      |
|    `port`   |       int      | Optional |    -    | Proxy listening port.                                        |
|  `account`  |     String     | Optional |    -    | Proxy login account.                                         |
|  `password` |     String     | Optional |    -    | Proxy login password.                                        |

##### RtmEncryptionConfig [#rtmencryptionconfig]

Use the `RtmEncryptionConfig` instance to set the properties required for the client-side encryption. After successfully setting encryption modes, encryption keys, and other related properties, the SDK automatically encrypts and decrypts all messages sent or all statuses set by the user on the client side.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

  <CalloutDescription>
    Once you set the encryption feature, all users must use the same encryption mode and key, otherwise users cannot communicate with each other.
  </CalloutDescription>
</CalloutContainer>

`RtmEncryptionConfig` contains the following properties:

|      Properties     |         Type        | Required | Default | Description                                                                                                           |
| :-----------------: | :-----------------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------- |
|   `encryptionMode`  | `RtmEncryptionMode` | Optional |  `NONE` | Encryption mode. See [`RtmEncryptionMode`](#enumvencryptionmod-e).                                                    |
|   `encryptionKey`   |        String       | Optional |    -    | User-defined encryption key, unlimited length. Agora recommends using a 32-byte key.                                  |
| `encryptionKdfSalt` |       byte\[]       | Optional |  `null` | User-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side. |

##### RtmPrivateConfig [#rtmprivateconfig]

Use the `RtmPrivateConfig` instance to set the properties required for the private deployment.

`RtmPrivateConfig` contains the following properties:

|     Properties     |               Type              | Required | Default | Description                                                                       |
| :----------------: | :-----------------------------: | :------: | :-----: | --------------------------------------------------------------------------------- |
|    `serviceType`   | `EnumSet&lt;RtmServiceType&gt;` | Optional |    -    | Service type. See [`RtmServiceType`](#enumvrtmservicetyp-e).                      |
| `accessPointHosts` |    `ArrayList&lt;String&gt;`    | Optional |    -    | An array of server addresses, where you can fill in domain names or IP addresses. |

#### Basic usage [#basic-usage]

```java
RtmProxyConfig proxyConfig = new RtmProxyConfig();
proxyConfig.setProxyType(RtmProxyType.HTTP);
proxyConfig.setServer("x.x.x.x"); // your proxy server ip
proxyConfig.setPort(8080); // your server port
proxyConfig.setAccount("user_name");
proxyConfig.setPassword("pass_word");

RtmLogConfig logConfig = new RtmLogConfig();
logConfig.setFilePath(""); // your log path
logConfig.setFileSize(10*1024); // log file size
logConfig.setLevel(RtmLogLevel.INFO);

byte[] salt = {1, 2, 3, 4, 5};
RtmEncryptionConfig encryptionConfig = new RtmEncryptionConfig();
encryptionConfig.setEncryptionMode(RtmEncryptionMode.AES_256_GCM);
encryptionConfig.setEncryptionKey("your_encryption_key");
encryptionConfig.setEncryptionSalt(salt);

RtmConfig rtmConfig = new RtmConfig.Builder("yourAppId", "Tony")
    .areaCode(EnumSet.of(RtmAreaCode.GLOB))
    .eventListener(eventListener)
    .protocolType(RtmProtocolType.TCP_UDP)
    .presenceTimeout(300)
    .heartbeatInterval(5)
    .useStringUserId(true)
    .proxyConfig(proxyConfig)
    .logConfig(logConfig)
    .encryptionConfig(encryptionConfig)
    .privateConfig(privateConfig)
    .build();
```

### create [#create]

#### Description [#description-1]

Call the `create` method to create and initialize the Signaling Client instance.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    <br />- You need to create and initialize a client instance before calling other Signaling APIs. <br />- To distinguish each user or device, you need to ensure that the `userId` parameter is globally unique and remains unchanged throughout the user or device's lifecycle.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-1]

You can create and initialize an instance as follows:

```java
RtmClient create(RtmConfig config) throws Exception;
```

| Parameters |     Type    | Required | Default | Description                                                                       |
| :--------: | :---------: | :------: | :-----: | --------------------------------------------------------------------------------- |
|  `config`  | `RtmConfig` | Required |    -    | Initialize the configuration parameters of the Signaling Client. See `RtmConfig`. |

#### Basic usage [#basic-usage-1]

```java
RtmConfig rtmConfig = new RtmConfig.Builder("yourAppId", "Tony")
    .eventListener(eventListener)
    .build();

try {
    rtmClient = RtmClient.create(rtmConfig);
} catch (Exception e) {
    e.printStackTrace();
}
```

#### Return Value [#return-value]

* If the method call succeeds, the SDK creates a Signaling client instance for subsequent calls to other Signaling APIs.
* If the method call fails, the SDK returns `Exception`.

### Event Listeners [#event-listeners]

#### DescriptionRtmEventListener [#descriptionrtmeventlistener]

Signaling event notifications.

Signaling has a total of 8 types of event notifications, as shown in the following table:

|          Event Type          | Description                                                                                                                                                                                                          |
| :--------------------------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|       `onMessageEvent`       | Receive message notifications from all subscribed Message Channels or topic message notifications subscribed to, in all Stream Channels you join. See [`MessageEvent`](#configmessageeven-t) .                       |
|       `onPresenceEvent`      | Receive presence event notifications in subscribed message channels and joined stream channels. See [`PresenceEvent`](#configpresenceeven-t)                                                                         |
|        `onTopicEvent`        | Receive all topic event notifications in joined stream channels. See [`TopicEvent`](#configtopiceven-t)                                                                                                              |
|       `onStorageEvent`       | Receive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. See [`StorageEvent`](#configstorageeven-t) |
|         `onLockEvent`        | Receive lock event notifications in subscribed message channels and joined stream channels. See [`LockEvent`](#configlockeven-t)                                                                                     |
|  `onConnectionStateChanged`  | (Deprecated) Receive event notifications when client connection status changes. For details, see [`RtmConnectionState`](#enumvconnectionstat-e) and [`RtmConnectionChangeReason`](#enumvconnectionreaso-n).          |
|      `onLinkStateEvent`      | Receive event notifications when client connection status changes. See [`LinkStateEvent`](#configlinkstateeven-t).                                                                                                   |
| `onTokenPrivilegeWillExpire` | Receive event notifications when the client tokens are about to expire.                                                                                                                                              |

#### Add event listeners [#add-event-listeners]

You can add an event listener object through the following ways:

* Add only an event listener object during initialization.
* Add one or more event listener objects at any point during the app's lifecycle by calling the `addEventListener` method.

##### Adding During Initialization [#adding-during-initialization]

When initializing the Signaling client instance using the `create` method, you can refer to the following example code to add an event listener object:

```java
 // Add the message event listener
 // Only override the events that you want to receive
rtmConfig.eventListener = new RtmEventListener {
    @Override
    public void onMessageEvent(MessageEvent event) {
 // Your message event handler
    }

    @Override
    public void onPresenceEvent(PresenceEvent event) {
 // Your presence event handler
    }

    @Override
    public void onTopicEvent(TopicEvent event) {
 // Your topic event handler
    }

    @Override
    public void onLockEvent(LockEvent event) {
 // Your lock event handler
    }

    @Override
    public void onStorageEvent(StorageEvent event) {
 // Your storage event handler
    }

    @Override
    public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
 // Your connection state change event handler
    }

    @Override
    public void onLinkStateEvent(LinkStateEvent event) {
 // Your link state change event handler
    }

    @Override
    public void onTokenPrivilegeWillExpire(String channelName) {
 // Your token privilege will expire event handler
    }
}
```

##### Adding at Any Time [#adding-at-any-time]

addDelegate
At any point during the app's lifecycle, if you need to add multiple event listener objects, you can call the `addEventListener` method multiple times.

```java
 // create event listener
 // only need to override the event which you want to receive
RtmEventListener listener = new RtmEventListener() {
    @Override
    public void onMessageEvent(MessageEvent event) {
    }

    @Override
    public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
    }
};

 // add listener
rtmClient.addEventListener(listener);
 // ...
```

removeEventListener
If you no longer need to listen to a specific event listener object, but still need to listen to other event listener objects, you can call the `removeEventListener` method to remove the specified event listener object.

```java
rtmClient.removeEventListener(listener);
```

##### MessageEvent [#messageevent]

`MessageEvent` contains the following properties:

|   Properties  |       Type       | Description                                                |
| :-----------: | :--------------: | ---------------------------------------------------------- |
| `channelType` | `RtmChannelType` | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
| `channelName` |      String      | Channel name.                                              |
|  `topicName`  |      String      | Topic name.                                                |
|   `message`   |   `RtmMessage`   | Message.                                                   |
|  `publisher`  |      String      | User ID of the message publisher.                          |
|  `customType` |      String      | A user-defined field. Only supports string type.           |
|  `timestamp`  |       long       | The timestamp when the event occurs.                       |

`RtmMessage` contains the following properties:

|   Properties  |       Type       | Description                                               |
| :-----------: | :--------------: | --------------------------------------------------------- |
|   `message`   |      String      | String type message.                                      |
|     `data`    |      byte\[]     | Byte type message.                                        |
| `messageType` | `RtmMessageType` | Message type. See [`RtmMessageType`](#enumvmessagetyp-e). |

##### PresenceEvent [#presenceevent]

`PresenceEvent` contains the following properties:

|   Properties  |             Type             | Description                                                                                                                                                                                   |
| :-----------: | :--------------------------: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `type`    |    `RtmPresenceEventType`    | Presence event type. See [`RtmPresenceEventType`](#enumvpresencetyp-e).                                                                                                                       |
| `channelType` |       `RtmChannelType`       | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                    |
| `channelName` |            String            | Channel name.                                                                                                                                                                                 |
|  `publisher`  |            String            | User ID of the message publisher.                                                                                                                                                             |
|  `stateItems` | `ArrayList&lt;StateItem&gt;` | Key-value pair that identifies the user's presence state.                                                                                                                                     |
|   `interval`  |        `IntervalInfo`        | In the Interval state, the aggregated incremental information of event notifications such as user joining, leaving, timeout, and status change in the previous period of the current channel. |
|   `snapshot`  |        `SnapshotInfo`        | When the user first joins the channel, the server pushes the snapshot data of all users in the current channel and their statuses to the user.                                                |
|  `timestamp`  |             long             | The timestamp when the event occurred.                                                                                                                                                        |

`IntervalInfo` contains the following properties:

| Properties        |             Type             | Description                                                                                                |
| :---------------- | :--------------------------: | :--------------------------------------------------------------------------------------------------------- |
| `joinUserList`    |   `ArrayList&lt;String&gt;`  | List of users who joined the channel in the previous cycle.                                                |
| `leaveUserList`   |   `ArrayList&lt;String&gt;`  | List of users who left the channel in the previous cycle.                                                  |
| `timeoutUserList` |   `ArrayList&lt;String&gt;`  | List of users who timed out joining the channel in the previous cycle.                                     |
| `userStateList`   | `ArrayList&lt;UserState&gt;` | List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs. |

`SnapshotInfo` contains the following properties:

| Properties      |             Type             | Description                                                                                                       |
| :-------------- | :--------------------------: | :---------------------------------------------------------------------------------------------------------------- |
| `userStateList` | `ArrayList&lt;UserState&gt;` | Snapshot information of the user when first joining the channel, including user ID and key-value pairs of status. |

`StateItem` data type contains the following properties:

| Properties |  Type  | Description                                                                                                                                                        |
| :--------- | :----: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`      | string | Key of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair. |
| `value`    | string | Value of the user state.                                                                                                                                           |

##### TopicEvent [#topicevent]

`TopicEvent` contains the following properties:

|   Properties  |             Type             | Description                                                    |
| :-----------: | :--------------------------: | -------------------------------------------------------------- |
|     `type`    |      `RtmTopicEventType`     | Topic event type. See [`RtmTopicEventType`](#enumvtopictyp-e). |
| `channelName` |            String            | Channel name.                                                  |
|  `publisher`  |            String            | User ID.                                                       |
|  `topicInfos` | `ArrayList&lt;TopicInfo&gt;` | Topic information.                                             |
|  `timestamp`  |             long             | The timestamp when the event occurs.                           |

`TopicInfo` data type contains the following properties:

|  Properties  |               Type               | Description              |
| :----------: | :------------------------------: | ------------------------ |
|  `topicName` |              String              | Topic name.              |
| `publishers` | `ArrayList&lt;PublisherInfo&gt;` | Message publisher array. |

`PublisherInfo` data type contains the following properties:

|     Properties    |  Type  | Description                        |
| :---------------: | :----: | ---------------------------------- |
| `publisherUserId` | String | User ID of the message publisher.  |
|  `publisherMeta`  | String | Metadata of the message publisher. |

##### StorageEvent [#storageevent]

`StorageEvent` contains the following properties:

|   Properties  |          Type         | Description                                                               |
| :-----------: | :-------------------: | ------------------------------------------------------------------------- |
| `channelType` |    `RtmChannelType`   | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                |
| `storageType` |    `RtmStorageType`   | Storage type. See [`RtmStorageType`](#enumvstoragetyp-e).                 |
|  `eventType`  | `RtmStorageEventType` | Storage event type. See [`RtmStorageEventType`](#enumvstorageeventtyp-e). |
|    `target`   |         String        | User ID or channel name.                                                  |
|     `data`    |       `Metadata`      | Metadata item. See [`Metadata`](#storagemetadat-a).                       |
|  `timestamp`  |          long         | The timestamp when the event occurs.                                      |

##### LockEvent [#lockevent]

`LockEvent` contains the following properties:

|    Properties    |              Type             | Description                                                 |
| :--------------: | :---------------------------: | ----------------------------------------------------------- |
|   `channelType`  |        `RtmChannelType`       | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).  |
|    `eventType`   |       `RtmLockEventType`      | Lock event type. See [`RtmLockEventType`](#enumvlocktyp-e). |
|   `channelName`  |             String            | Channel name.                                               |
| `lockDetailList` | `ArrayList&lt;LockDetail&gt;` | Details of lock.                                            |
|    `timestamp`   |              long             | The timestamp when the event occurs.                        |

The `LockDetail` data type contains the following properties:

| Properties  |  Type  | Description                                                                                                                                                                                                                                                                                                                            |
| :---------- | :----: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lockName`  | String | Lock name.                                                                                                                                                                                                                                                                                                                             |
| `lockOwner` | String | The ID of the user who has a lock.                                                                                                                                                                                                                                                                                                     |
| `ttl`       |   int  | The expiration time of the lock. The value is in seconds, ranging from \[10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the `onLockEvent` event receives the `RELEASED` event. |

##### LinkStateEvent [#linkstateevent]

SDK link state event.
`LinkStateEvent` data type contains the following properties:

|      Parameters      |               Type              | Description                                                                                                                                                                                                         |
| :------------------: | :-----------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|    `currentState`    |          `RtmLinkState`         | The current link state. See [`RtmLinkState`](#enumvlinkstat-e).                                                                                                                                                     |
|    `previousState`   |          `RtmLinkState`         | The previous link state. See [`RtmLinkState`](#enumvlinkstat-e).                                                                                                                                                    |
|     `serviceType`    |         `RtmServiceType`        | The network connection type. See [`RtmServiceType`](#enumvrtmservicetyp-e).                                                                                                                                         |
|      `operation`     |        `RtmLinkOperation`       | The operation that triggered the current state transition. See [`RtmLinkOperation`](#enumvlinkoperatio-n).                                                                                                          |
|     `reasonCode`     | `AgoraRtmLinkStateChangeReason` | The reason for this state transition. See [`AgoraRtmLinkStateChangeReason`](#enumvlinkstatereaso-n).                                                                                                                |
|       `reason`       |              String             | The reason for the current state transition. This parameter will be deprecated in the future, please use the `reasonCode` parameter instead.                                                                        |
|  `affectedChannels`  |    `ArrayList&lt;String&gt;`    | The channels affected by the current state transition.                                                                                                                                                              |
| `unrestoredChannels` |    `ArrayList&lt;String&gt;`    | The information about the channels to which subscription or joining has not been restored, including the channel name, channel type, and temporary state data in the channel. Typically, this information is empty. |
|      `isResumed`     |             boolean             | Within 2 minutes of the disconnection, whether the state transitions from `DISCONNECTED` to `CONNECTED`. `true` refers to the state has transitioned.                                                               |
|      `timestamp`     |               long              | The timestamp when the event occurs.                                                                                                                                                                                |

RtmClient
Signaling client instance

### login [#login]

#### Description [#description-2]

After creating and initializing the Signaling instance, you need to perform the `login` operation to log in to the Signaling service. After successful login, the client establishes a long connection with the Signaling server, and then the SDK allows the client to access Signaling resources.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    After the user successfully logs in to the Signaling service, the PCU of the application increases, which affects your billing data.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-2]

You can log in to the Signaling system as follows:

```java
void login(String token, ResultCallback<Void> resultCallback);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| :--------------: | :--------------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|      `token`     |         const char\*         | Required |    -    | The token used for logging in to Signaling.<br />- If you have enabled token authentication for your project, use either the [Signaling temporary token](https://agora-token-generator-demo.vercel.app/) or obtain a Signaling token generated by your [token server](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow).<br />- If your project does not enable token authentication, use an empty string or the App ID of a project that has Signaling services enabled. |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method.                                                                                                                                                                                                                                                                                                                                                                          |

After calling most of the APIs of the Signaling Java SDK, the SDK returns a `resultCallback` callback. Based on different invocation results, the SDK executes different methods in the `resultCallback` callback:

* If the method call succeeds, the SDK executes the `onSuccess` method.
* If the method call fails, the SDK executes the `onFailure `method and the `onFailure` method returns an `errorInfo` value of type `ErrorInfo`, which includes the error code, error reason, and API operation name as follows:

|  Properties |      Type      | Description                      |
| :---------: | :------------: | -------------------------------- |
| `errorCode` | `RtmErrorCode` | Error code for this operation.   |
|   `reason`  |     String     | Error reason for this operation. |
| `operation` |     String     | Operation type.                  |

To find out the cause of the error and get the corresponding solution, use the `errorCode` field with the [error codes table](#error-codes-table).

#### Basic usage [#basic-usage-2]

```java
rtmClient.login(token, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
    }
    @Override
    public void onFailure(ErrorInfo errorInfo) {
    }
});
```

### logout [#logout]

#### Description [#description-3]

When you no longer need to operate, you can log out of the system. This operation affects the PCU item in your billing data.

#### Method [#method-3]

You can log out as follows:

```java
void logout(ResultCallback<Void> resultCallback);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-3]

```java
rtmClient.logout(new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
    }
});
```

### releaseLock [#releaselock]

#### Description [#description-4]

Once you no longer need the Signaling service, it is best to destroy the `RtmClient` instance. Doing so protects you from the performance degradation caused by memory leaks, errors, and exceptions.

#### Method [#method-4]

You can destroy the `RtmClient` instance as follows:

```java
void release();
```

#### Basic usage [#basic-usage-4]

```java
rtmClient.release();
```

## User authentication [#user-authentication]

Authentication is the process of validating the identity of each user before they access a system. Agora uses digital tokens to authenticate users and their privileges.

Different types of channels in SIgnaling require different types of tokens:

* Message channels and User channels: When logging in to Signaling using the `login` method, you only need to pass the token that enables Signaling.
* Stream channels: In addition to the Signaling token, when joining a stream channel using the `joinTopic` method, you also need to pass the token that enables RTC service.

The token is valid for up to 24 hours. Agora recommends that you update the token before it expires. This section describes how to update the token.

For more information on generating and using tokens, see [Secure authentication with tokens](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow).

### RtmClient.renewToken [#rtmclientrenewtoken]

#### Description [#description-5]

Call the `RtmClient.renewToken` method to renew the Signaling token.

To ensure timely token updates, Agora recommends listening for the `onTokenPrivilegeWillExpire` callback. See [Event listeners](#event-listeners) for details. Once you successfully add the event listener, the SDK triggers the `onTokenPrivilegeWillExpire` callback 30 seconds before the Signaling token is set to expire to notify you about the impending token expiration.

Upon receiving this callback, you can obtain a new Signaling token from the token server and call the `renewToken` method to provide the SDK with the newly generated Signaling token.

#### Method [#method-5]

You can call the `RtmClient.renewToken` method as follows:

```java
void renewToken(String token, ResultCallback<Void> resultCallback)
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|      `token`     |            string            | Required |    -    | The newly generated Signaling token.                                                                                          |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-5]

```java
rtmClient.renewToken("your_token", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        // Handle success
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        // Handle failure
    }
});
```

### StreamChannel.renewToken [#streamchannelrenewtoken]

#### Description [#description-6]

Call the `StreamChannel.renewToken` method to renew the RTC token.

To ensure timely token updates, Agora recommends listening for the `onTokenPrivilegeWillExpire` callback. See [Event listeners](#event-listeners) for details. Once you successfully add the event listener, when the RTC token is about to expire within 30 seconds, the SDK triggers the `onTokenPrivilegeWillExpire` callback to notify the user about the impending token expiration.

Upon receiving this callback, you can generate a new RTC token on the server-side and call the `renewToken` method to provide the SDK with the newly generated RTC token.

#### Method [#method-6]

You can call the `StreamChannel.renewToken` method as follows:

```java
void renewToken(String token, ResultCallback<Void> resultCallback)
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                    |
| :--------------: | :--------------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------ |
|      `token`     |            string            | Required |    -    | The newly generated RTC token.                                                                                                 |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback: <br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-6]

```java
streamChannel.renewToken("your_token", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        // Handle success
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        // Handle failure
    }
});
```

## Channels [#channels]

Signaling provides a highly efficient channel management mechanism for data transmission. Any user who subscribes or joins a channel can receive messages and events transmitted within 100 milliseconds. Signaling allows clients to subscribe to hundreds or even thousands of channels. Most Signaling APIs perform actions such as sending, receiving, and encrypting based on channels.

Based on capabilities of Agora, Signaling channels are divided into two types to match different application use-cases:

* Message Channel: Follows the industry-standard Pub/Sub (publish/subscribe) mode. You can send and receive messages within the channel by subscribing to a channel, and do not need to create the channel in advance. There is no limit to the number of publishers and subscribers in a channel.

* User Channel: Point-to-point message sending and receiving based on the Pub/Sub (publish/subscribe) model. Users do not need to subscribe to the channel, they can directly specify the user ID to send messages. To receive messages, they only need to listen to `onMessageEvent` events.

* Stream Channel: Follows a concept similar to the observer pattern in the industry, where users need to create and join a channel before sending and receiving messages. You can create different topics in the channel, and messages are organized and managed through topics.

RtmClient
Signaling client instance

### subscribeTopic [#subscribetopic]

#### Description [#description-7]

Signaling provides event notification capabilities for messages and states. By listening for callbacks, you can receive messages and events within subscribed channels. For information on how to add and set event listeners, see [Event Listeners](#event-listeners).

By calling the `subscribeTopic` method, the client can subscribe to a message channel and start receiving messages and event notifications within the channel. After successfully calling this method, users who subscribe to the channel and enable the presence event listener can receive a `REMOTE_JOIN` type of the `onPresenceEvent` event. See [Event Listeners](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the message channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-7]

You can call the `subscribeTopic` method as follows:

```java
void subscribe(
    String channelName,
    SubscribeOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|     `options`    |      `SubscribeOptions`      | Required |    -    | Options for subscribing to a channel.                                                                                         |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

`SubscribeOptions` contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| :------------: | :-----: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|  `withMessage` | boolean | Optional |  `true` | Whether to subscribe to message event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `withPresence` | boolean | Optional |  `true` | Whether to subscribe to presence event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `withMetadata` | boolean | Optional | `false` | Whether to subscribe to storage event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
|   `withLock`   | boolean | Optional | `false` | Whether to subscribe to lock event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
|    `beQuiet`   | boolean | Optional | `false` | Whether to enable silent mode. If you set this parameter to `true`, the SDK behaves as follows:<br />- You still receive event notifications from other users.<br />- Event notifications related to your channel activity, such as subscribing or unsubscribing a channel, and actions related to setting, getting, or deleting temporary user states, are not broadcasted to other users.<br />- When calling the `getOnlineUsers` method, your information is not included.<br />- When calling the `getUserChannels` method, the channels that you subscribe to in silent mode are not included. |

#### Basic usage [#basic-usage-7]

```java
SubscribeOptions options = new SubscribeOptions();
options.setWithMessage(true);
options.setWithPresence(true);
options.setWithMetadata(false);
options.setWithLock(false);

rtmClient.subscribe("channel_name", options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "subscribe channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### unsubscribeTopic [#unsubscribetopic]

#### Description [#description-8]

If you no longer need to subscribe to a channel, you can call the `unsubscribeTopic` method to unsubscribe from the channel. After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the `REMOTE_LEAVE` type of the `onPresenceEvent` event notification. See [Event Listeners](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the message channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-8]

You can call the `unsubscribeTopic` method as follows:

```java
void unsubscribe(
    String channelName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-8]

```java
rtmClient.unsubscribe("channel_name", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "unsubscribe channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### create [#create-1]

#### Description [#description-9]

Before using a stream channel, you need to call the `create` method to create the `StreamChannel` instance. After successfully creating the instance, you can call its relevant methods to implement functions, such as joining the channel, leaving the channel, sending messages in a topic, and subscribing to messages in a topic.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-9]

You can call the `create` method as follows:

```java
StreamChannel createStreamChannel(String channelName) throws Exception;
```

|   Parameters  |  Type  | Required | Default | Description   |
| :-----------: | :----: | :------: | :-----: | ------------- |
| `channelName` | String | Required |    -    | Channel name. |

#### Basic usage [#basic-usage-9]

```java
try {
    StreamChannel streamChannel = rtmClient.createStreamChannel("channel_name");
} catch (Exception e) {
    log(ERROR, "create stream channel failed: " + e.toString());
}
```

#### Return Value [#return-value-1]

The `StreamChannel` instance.

StreamChannel
Stream channel instance

### joinTopic [#jointopic]

#### Description [#description-10]

After successfully creating a stream channel, you can call the `joinTopic` method to join the stream channel. Once you join the channel, you can implement channel-related functions. At this point, users who subscribe to the channel and add event listeners can receive the following event notifications:

* For the local user:
  * The `SNAPSHOT` type of the `onPresenceEvent` event.
  * The `SNAPSHOT` type of the `onTopicEvent` event.
* For remote users: The `REMOTE_JOIN` type of the `onPresenceEvent` event.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-10]

You can call the `joinTopic` method as follows:

```java
void join(
    JoinChannelOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `options`    |     `JoinChannelOptions`     | Required |    -    | Options for joining a channel.                                                                                                |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `JoinChannelOptions` data type contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :------------: | :-----: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|     `token`    |  String | Required |    -    | An RTC token for joining a stream channel.<br />- If you have enabled token authentication for your project, generate a [temporary RTC token](/video-calling/get-started/manage-agora-account#generate-temporary-tokens) or obtain an RTC token generated by your [token server](/video-calling/token-authentication/deploy-token-server).<br />- If you have not enabled token authentication for your project, use an empty string or the App ID of your project that has RTC and Signaling services enabled.                                                                            |
| `withPresence` | boolean | Optional |  `true` | Whether to subscribe to presence event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `withMetadata` | boolean | Optional | `false` | Whether to subscribe to storage event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|   `withLock`   | boolean | Optional | `false` | Whether to subscribe to lock event notifications in the channel.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
|    `beQuiet`   | boolean | Optional | `false` | Whether to enable silent mode. If you set this parameter to `true`, the SDK behaves as follows:<br />- You still receive event notifications from other users.<br />- Event notifications related to your channel activity, such as joining or leaving a channel, and actions related to setting, getting, or deleting temporary user states, are not broadcasted to other users.<br />- When calling the `getOnlineUsers` method, your information is not included.<br />- When calling the `getUserChannels` method, the channels that you subscribe to in silent mode are not included. |

#### Basic usage [#basic-usage-10]

```java
JoinChannelOptions options = new JoinChannelOptions();
options.setToken("yourToken")
options.setWithPresence(true);
options.setWithMetadata(false);
options.setWithLock(false);

streamChannel.join(options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "join stream channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### leaveTopic [#leavetopic]

#### Description [#description-11]

If you no longer need to stay in a channel, you can call the `leaveTopic` method to leave the channel. After leaving the channel, you can no longer receive any messages, states, or event notifications from this channel. At the same time, you can no loger be the topic publisher or subscriber of all topics. If you want to restore your previous publisher role and subscribing relationship, you need to call `joinTopic`, `joinTopic` and `subscribeTopic` methods in order.

After successfully leaving the channel, remote users in the channel can receive the `REMOTE_LEAVE` type of the `onPresenceEvent` event notification. For details, see [Event Listeners](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-11]

You can call the `leaveTopic` method as follows:

```java
void leave(ResultCallback<Void> resultCallback);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-11]

```java
streamChannel.leave(new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "leave stream channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### releaseLock [#releaselock-1]

#### Description [#description-12]

If you no longer need a channel, you can call the `releaseLock` method to destroy the corresponding stream channel instance and release resources. Calling the `releaseLock` method does not destroy the stream channel, and it can be re-joined later by calling `create` and `joinTopic` again.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel. If you don't call `leaveTopic` to leave the channel before directly calling `releaseLock` to destroy the stream channel instance, the SDK automatically calls the `leaveTopic` and triggers the corresponding event.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-12]

You can call the `releaseLock` method as follows:

```java
RtmErrorCode release();
```

#### Basic usage [#basic-usage-12]

```java
RtmErrorCode errorCode = streamChannel.release();
```

#### Return Value [#return-value-2]

This operation returns the `RtmErrorCode` data type.

## Topics [#topics]

Topic is a data stream management mechanism in stream channels. Users can use topics to subscribe to and distribute data streams, as well as notify events in data streams in stream channels.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    Topics only exist in stream channels. Therefore, before using relevant features, you need to create the `StreamChannel` instance.
  </CalloutDescription>
</CalloutContainer>

StreamChannel
Stream channel instance

### joinTopic [#jointopic-1]

#### Description [#description-13]

The purpose of joining a topic is to register as one of the message publishers for the topic, so that the user can send messages in the topic. This operation does not affect whether or not the user becomes a subscriber to the topic.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    * Currently, Signaling supports a single client joining up to 8 topics in the same stream channel at a time.
    * Before joining a topic, a user needs to create the `StreamChannel` instance and call the `joinTopic` method to join the channel.
  </CalloutDescription>
</CalloutContainer>

After successfully joining a topic, users who subscribe to that topic and add event listeners can receive the `REMOTE_JOIN` type of the `onTopicEvent` event notification. For details, see [Event Listeners](#event-listeners).

#### Method [#method-13]

You can call the `joinTopic` method as follows:

```java
void StreamChannel.joinTopic(
    String topicName,
    JoinTopicOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|    `topicName`   |            String            | Required |    -    | Topic name.                                                                                                                   |
|     `options`    |      `JoinTopicOptions`      | Required |    -    | Options for joining a topic.                                                                                                  |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

|    Properties   |         Type         | Required | Default     | Description                                                                                                                               |
| :-------------: | :------------------: | :------: | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|   `messageQos`  |    `RtmMessageQos`   | Optional | `UNORDERED` | Whether the data transmitted in the topic is ordered. See [`RtmMessageQos`](#enumvmessageqo-s).                                           |
|    `priority`   | `RtmMessagePriority` | Optional | `NORMAL`    | The priority of data transmission in the topic compared to other topics in the same channel. See [`RtmMessagePriority`](#enumvpriorit-y). |
|   `topicMeta`   |        String        | Optional | -           | Adds additional metadata when joining the topic.                                                                                          |
| `syncWithMedia` |        boolean       | Optional | `false`     | Whether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel.   |

#### Basic usage [#basic-usage-13]

```java
JoinTopicOptions options = new JoinTopicOptions();
options.messageQos = RtmMessageQos.ORDERED;
streamChannel.joinTopic("topic_name", options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "join topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### publishTopicMessage [#publishtopicmessage]

#### Description [#description-14]

Use the `publishTopicMessage` method to send messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the `publishTopicMessage` method, users need to join the stream channel, and then register as a message publisher for that topic by calling the `joinTopic` method.

The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see [Setup](#setup).

#### Method [#method-14]

You can call the `publishTopicMessage`\[1/2] and `publishTopicMessage`\[2/2] method as follows:

```java
// publishTopicMessage [1/2]
void StreamChannel.publishTopicMessage(
    String topicName,
    String message,
    TopicMessageOptions options,
    ResultCallback<Void> resultCallback
);
```

```java
// publishTopicMessage [2/2]
void StreamChannel.publishTopicMessage(
    String topicName,
    byte[] message,
    TopicMessageOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|    `topicName`   |            String            | Required |    -    | Topic name.                                                                                                                   |
|     `message`    |        String\byte\[]        | Required |    -    | Message payload.                                                                                                              |
|     `options`    |     `TopicMessageOptions`    | Required |    -    | Message options.                                                                                                              |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `TopicMessageOptions` data type contains the following properties:

|  Properties  |  Type  | Required | Default | Description                                                                                                                                                                                                                 |
| :----------: | :----: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `sendTs`   |  long  | Optional |   `0`   | The timestamp when the SDK sends a message. This parameter is only valid when you set `syncWithMedia = true` in the `joinTopic` method. The SDK synchronizes data with RTC audio and video streams based on this timestamp. |
| `customType` | String | Optional |    -    | A user-defined field. Only supports string type.                                                                                                                                                                            |

#### Basic usage [#basic-usage-14]

Example 1: Send string messages to a specified channel.

```java
String message = "message";
TopicMessageOptions options = new TopicMessageOptions();
options.customType = "PlainTxT";
streamChannel.publishTopicMessage("topic_name", message, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "publish topic message success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 2: Send byte messages to a specified channel.

```java
byte[] message = new byte[] {1, 2, 3, 4};
TopicMessageOptions options = new TopicMessageOptions();
options.customType = "ByteArray";
streamChannel.publishTopicMessage("topic_name", message, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "publish topic message success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### leaveTopic [#leavetopic-1]

#### Description [#description-15]

When you no longer need to publish messages to a topic, to release resources, you can call the `leaveTopic` method to unregister as a message publisher for that topic. This method does not affect whether or not you subscribe to that topic or any other operations performed by other users on that topic.

After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the `REMOTE_LEAVE` type of the `onTopicEvent` event notification. See [Event Listeners](#event-listeners).

#### Method [#method-15]

You can call the `leaveTopic` method as follows:

```java
void StreamChannel.leaveTopic(String topicName, ResultCallback<Void> resultCallback);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|    `topicName`   |            String            | Required |    -    | Topic name.                                                                                                                   |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-15]

```java
streamChannel.leaveTopic("topic_name", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "leave topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### subscribeTopic [#subscribetopic-1]

#### Description [#description-16]

After joining the channel, you can call the `subscribeTopic` method to subscribe to the message publisher of the topic in the channel.

`subscribeTopic` is an incremental method. For example, if you call this method for the first time with a subscribing list of `[UserA, UserB]`, and then call it again with a subscribing list of `[UserB, UserC]`, the final successful subscribing result is `[UserA, UserB, UserC]`.

A user can subscribe to a maximum of 50 topics in each channel, and a maximum of 64 message publishers in each topic. See [API usage restrictions](./reference/limitations).

#### Method [#method-16]

You can call the `subscribeTopic` method as follows:

```java
void StreamChannel.subscribeTopic(
    String topicName,
    TopicOptions options,
    ResultCallback<SubscribeTopicResult> resultCallback
);
```

|    Parameters    |                     Type                     | Required | Default | Description                                                                                                                                                              |
| :--------------: | :------------------------------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|    `topicName`   |                    String                    | Required |    -    | Topic name.                                                                                                                                                              |
|     `options`    |                `TopicOptions`                | Required |    -    | Options for subscribing to a topic.                                                                                                                                      |
| `resultCallback` | `ResultCallback&lt;SubscribeTopicResult&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the `SubscribeTopicResult` data.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

| Properties |            Type           | Required | Default | Description                                                                                                                                                       |
| :--------: | :-----------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `users`  | `ArrayList&lt;String&gt;` | Optional |    -    | A list of `UserId` of message publishers that you want to subscribe to. If you do not set this property, you can randomly subscribe to up to 64 users by default. |

`SubscribeTopicResult` parameter contains the following properties:

| Properties     |            Type           | Description                                         |
| :------------- | :-----------------------: | :-------------------------------------------------- |
| `succeedUsers` | `ArrayList&lt;String&gt;` | A list of successfully subscribed users.            |
| `failedUsers`  | `ArrayList&lt;String&gt;` | A list of users that the SDK fails to subscribe to. |

#### Basic usage [#basic-usage-16]

Example 1: Subscribe to the specified message publisher in the topic.

```java
TopicOptions options = new TopicOptions();
options.users = new ArrayList<>(Arrays.asList("UserA","UserB","UserC"));
streamChannel.subscribeTopic("topic_name", options, new ResultCallback<SubscribeTopicResult>() {
    @Override
    public void onSuccess(SubscribeTopicResult responseInfo) {
        log(CALLBACK, "subscribe topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 2: Randomly subscribe to 64 message publishers in the topic.

```java
TopicOptions options = new TopicOptions();
mStreamChannel.subscribeTopic("topic_name", options, new ResultCallback<SubscribeTopicResult>() {
    @Override
    public void onSuccess(SubscribeTopicResult responseInfo) {
        log(CALLBACK, "subscribe topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### unsubscribeTopic [#unsubscribetopic-1]

#### Description [#description-17]

If you are no longer interested in a specified topic, or no longer need to subscribe to one or more message publishers in the topic, you can call the `unsubscribeTopic` method to unsubscribe from the topic or the specified message publishers in the topic.

#### Method [#method-17]

You can call the `unsubscribeTopic` method as follows:

```java
void StreamChannel.unsubscribeTopic(
    String topicName,
    TopicOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|    `topicName`   |            String            | Required |    -    | Topic name.                                                                                                                   |
|     `options`    |        `TopicOptions`        | Required |    -    | Options for unsubscribe from a topic.                                                                                         |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

| Properties |            Type           | Required | Default | Description                                                                                                                                                               |
| :--------: | :-----------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `users`  | `ArrayList&lt;String&gt;` | Optional |    -    | A list of `UserId` of message publishers that you want to unsubscribe from. If you do not set this property, you can randomly unsubscribe from up to 64 users by default. |

#### Basic usage [#basic-usage-17]

Example 1: Unsubscribe the specified message publisher in the topic

```java
TopicOptions options = new TopicOptions();
options.users = new ArrayList<>(Arrays.asList("Tony","Bo"));

streamChannel.unsubscribeTopic("topicName", options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "unsubscribe topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 2: Randomly unsubscribe 64 message publishers from the topic.

```java
TopicOptions options = new TopicOptions();
streamChannel.unsubscribeTopic("topicName", options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "unsubscribe topic success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

## Messages [#messages]

Sending and receiving messages is the most basic function of the Signaling service. Any message sent by the Signaling server can be delivered to any online subscribing user within 100 ms. Depending on your business requirements, you can send messages to one user only or broadcast messages to multiple users.

Signaling offers the following channel types:

* Message Channel: The real-time channel. Messages are transmitted through the channel, and the channel is highly scalable. Local users can call the `publishTopicMessage` method, set the `channelType` parameter to `MESSAGE`, and set the `channelName` parameter to the channel name to send messages in the channel. The remote users can call the `subscribeTopic` method to subscribe to the channel and receive messages.
* User Channel: The real-time channel. Messages are transmitted to the specified user. Local users can call the `publishTopicMessage` method, set the `channelType` parameter to `USER`, and set the `channelName` parameter to the user ID to send messages to the specified user. The specified remote users receive messages through the `onMessageEvent` event notifications.
* Stream Channel: The streaming transmission channel. Messages are transmitted through the topic. Users need to join a channel first, and then join a topic. Local users can call the `publishTopicMessage` method to send messages in the topic, and remote users can call the `subscribeTopic` method to subscribe to the topic and receive messages.

This section shows you how to send and receive messages in a message channel or a user channel.

RtmClient
Signaling client instance

### publishTopicMessage [#publishtopicmessage-1]

#### Description [#description-18]

You can directly call the `publishTopicMessage` method to send messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    The following practices can effectively improve the reliability of message transmission:<br />- The message payload should be within 32 KB; otherwise, the sending will fail. <br />- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.
  </CalloutDescription>
</CalloutContainer>

After successfully calling this method, the SDK triggers a `onMessageEvent` event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see [Event Listeners](#event-listeners).

#### Method [#method-18]

You can call the `publishTopicMessage` method as follows:

```java
 // publish [1/2]
void publish(
        String channelName,
        String message,
        PublishOptions options,
        ResultCallback<Void> resultCallback
        );
```

```java
 // publish [2/2]
void publish(
        String channelName,
        byte[] message,
        PublishOptions options,
        ResultCallback<Void> resultCallback
        );
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Fill in a channel name to send messages to a specified channel, or fill in a user ID to send messages to a specified user.    |
|     `message`    |        String\byte\[]        | Required |    -    | Message payload.                                                                                                              |
|     `options`    |     `TopicMessageOptions`    | Required |    -    | Message options.                                                                                                              |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

|   Properties  |       Type       | Required | Default | Description                                                |
| :-----------: | :--------------: | :------: | :-----: | ---------------------------------------------------------- |
| `channelType` | `RtmChannelType` | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |
|  `customType` |      String      | Optional |    -    | A user-defined field. Only supports string type.           |

#### Basic usage [#basic-usage-18]

Example 1: Send string messages to a specified channel.

```java
String message = "Hello world";
PublishOptions options = new PublishOptions();
options.customType = 'PlainText';
rtmClient.publish("my_channel", message, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "send message to channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 2: Send byte messages to a specified channel.

```java
byte[] message = new byte[] {1, 2, 3, 4};
PublishOptions options = new PublishOptions();
options.customType = 'ByteArray';
rtmClient.publish("my_channel", message, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "send message to channel success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 3: Send string messages to a specified user.

```java
PublishOptions options = new PublishOptions();
options.setChannelType(RtmChannelType.USER);
options.setCustomType("PlainText");
rtmClient.publish("Tony", "Hello world", options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "send message success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

Example 4: Send byte messages to a specified user.

```java
byte[] message = new byte[] {1, 2, 3, 4};
PublishOptions options = new PublishOptions();
options.setChannelType(RtmChannelType.USER);
options.setCustomType("ByteArray");
rtmClient.publish("Tony", message, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "send message success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### Receive [#receive]

Signaling provides event notifications for messages, states, and event changes. By listening for callbacks, you can receive messages and events within subscribed channels. As an example, the code snippet below shows how to receive messages from the user channel.

* Adding during initialization:

```java
  rtmConfig.eventListener = new RtmEventListener {
      @Override
      public void onMessageEvent(MessageEvent event) {
          // User channel messages
          if (event.getChannelType() == RtmChannelType.USER) {
            log(CALLBACK, "receive message from " + event.getPublisherId() + ", message: " + event.getMessage().toString());
          }
      }
      // ...
  }
```

* Adding at any time:

```java
    RtmEventListener listener = new RtmEventListener() {
        @Override
        public void onMessageEvent(MessageEvent event) {
            // User channel messages
            if (event.getChannelType() == RtmChannelType.USER) {
                log(CALLBACK, "receive message from " + event.getPublisherId() + ", message: " + event.getMessage().toString());
            }
        }

        @Override
        public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
        }
    };

    rtmClient.addEventListener(listener);
    // ...

```

For information on how to add and set event listeners, see [Event Listeners](#event-listeners).

## Presence [#presence]

The presence feature provides the ability to monitor user online, offline, and user historical state change. With the Presence feature, you can get real-time access to the following information:

* Real-time event notification when a user joins or leaves a specified channel.
* Real-time event notification when the custom temporary user state changes.
* Query which channels a specified user has joined or subscribed to.
* Query which users have joined a specified channel and their temporary user state data.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    **Presence** applies to both message channels and stream channels.
  </CalloutDescription>
</CalloutContainer>

RtmPresence
Presence instance

### getOnlineUsers [#getonlineusers]

#### Description [#description-19]

By calling the `getOnlineUsers` method, you can query real-time information about the number of online users, the list of online users, and the temporary state of online users in a specified channel.

#### Method [#method-19]

You can call the `getOnlineUsers` method as follows:

```java
void getOnlineUsers(
    String channelName,
    RtmChannelType channelType,
    GetOnlineUsersOptions options,
    ResultCallback<GetOnlineUsersResult> resultCallback
);
```

|    Parameters    |                     Type                     | Required | Default | Description                                                                                                                                                                                                 |
| :--------------: | :------------------------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |                    string                    | Required |    -    | Channel name.                                                                                                                                                                                               |
|   `channelType`  |               `RtmChannelType`               | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                                  |
|     `options`    |            `GetOnlineUsersOptions`           | Required |    -    | Query options.                                                                                                                                                                                              |
| `resultCallback` | `ResultCallback&lt;GetOnlineUsersResult&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the `GetOnlineUsersResult` query result.<br />- Failure: Executes the `onFailure` method and return an error result. |

The `options` parameter contains the following properties:

|    Properties   |   Type  | Required | Default | Description                                                                                                                                                                          |
| :-------------: | :-----: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `includeUserId` | boolean | Optional |  `true` | Whether the returned result includes the user ID of online members.                                                                                                                  |
|  `includeState` | boolean | Optional | `false` | Whether the returned result includes temporary state data of online users.                                                                                                           |
|      `page`     |  String | Optional |    -    | Page number of the returned result. If you do not provide this property, the SDK returns the first page by default. You can check whether there is next page in the returned result. |

`GetOnlineUsersResult` data contains the following properties:

|    Properties    |             Type             | Description                                                                                                                                                                                                                                                                                                 |
| :--------------: | :--------------------------: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|    `nextPage`    |            String            | Page number of the next page. Confirm whether there is a next page:<br />- A null value indicates that next page does not exist.<br />- A non-null value indicates that there is a next page. You can fill this value in the `page` property of the `getOnlineUsers` method to query the next page results. |
|  `userStateList` | `ArrayList&lt;UserState&gt;` | List of online users and their temporary state information in a specified channel.                                                                                                                                                                                                                          |
| `totalOccupancy` |             long             | The list length of `UserStateList`. When you set both `includeUserId `and `includeState `properties in the `getOnlineUsers` method to `false`, this value represents the total number of current online users in the channel.                                                                               |

The `UserState` data type contains the following properties:

| Properties |               Type              | Description           |
| :--------- | :-----------------------------: | --------------------- |
| `userId`   |              String             | User ID.              |
| `states`   | `HashMap&lt;String, String&gt;` | Temporary user state. |

#### Basic usage [#basic-usage-19]

```java
GetOnlineUsersOptions options = new GetOnlineUsersOptions();
options.setIncludeUserId(true);
options.setIncludeState(true);
options.setPage("yourBookMark");

rtmClient.getPresence().getOnlineUsers("channelName", RtmChannelType.MESSAGE, options, new ResultCallback<GetOnlineUsersResult>() {
    @Override
    public void onSuccess(GetOnlineUsersResult result) {
        log(CALLBACK, "getOnlineUsers success");
        for (UserState state : result.getUserStateList()) {
            log(INFO, "user id: " + state.getUserId());
            state.getStates().forEach((key, value) -> {
                log(INFO, "key: " + key + ", value: " + value);
            });
        }
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### getUserChannels [#getuserchannels]

#### Description [#description-20]

In use-cases such as statistic analytics and debugging, you may need to know all the channels that a specified user has subscribed to or joined. Call the `getUserChannels` method to get the list of channels where the specified user is in real time.

#### Method [#method-20]

You can call the `getUserChannels` method as follows:

```java
void getUserChannels(
    String userId,
    ResultCallback<ArrayList<ChannelInfo>> resultCallback
);
```

|    Parameters    |                         Type                         | Required | Default | Description                                                                                                                                                                              |
| :--------------: | :--------------------------------------------------: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |                        string                        | Required |    -    | User ID.                                                                                                                                                                                 |
| `resultCallback` | `ResultCallback&lt;ArrayList&lt;ChannelInfo&gt;&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the `ArrayList&lt;ChannelInfo&gt;` query result.<br />- Failure: Executes the `onFailure` method. |

`ChannelInfo` data type contains the following properties:

|   Properties  |       Type       | Description                                                |
| :-----------: | :--------------: | ---------------------------------------------------------- |
| `channelName` |      String      | Channel name.                                              |
| `channelType` | `RtmChannelType` | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e). |

#### Basic usage [#basic-usage-20]

```java
rtmClient.getPresence().getUserChannels("Tony", new ResultCallback<ArrayList<ChannelInfo>>() {
    @Override
    public void onSuccess(ArrayList<ChannelInfo> channels) {
        log(CALLBACK, "get " + queryUserId + " getUserChannels success");
        for (ChannelInfo channel : channels) {
            log(INFO, channel.toString());
        }
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### setState [#setstate]

#### Description [#description-21]

To meet different requirements in different business use-cases for setting user states, Signaling provides the `setState` method to customize the temporary user state. Users can add custom states such as scores, game state, location, mood, and hosting state for themselves.

After successful setup, as long as the user keeps subscribing to the channel and stays online, the custom states can persist in the channel. `setState` method sets the temporary user state, and the state disappears when the user leaves the channel or disconnects from Signaling. If you need to restore user states when rejoining a channel or reconnecting, you need to cache the data locally in real time. If you want to permanently save user states, Agora recommends you use the `setUserMetadata` method of the storage function instead.

If a user modifies the temporary user state, Signaling triggers the `REMOTE_STATE_CHANGED` type of the `onPresenceEvent` event in real time. You can receive the event by subscribing to the channel and configuring the corresponding property.

#### Method [#method-21]

You can call the `setState` method as follows:

```java
void setState(
    String channelName,
    RtmChannelType channelType,
    Map<String, String> items,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name                                                                                                                  |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|      `items`     |  `Map&lt;String, String&gt;` | Required |    -    | User state.                                                                                                                   |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

`StateItem` data type contains the following properties:

| Properties |  Type  | Description                                                                                                                                                        |
| :--------- | :----: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`      | string | Key of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair. |
| `value`    | string | Value of the user state.                                                                                                                                           |

#### Basic usage [#basic-usage-21]

```java
HashMap<String, String> stateItems = new HashMap<String, String>();
stateItems.put("mood", "pumped");

rtmClient.getPresence().setState("channelName", RtmChannelType.MESSAGE, stateItems, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "set state success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### getState [#getstate]

#### Description [#description-22]

To get the temporary user state of a specified user in the channel, you can use the `getState` method.

#### Method [#method-22]

You can call the `getState` method as follows:

```java
void getState(
    String channelName,
    RtmChannelType channelType,
    String userId,
    ResultCallback<UserState> resultCallback
);
```

|    Parameters    |                Type               | Required | Default | Description                                                                                                                                                           |
| :--------------: | :-------------------------------: | :------: | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |               String              | Required |    -    | Channel name.                                                                                                                                                         |
|   `channelType`  |          `RtmChannelType`         | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                            |
|     `userId`     |               String              | Required |    -    | User ID.                                                                                                                                                              |
| `resultCallback` | `ResultCallback&lt;UserState&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the `UserState` query result.<br />- Failure: Executes the `onFailure` method. |

The `UserState` data type contains the following properties:

| Properties |               Type              | Description           |
| :--------- | :-----------------------------: | --------------------- |
| `userId`   |              String             | User ID.              |
| `states`   | `HashMap&lt;String, String&gt;` | Temporary user state. |

#### Basic usage [#basic-usage-22]

```java
rtmClient.getPresence().getState("channelName", RtmChannelType.MESSAGE, "Tony", new ResultCallback<UserState>() {
    @Override
    public void onSuccess(UserState state) {
        log(CALLBACK, "get users(" + state.getUserId() + ") state success");
        state.getStates().forEach((key, value) -> {
            log(INFO, "key: " + key + ", value: " + value);
        });
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### removeState [#removestate]

#### Description [#description-23]

When a temporary user state is no longer needed, you can call the `removeState` method to remove one or more of your temporary states. When the user state is removed, the user who has subscribed to the channel and enabled the presence event listener receives the `REMOTE_STATE_CHANGED` type of `onPresenceEvent` event notification. See [Event Listeners](#event-listeners).

#### Method [#method-23]

You can call the `removeState` method as follows:

```java
void removeState(
    String channelName,
    RtmChannelType channelType,
    ArrayList<String> keys,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name                                                                                                                  |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|      `keys`      |   `ArrayList&lt;String&gt;`  | Required |    -    | List of keys to be deleted. If you do not provide this property, the SDK removes all states.                                  |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-23]

```java
ArrayList<String> keys = new ArrayList<>(Arrays.asList("A", "B", "C"));
rtmClient.getPresence().removeState("channelName", RtmChannelType.MESSAGE, keys, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "remove state success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

## Storage [#storage]

The storage feature provides a database mechanism that allows developers to dynamically set, store, update, and delete data such as channel metadata and user metadata.

RtmStorage
Storage instance

### setChannelMetadata [#setchannelmetadata]

#### Description [#description-24]

The `setChannelMetadata` method sets metadata for a message channel or a stream channel. A channel can only have one set of metadata, but each set of metadata can have one or more metadata items. If you call this method multiple times, the SDK retrieves the `key` of the metadata items and applies settings according to the following rules:

* If you set metadata with different `key` values, the SDK adds each set of metadata in sequence according to the order of the method calls.
* If you set metadata with the same `key`, the `value` of the last setting overwrites the previous one.

After successfully setting channel metadata, users who subscribe to the channel and enable event listeners receive the `CHANNEL` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

Channel metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of these according to your actual business use-case:

* Enable version number verification for the entire set of channel metadata by setting the `majorRevision` property in the `Metadata` data type.
* Enable version number verification for a single metadata item by setting the `revision` property in the `MetadataItem` class.

When setting channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

* The default value of the revision property is `-1`, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the latest value overwrites the previous one. If the channel metadata or metadata item does not exist, the SDK creates it.
* If the revision property is a positive integer, this method call performs CAS verification. If the channel metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns an error code.

#### Method [#method-24]

You can call the `setChannelMetadata` method as follows:

```java
void setChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    Metadata data,
    MetadataOptions options,
    String lockName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                     |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata`](#storagemetadat-a).                                                                           |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
|    `lockName`    |            String            | Required |    -    | Lock name. If set, only users who call the `acquireLock` method to acquire the lock can perform operations.                   |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `MetadataOptions` data type contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-24]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add metadata item
ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
items.add(new MetadataItem("Apple", "100", 174298200));
items.add(new MetadataItem("Banana", "200", 174298100));
metadata.setItems(items);
 // Record who and when set the metadata
MetadataOptions options = new MetadataOptions();
options.setRecordTs(true);
options.setRecordUserId(true);

rtmClient.getStorage().setChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, options, "lockName", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "set channel metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### getChannelMetadata [#getchannelmetadata]

#### Description [#description-25]

The `getChannelMetadata` method gets the metadata of the specified channel.

#### Method [#method-25]

You can call the `getChannelMetadata` method as follows:

```java
void getChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    ResultCallback<Metadata> resultCallback
);
```

|    Parameters    |               Type               | Required | Default | Description                                                                                                                                                                                |
| :--------------: | :------------------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|   `channelName`  |              String              | Required |    -    | Channel name.                                                                                                                                                                              |
|   `channelType`  |         `RtmChannelType`         | Required |    -    | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                  |
| `resultCallback` | `ResultCallback&lt;Metadata&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the [`Metadata `](#storagemetadat-a) query result.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-25]

```java
rtmClient.getStorage().getChannelMetadata("channelName", RtmChannelType.MESSAGE, new ResultCallback<Metadata>() {
    @Override
    public void onSuccess(Metadata data) {
        log(CALLBACK, "get channel metadata success");
        log(INFO, "metadata major revision: " + data.getMajorRevision());
        for (MetadataItem item : data.getItems()) {
            log(INFO, item.toString);
        }
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### removeChannelMetadata [#removechannelmetadata]

#### Description [#description-26]

The `removeChannelMetadata` method removes channel metadata or metadata items.

When removing channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

* The default value of the revision property is `-1`, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the SDK removes it. If the channel metadata or metadata item does not exist, the SDK returns an error code.
* If the revision property is a positive integer, this method call performs CAS verification. If the channel metadata or metadata item already exists, the SDK removes the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns an error code.

After successfully removing channel metadata or metadata items, users who subscribe to the channel and enable event listeners receive the `CHANNEL` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

#### Method [#method-26]

You can call the `removeChannelMetadata` method as follows:

```java
void removeChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    Metadata data,
    MetadataOptions options,
    String lockName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                     |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata `](#storagemetadat-a).                                                                          |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
|    `lockName`    |            String            | Required |    -    | Lock name. If set, only users who call the `acquireLock` method to acquire the lock can perform operations.                   |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `MetadataOptions` data type contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-26]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add a metadata item
MetadataItem item = new MetadataItem();
item.setKey("Apple");
item.setRevision(174298200);
metadata.getItems().add(item);
 //Record who and when set the metadata
MetadataOptions options = new MetadataOptions();

rtmClient.getStorage().removeChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, options, "", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "remove channel metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### updateChannelMetadata [#updatechannelmetadata]

#### Description [#description-27]

The `updateChannelMetadata` method updates existing channel metadata. Each time you call this method, you can update one channel metadata or a channel metadata item.

After successfully updating channel metadata, users who subscribe to the channel and enable event listeners receive the `CHANNEL` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-27]

You can call the `updateChannelMetadata` method as follows:

```java
void updateChannelMetadata(
    String channelName,
    RtmChannelType channelType,
    Metadata data,
    MetadataOptions options,
    String lockName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel type. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                     |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata `](#storagemetadat-a).                                                                          |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
|    `lockName`    |            String            | Required |    -    | Lock name. If set, only users who call the `acquireLock` method to acquire the lock can perform operations.                   |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-27]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add metadata item
ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
items.add(new MetadataItem("Apple", "120", 174298200));
items.add(new MetadataItem("Banana", "220", 174298100));
metadata.setItems(items);

rtmClient.getStorage().updateChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, new MetadataOptions(true, true), "lockName", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "update channel metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### setUserMetadata [#setusermetadata]

#### Description [#description-28]

The `setUserMetadata` method sets metadata for a user. If you call this method multiple times, the SDK retrieves the `key` of the metadata items and applies settings according to the following rules:

* If you set metadata with different `key`, the SDK adds each set of metadata in sequence according to the order of the method calls.
* If you set metadata with the same `key`, the `value` of the last setting overwrites the previous one.

After successfully setting user metadata, users who subscribe to the user and enable event listeners receive the `USER` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

User metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:

* Enable version number verification for the entire set of channel metadata by setting the `majorRevision` property in the `Metadata` data type.
* Enable version number verification for a single metadata item by setting the `revision` property in the `MetadataItem` class.

When setting user metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

* The default value of the revision property is `-1`, indicating that this method call does not perform any CAS verification. If the user metadata or metadata item already exists, the latest value overwrites the previous one. If the user metadata or metadata item does not exist, the SDK creates it.
* If the revision property is a positive integer, this method call performs CAS verification. If the user metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the user metadata or metadata item does not exist, the SDK returns an error code.

#### Method [#method-28]

You can call the `setUserMetadata` method as follows:

```java
void setUserMetadata(
    String userId,
    Metadata data,
    MetadataOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |            String            | Required |    -    | User ID.                                                                                                                      |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata `](#storagemetadat-a).                                                                          |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-28]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add metadata item
ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
items.add(new MetadataItem("Name", "Tony", 174298200));
items.add(new MetadataItem("Mute", "true", 174298100));
metadata.setItems(items);

rtmClient.getStorage().setUserMetadata("userName", metadata, new MetadataOptions(true, true), new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "set user metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### getUserMetadata [#getusermetadata]

#### Description [#description-29]

The `getUserMetadata` method gets the metadata and metadata item for the specified user.

#### Method [#method-29]

You can call the `getUserMetadata` method as follows:

```java
void getUserMetadata(
    String userId,
    ResultCallback<Metadata> resultCallback
);
```

|    Parameters    |               Type               | Required | Default | Description                                                                                                                                                                                |
| :--------------: | :------------------------------: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|     `userId`     |              String              | Required |    -    | User ID.                                                                                                                                                                                   |
| `resultCallback` | `ResultCallback&lt;Metadata&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method and return the [`Metadata `](#storagemetadat-a) query result.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-29]

```java
rtmClient.getStorage().getUserMetadata("userName", new ResultCallback<Metadata>() {
    @Override
    public void onSuccess(Metadata data) {
        log(CALLBACK, "get user metadata success");
        log(INFO, "major revision: " + data.getMajorRevision());
        for (MetadataItem item : data.getItems()) {
            log(INFO, item.toString());
        }
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### removeUserMetadata [#removeusermetadata]

#### Description [#description-30]

The `removeUserMetadata` method removes user metadata or metadata items.

After successfully removing user metadata, users who subscribe to the user and enable event listeners receive the `USER` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

#### Method [#method-30]

You can call the `removeUserMetadata` method as follows:

```java
void removeUserMetadata(
    String userId,
    Metadata data,
    MetadataOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |            String            | Required |    -    | User ID.                                                                                                                      |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata `](#storagemetadat-a).                                                                          |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `options` parameter contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-30]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add metadata item
MetadataItem item = new MetadataItem();
item.setKey("Mute");
item.setRevision(174298100);
metadata.getItems().add(item);
 // Record who and when set the metadata
MetadataOptions options = new MetadataOptions();

rtmClient.getStorage().removeUserMetadata("Tony", metadata, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "remove user metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### updateUserMetadata [#updateusermetadata]

#### Description [#description-31]

The `updateUserMetadata` method updates existing user metadata. After successfully updating channel metadata, users who subscribe to the user and enable event listeners receive the `USER` type of the `onStorageEvent` event notification. See [Event listeners](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-31]

You can call the `updateUserMetadata` method as follows:

```java
void updateUserMetadata(
    String userId,
    Metadata data,
    MetadataOptions options,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |            String            | Required |    -    | User ID.                                                                                                                      |
|      `data`      |          `Metadata`          | Required |    -    | Metadata item. See [`Metadata `](#storagemetadat-a).                                                                          |
|     `options`    |       `MetadataOptions`      | Required |    -    | Options for setting the channel metadata.                                                                                     |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

The `MetadataOptions` data type contains the following properties:

|   Properties   |   Type  | Required | Default | Description                                   |
| :------------: | :-----: | :------: | :-----: | --------------------------------------------- |
|   `recordTs`   | boolean | Optional | `false` | Whether to record the timestamp of the edits. |
| `recordUserId` | boolean | Optional | `false` | Whether to record the user ID of the editor.  |

#### Basic usage [#basic-usage-31]

```java
 // Create a metadata instance
Metadata metadata = new Metadata();
 // Set the Major Revision
metadata.setMajorRevision(174298270);
 // Add a metadata item
metadata.getItems().add(new MetadataItem("Name", "Tony", 174298200));
 // Record who and when set the metadata
MetadataOptions options = new MetadataOptions();
options.setRecordTs(true);
options.setRecordUserId(true);

rtmClient.getStorage().updateUserMetadata("Tony", metadata, options, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "update user metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### subscribeUserMetadata [#subscribeusermetadata]

#### Description [#description-32]

The `subscribeUserMetadata` method can subscribe to metadata for a specified user. After successfully subscribing to the user metadata, you receive the `USER` type of the `onStorageEvent` event notification when the metadata for that user changes. See [Event listeners](#event-listeners).

#### Method [#method-32]

You can call the `subscribeUserMetadata` method as follows:

```java
void subscribeUserMetadata(
    String userId,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |            String            | Required |    -    | User ID.                                                                                                                      |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-32]

```java
rtmClient.getStorage().subscribeUserMetadata("Tony", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "subscribe user metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### unsubscribeUserMetadata [#unsubscribeusermetadata]

#### Description [#description-33]

If you do not need to receive notifications of changes to a user metadata, call the `unsubscribeUserMetadata` method to unsubscribe.

#### Method [#method-33]

You can call the `unsubscribeUserMetadata` method as follows:

```java
void unsubscribeUserMetadata(
    String userId,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|     `userId`     |            String            | Required |    -    | User ID.                                                                                                                      |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-33]

```java
rtmClient.getStorage().unsubscribeUserMetadata("Tony", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "unsubscribe user metadata success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### Metadata [#metadata]

Use the `Metadata` data type to set and manage metadata, containing the following properties:

|    Properties   |               Type              | Required | Default | Description                                                                                                                                                                                                    |
| :-------------: | :-----------------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `majorRevision` |               long              | Optional |   `-1`  | The version control switch:<br />- `-1`: Disable the version verification.<br />- > `0`: Enable the version verification. The operation can only be performed if the target version number matches this value. |
|     `items`     | `ArrayList&lt;MetadataItem&gt;` | Optional |  `null` | Metadata items.                                                                                                                                                                                                |

The `MetadataItem` data type contains the following properties:

|   Properties   |  Type  | Required | Default | Description                                                                                                                                                                                                                                                                                       |
| :------------: | :----: | :------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|      `key`     | String | Optional |    -    | Key.                                                                                                                                                                                                                                                                                              |
|     `value`    | String | Optional |    -    | Value.                                                                                                                                                                                                                                                                                            |
| `authorUserId` | String | Optional |    -    | The user ID of the editor. This value is read-only and does not support writing.                                                                                                                                                                                                                  |
|   `revision`   |  long  | Optional |   `-1`  | <br />- Returns the real version number in read operations.<br />- Serves as a version control switch in write operations:<br />- `-1`: Disable the version verification. <br />- > `0`: Enable version verification, only perform the operation if the target version number matches this value. |
|   `updateTs`   |  long  | Optional |   `0`   | Update timestamp. This value is read-only and does not support writing.                                                                                                                                                                                                                           |

## Lock [#lock]

A critical resource can only be used by one process at a time. If a critical resource is shared between different processes, each process needs to adopt a mutually exclusive method to prevent mutual interference. Signaling provides a full set of lock solutions. By controlling different processes in a distributed system, you can solve the competition problem when users access shared resources.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    The client is able to set, remove, and revoke locks. We recommend that you control the permissions of these operations on the client side based on your business needs.
  </CalloutDescription>
</CalloutContainer>

RtmLock
Lock instance

### setLock [#setlock]

#### Description [#description-34]

You need to configure the lock name, time to live (TTL) and other parameters by calling the `setLock` method. If the configuration succeeds, all users in the channel receives the `onLockEvent` event notifications of the `SET` type. For details, see [Event Listeners](#event-listeners).

#### Method [#method-34]

You can call the `setLock` method as follows:

```java
void setLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    long ttl,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                                                                                                                                                                                                                            |
| :--------------: | :--------------------------: | :------: | :-----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                                                                                                                                                                                                                          |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                                                                                                                                                                                                                             |
|    `lockName`    |            String            | Required |    -    | Lock name.                                                                                                                                                                                                                                                                                                                             |
|       `ttl`      |             long             | Required |    -    | The expiration time of the lock. The value is in seconds, ranging from \[10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the `onLockEvent` event receives the `RELEASED` event. |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method.                                                                                                                                                                                                          |

#### Basic usage [#basic-usage-34]

```java
long ttl = 30;
rtmClient.getLock().setLock("my_channel", RtmChannelType.STREAM, "my_lock", ttl, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "set lock success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### acquireLock [#acquirelock]

#### Description [#description-35]

After successfully configuring a lock, you can call the `acquireLock` method on the client to acquire the right to own the lock. When you acquire the lock, other users in the channel receives the `ACQUIRED` type of the `onLockEvent` event. For details, see [Event Listeners](#event-listeners).

#### Method [#method-35]

You can call the `acquireLock` method as follows:

```java
void acquireLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    boolean retry,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|    `lockName`    |            String            | Required |    -    | Lock name.                                                                                                                    |
|      `retry`     |            boolean           | Required |    -    | If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel.                |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-35]

```java
boolean retry = false;
rtmClient.getLock().acquireLock("chat_room", RtmChannelType.STREAM, "my_lock", retry, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "acquire lock success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### releaseLock [#releaselock-2]

#### Description [#description-36]

When a user no longer needs to own a lock, the user can call the `releaseLock` method on the client side to release the lock. After successful release the lock, other users in the channel receives the `RELEASED` type of the `onLockEvent` event. See [Event Listeners](#event-listeners).

At this time, if other users want to acquire the lock, they can call the `acquireLock` method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the `retry` property to automatically retry to acquire locks.

#### Method [#method-36]

You can call the `releaseLock` method as follows:

```java
void releaseLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | ----------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|    `lockName`    |            String            | Required |    -    | Lock name.                                                                                                                    |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-36]

```java
rtmClient.getLock().releaseLock("chat_room", RtmChannelType.STREAM, "my_lock", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "release lock success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### revokeLock [#revokelock]

#### Description [#description-37]

When the lock is occupied, to ensure that your business is not affected, you may need to revoke the lock and give other users a chance to obtain it. Revoke the occupied lock by calling `revokeLock`. When the lock is revoked, all users in the channel receives the `RELEASED` type of the `onLockEvent` event. See [Event Listeners](#event-listeners).

At this time, if other users want to acquire the lock, they can call the `acquireLock` method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the `retry` property to automatically retry to acquire locks.

#### Method [#method-37]

You can call the `revokeLock` method as follows:

```java
void revokeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    String owner,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|    `lockName`    |            String            | Required |    -    | Lock name.                                                                                                                    |
|      `owner`     |            String            | Required |    -    | The ID of the user who has a lock.                                                                                            |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-37]

```java
String lockOwner = "Tony";
rtmClient.getLock().revokeLock("chat_room", RtmChannelType.STREAM, "my_lock", lockOwner, new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "revoke lock(" + lockName + ") success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### getMessages [#getmessages]

#### Description [#description-38]

If you want to query the lock information such as lock total number, lock name, and lock user, time to live, you can call the `getMessages` method on the client.

#### Method [#method-38]

You can call the `getMessages` method as follows:

```java
void getLocks(
    String channelName,
    RtmChannelType channelType,
    ResultCallback<ArrayList<LockDetail>> resultCallback
);
```

|    Parameters    |                         Type                        | Required | Default | Description                                                                                                                              |
| :--------------: | :-------------------------------------------------: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |                        String                       | Required |    -    | Channel name.                                                                                                                            |
|   `channelType`  |                   `RtmChannelType`                  | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                               |
| `resultCallback` | `ResultCallback&lt;ArrayList&lt;LockDetail&gt;&gt;` | Required |    -    | <br />- Success: Executes the `onSuccess` method and return the `LockDetail` data type.<br />- Failure: Executes the `onFailure` method. |

The `LockDetail` data type contains the following properties:

| Properties  |  Type  | Description                                                                                                                                                                                                                                                                                                                            |
| :---------- | :----: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lockName`  | String | Lock name.                                                                                                                                                                                                                                                                                                                             |
| `lockOwner` | String | The ID of the user who has a lock.                                                                                                                                                                                                                                                                                                     |
| `ttl`       |   int  | The expiration time of the lock. The value is in seconds, ranging from \[10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the `onLockEvent` event receives the `RELEASED` event. |

#### Basic usage [#basic-usage-38]

```java
rtmClient.getLock().getLocks("chat_room", RtmChannelType.STREAM, new ResultCallback<ArrayList<LockDetail>>() {
    @Override
    public void onSuccess(ArrayList<LockDetail> details) {
        log(CALLBACK, "get channel locks success");

        for (LockDetail detail : details) {
            log(INFO, "lock name: " + detail.lockName + ", lock owner: " + detail.lockOwner + ", ttl: " + detail.ttl);
        }
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

### removeLock [#removelock]

#### Description [#description-39]

If you no longer need a lock, you can call the `removeLock` method to remove the lock. After successfully removing the lock, all users in the channel receives the `REMOVED` type of `onLockEvent` event notification. See [Event Listeners](#event-listeners).

#### Method [#method-39]

You can call the `removeLock` method as follows:

```java
void removeLock(
    String channelName,
    RtmChannelType channelType,
    String lockName,
    ResultCallback<Void> resultCallback
);
```

|    Parameters    |             Type             | Required | Default | Description                                                                                                                   |
| :--------------: | :--------------------------: | :------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------- |
|   `channelName`  |            String            | Required |    -    | Channel name.                                                                                                                 |
|   `channelType`  |       `RtmChannelType`       | Required |    -    | Channel types. See [`RtmChannelType`](#enumvchanneltyp-e).                                                                    |
|    `lockName`    |            String            | Required |    -    | Lock name.                                                                                                                    |
| `resultCallback` | `ResultCallback&lt;Void&gt;` | Required |    -    | Invocation result callback:<br />- Success: Executes the `onSuccess` method.<br />- Failure: Executes the `onFailure` method. |

#### Basic usage [#basic-usage-39]

```java
rtmClient.getLock().removeLock("chat_room", RtmChannelType.STREAM, "my_lock", new ResultCallback<Void>() {
    @Override
    public void onSuccess(Void responseInfo) {
        log(CALLBACK, "remove lock success");
    }

    @Override
    public void onFailure(ErrorInfo errorInfo) {
        log(ERROR, errorInfo.toString());
    }
});
```

## Enumerated types [#enumerated-types]

### Enum [#enum]

#### RtmAreaCode [#rtmareacode]

The region for connection, which is the region where the server the SDK connects to is located.

|  Value | Description                                   |
| :----: | --------------------------------------------- |
|  `CN`  | `0x00000001`: Mainland China.                 |
|  `NA`  | `0x00000002`: North America.                  |
|  `EU`  | `0x00000004`: Europe.                         |
|  `AS`  | `0x00000008`: Asia, excluding Mainland China. |
|  `JP`  | `0x00000010`: Japan.                          |
|  `IN`  | `0x00000020`: India.                          |
| `GLOB` | `0xFFFFFFFF`: Global.                         |

#### RtmChannelType [#rtmchanneltype]

Channel types.

|   Value   | Description           |
| :-------: | --------------------- |
| `MESSAGE` | `1`: Message channel. |
|  `STREAM` | `2`: Stream channel.  |
|   `USER`  | `3`: User Channel.    |

#### RtmConnectionChangeReason [#rtmconnectionchangereason]

Reasons causing the change of the connection state.

|                Value                | Description                                                                                                                                                               |
| :---------------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|             `CONNECTING`            | `0`: The SDK is connecting with the server.                                                                                                                               |
|            `JOIN_SUCCESS`           | `1`: The SDK has joined the channel successfully.                                                                                                                         |
|            `INTERRUPTED`            | `2`: The connection between the SDK and the server is interrupted.                                                                                                        |
|          `BANNED_BY_SERVER`         | `3`: The connection between the SDK and the server is banned by the server.                                                                                               |
|            `JOIN_FAILED`            | `4`: The SDK fails to join the channel. When the SDK fails to join the channel for more than 20 minutes, this error occurs and the SDK stops reconnecting to the channel. |
|           `LEAVE_CHANNEL`           | `5`: The SDK has left the channel.                                                                                                                                        |
|           `INVALID_APP_ID`          | `6`: The connection failed because the App ID is not valid.                                                                                                               |
|        `INVALID_CHANNEL_NAME`       | `7`: The connection failed because the channel name is not valid.                                                                                                         |
|           `INVALID_TOKEN`           | `8`: The connection failed because the token is not valid.                                                                                                                |
|           `TOKEN_EXPIRED`           | `9`: The connection failed because the token is expired.                                                                                                                  |
|         `REJECTED_BY_SERVER`        | `10`: The connection is rejected by server.                                                                                                                               |
|        `SETTING_PROXY_SERVER`       | `11`: The connection state changed to reconnecting because the SDK has set a proxy server.                                                                                |
|            `RENEW_TOKEN`            | `12`: The connection state changed because the token is renewed.                                                                                                          |
|     `CLIENT_IP_ADDRESS_CHANGED`     | `13`: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed.                                                  |
|         `KEEP_ALIVE_TIMEOUT`        | `14`: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting.                                          |
|           `REJOIN_SUCCESS`          | `15`: The user has rejoined the channel successfully.                                                                                                                     |
|                `LOST`               | `16`: The connection between the SDK and the server is lost.                                                                                                              |
|             `ECHO_TEST`             | `17`: The connection state changes due to the echo test.                                                                                                                  |
| `CLIENT_IP_ADDRESS_CHANGED_BY_USER` | `18`: The local IP address was changed by the user. The connection state changes to reconnecting.                                                                         |
|           `SAME_UID_LOGIN`          | `19`: The user joined the same channel from different devices with the same UID.                                                                                          |
|       `TOO_MANY_BROADCASTERS`       | `20`: The number of hosts in the channel has reached the upper limit.                                                                                                     |
|     `LICENSE_VALIDATION_FAILURE`    | `21`: License validation failure.                                                                                                                                         |
|    `CERTIFICATION_VERIFY_FAILURE`   | `22`: The server certificate verification has encountered an error.                                                                                                       |
|    `STREAM_CHANNEL_NOT_AVAILABLE`   | `23`: The stream channel does not exist.                                                                                                                                  |
|         `INCONSISTENT_APPID`        | `24`: The App ID does not match the token.                                                                                                                                |
|           `LOGIN_SUCCESS`           | `10001`: The SDK logs in to the Signaling system.                                                                                                                         |
|               `LOGOUT`              | `10002`: The SDK logs out from the Signaling system.                                                                                                                      |
|         `PRESENCE_NOT_READY`        | `10003`: Presence service is not ready. You need to call the `login` method again to log in to the Signaling system and re-execute all operations on the SDK.             |

#### RtmConnectionState [#rtmconnectionstate]

SDK connection states.

|      Value     | Description                                                           |
| :------------: | --------------------------------------------------------------------- |
| `DISCONNECTED` | `1`: The SDK has disconnected with the server.                        |
|  `CONNECTING`  | `2`: The SDK is connecting with the server.                           |
|   `CONNECTED`  | `3`: The SDK has connected with the server.                           |
| `RECONNECTING` | `4`: The connection is lost. The SDK is reconnecting with the server. |
|    `FAILED`    | `5`: The SDK failed to connect with the server.                       |

#### RtmEncryptionMode [#rtmencryptionmode]

Encryption mode.

|     Value     | Description            |
| :-----------: | ---------------------- |
|     `NONE`    | `0`: No encryption.    |
| `AES_128_GCM` | `1`: AES-128-GCM mode. |
| `AES_256_GCM` | `2`: AES-256-GCM mode. |

#### RtmLockEventType [#rtmlockeventtype]

Lock event type.

|    Value   | Description                                                     |
| :--------: | --------------------------------------------------------------- |
| `SNAPSHOT` | `1`: The snapshot of the lock when the user joined the channel. |
|    `SET`   | `2`: The lock is set.                                           |
|  `REMOVED` | `3`: The lock is removed.                                       |
| `ACQUIRED` | `4`: The lock is acquired.                                      |
| `RELEASED` | `5`: The lock is released.                                      |
|  `EXPIRED` | `6`: The lock expired.                                          |

#### RtmLogLevel [#rtmloglevel]

Log output levels.

|  Value  | Description                                                                                                    |
| :-----: | -------------------------------------------------------------------------------------------------------------- |
|  `NONE` | `0x0000`: No log.                                                                                              |
|  `INFO` | `0x0001`: Output the log at the `FATAL`, `ERROR`, `WARN`, or `INFO` level. We recommend you set to this value. |
|  `WARN` | `0x0002`: Output the log at the `FATAL`, `ERROR`, `WARN` level.                                                |
| `ERROR` | `0x0004`: Output the log at the `FATAL`, `ERROR` level.                                                        |
| `FATAL` | `0x0008`: Output the log at the `FATAL` level.                                                                 |

#### RtmMessagePriority [#rtmmessagepriority]

Message priority.

|   Value   | Description   |
| :-------: | ------------- |
| `HIGHEST` | `0`: Highest. |
|   `HIGH`  | `1`: High.    |
|  `NORMAL` | `4`: Normal.  |
|   `LOW`   | `8`: Low.     |

#### RtmMessageQos [#rtmmessageqos]

QoS guarantee when sending topic messages.

|    Value    | Description                                             |
| :---------: | ------------------------------------------------------- |
| `UNORDERED` | `0`: Message data is not guaranteed to arrive in order. |
|  `ORDERED`  | `1`: Message data arrives in order.                     |

#### RtmMessageType [#rtmmessagetype]

Message type.

|   Value  | Description       |
| :------: | ----------------- |
| `BINARY` | `0`: Binary type. |
| `STRING` | `1`: String type. |

#### RtmPresenceEventType [#rtmpresenceeventtype]

Presence event type.

|          Value         | Description                                                                                                                     |
| :--------------------: | ------------------------------------------------------------------------------------------------------------------------------- |
|       `SNAPSHOT`       | `1`: The snapshot of the presence when the user joined the channel.                                                             |
|       `INTERVAL`       | `2`: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time. |
|      `REMOTE_JOIN`     | `3`: A remote user joined the channel.                                                                                          |
|     `REMOTE_LEAVE`     | `4`: A remote user left the channel.                                                                                            |
|    `REMOTE_TIMEOUT`    | `5`: A remote user's connection timed out.                                                                                      |
| `REMOTE_STATE_CHANGED` | `6`: A remote user's temporary state changed.                                                                                   |
| `ERROR_OUT_OF_SERVICE` | `7`: The user did not enable presence when joining the channel.                                                                 |

#### RtmLinkOperation [#rtmlinkoperation]

Operation type.

|        Value        | Description                                                                                          |
| :-----------------: | ---------------------------------------------------------------------------------------------------- |
|       `LOGIN`       | `0`: The user logins to the Signaling system.                                                        |
|       `LOGOUT`      | `1`: The user logouts of the Signaling system.                                                       |
|        `JOIN`       | `2`: The user joins in a stream channel.                                                             |
|       `LEAVE`       | `3`: The user leaves a stream channel.                                                               |
|   `SERVER_REJECT`   | `4`: The Signaling server reject the connection.                                                     |
|   `AUTO_RECONNECT`  | `5`: The SDK is automatically reconnecting to the Signaling server.                                  |
|    `RECONNECTED`    | `6`: The SDK is reconnected to the Signaling server.                                                 |
| `HEARTBEAT_TIMEOUT` | `7`: The Signaling server does not receive the heartbeat packet within the specified timeout period. |
|   `SERVER_TIMEOUT`  | `8`: The Signaling server has timed out.                                                             |
|   `NETWORK_CHANGE`  | `9`: The network status changes.                                                                     |

#### RtmLinkState [#rtmlinkstate]

Link state type.

|      Value     | Description          |
| :------------: | -------------------- |
|     `IDLE`     | `0`: The init state. |
|  `CONNECTING`  | `1`: Connecting.     |
|   `CONNECTED`  | `2`: Connected.      |
| `DISCONNECTED` | `3`: Disconnected.   |
|   `SUSPENDED`  | `4`: Suspended.      |
|    `FAILED`    | `5`: Failed.         |

#### RtmLinkStateChangeReason [#rtmlinkstatechangereason]

Link state change reason.

|                 Value                | Description                                  |
| :----------------------------------: | -------------------------------------------- |
|               `UNKNOWN`              | `0`: Unknown reason.                         |
|                `LOGIN`               | `1`: Logging in.                             |
|            `LOGIN_SUCCESS`           | `2`: Login successful.                       |
|            `LOGIN_TIMEOUT`           | `3`: Login timeout.                          |
|        `LOGIN_NOT_AUTHORIZED`        | `4`: Login not authorized.                   |
|           `LOGIN_REJECTED`           | `5`: Login rejected.                         |
|               `RELOGIN`              | `6`: Re-login.                               |
|               `LOGOUT`               | `7`: Logout.                                 |
|           `AUTO_RECONNECT`           | `8`: Auto-reconnect.                         |
|          `RECONNECT_TIMEOUT`         | `9`: Reconnect timeout.                      |
|          `RECONNECT_SUCCESS`         | `10`: Reconnect successful.                  |
|                `JOIN`                | `11`: Joining a channel.                     |
|            `JOIN_SUCCESS`            | `12`: Join channel successful.               |
|             `JOIN_FAILED`            | `13`: Join channel failed.                   |
|               `REJOIN`               | `14`: Re-join a channel.                     |
|                `LEAVE`               | `15`: Leave a channel.                       |
|            `INVALID_TOKEN`           | `16`: Invalid token.                         |
|            `TOKEN_EXPIRED`           | `17`: Token expired.                         |
|         `INCONSISTENT_APP_ID`        | `18`: Inconsistent app ID.                   |
|        `INVALID_CHANNEL_NAME`        | `19`: Invalid channel name.                  |
|           `INVALID_USER_ID`          | `20`: Invalid user ID.                       |
|           `NOT_INITIALIZED`          | `21`: SDK not initialized.                   |
|      `RTM_SERVICE_NOT_CONNECTED`     | `22`: RTM service not connected.             |
| `CHANNEL_INSTANCE_EXCEED_LIMITATION` | `23`: Channel instance exceeds the limit.    |
|  `OPERATION_RATE_EXCEED_LIMITATION`  | `24`: Operation frequency exceeds the limit. |
|       `CHANNEL_IN_ERROR_STATE`       | `25`: Channel in error state.                |
|       `PRESENCE_NOT_CONNECTED`       | `26`: Presence service not connected.        |
|           `SAME_UID_LOGIN`           | `27`: Login with the same user ID.           |
|        `KICKED_OUT_BY_SERVER`        | `28`: Kicked out by the server.              |
|         `KEEP_ALIVE_TIMEOUT`         | `29`: Keepalive timeout.                     |
|          `CONNECTION_ERROR`          | `30`: Connection error.                      |
|         `PRESENCE_NOT_READY`         | `31`: Presence service not ready.            |
|           `NETWORK_CHANGE`           | `32`: Network changed.                       |
|        `SERVICE_NOT_SUPPORTED`       | `33`: Service not supported.                 |
|    `STREAM_CHANNEL_NOT_AVAILABLE`    | `34`: Stream Channel not available.          |
|        `STORAGE_NOT_AVAILABLE`       | `35`: Storage service not available.         |
|         `LOCK_NOT_AVAILABLE`         | `36`: Lock service not available.            |
|         `LOGIN_TOO_FREQUENT`         | `37`: The login operation is too frequent.   |

#### RtmProtocolType [#rtmprotocoltype]

Protocol type.

|    Value   | Description                      |
| :--------: | -------------------------------- |
|  `TCP_UDP` | `0`: Both TCP and UDP protocols. |
| `TCP_ONLY` | `1`: Only TCP protocol.          |

#### RtmServiceType [#rtmservicetype]

Service type

|   Value   | Description                                                                                                 |
| :-------: | ----------------------------------------------------------------------------------------------------------- |
| `MESSAGE` | The foundational services comprise the message channel, user channel, presence, storage, and lock services. |
|  `STREAM` | The stream channel service.                                                                                 |

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    To fully utilize all services offered by Signaling, use bitwise operations to simultaneously configure two service types.
  </CalloutDescription>
</CalloutContainer>

#### RtmProxyType [#rtmproxytype]

Proxy type.

|    Value    | Description                                   |
| :---------: | --------------------------------------------- |
|    `NONE`   | `0`: Do not enable the proxy.                 |
|    `HTTP`   | `1`: Enable the proxy for the HTTP protocol.  |
| `CLOUD_TCP` | `2`: Enable cloud proxy for the TCP protocol. |

#### RtmStorageEventType [#rtmstorageeventtype]

Storage event type.

|    Value   | Description                                                                                                                                                          |
| :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SNAPSHOT` | `1`: When a user subscribes to channel metadata or user etadata for the first time, or joins a channel, the local user receives notifications of this type of event. |
|    `SET`   | `2`: Occurs when calling `setChannelMetadata` or `setUserMetadata`. Caution: This event only occurs in incremental data update mode.                                 |
|  `UPDATE`  | `3`: Occurs when calling methods to set, update, or delete the channel metadata or user metadata.                                                                    |
|  `REMOVE`  | `4`: Occurs when calling `removeChannelMetadata` or `removeUserMetadata`. Caution: This event only occurs in incremental data update mode.                           |

#### RtmStorageType [#rtmstoragetype]

Storage type.

|   Value   | Description                  |
| :-------: | ---------------------------- |
|   `USER`  | `1`: User metadata event.    |
| `CHANNEL` | `2`: Channel metadata event. |

#### RtmTopicEventType [#rtmtopiceventtype]

Topic event type.

|      Value     | Description                                                      |
| :------------: | ---------------------------------------------------------------- |
|   `SNAPSHOT`   | `1`: The snapshot of the topic when the user joined the channel. |
|  `REMOTE_JOIN` | `2`: A remote user joined the channel.                           |
| `REMOTE_LEAVE` | `3`: A remote user left the channel.                             |

## Troubleshooting [#troubleshooting]

Refer to the following information for troubleshooting API calls.

### ErrorInfo [#errorinfo]

|  Properties |      Type      | Description                      |
| :---------: | :------------: | -------------------------------- |
| `errorCode` | `RtmErrorCode` | Error code for this operation.   |
|   `reason`  |     String     | Error reason for this operation. |
| `operation` |     String     | Operation type.                  |

To find out the cause of the error and get the corresponding solution, use the `errorCode` field with the [error codes table](#error-codes-table).

### Error codes table [#error-codes-table]

Refer to the following error codes table to identify and troubleshoot the problem:

| Error code | Error description                          | Cause and solution                                                                                                                                                                                                                                                                                                                                   |
| :--------- | :----------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0`        | `OK`                                       | Correct call                                                                                                                                                                                                                                                                                                                                         |
| `-10001`   | `NOT_INITIALIZED`                          | The SDK is not initialized. Please initialize the `RtmClient` instance by calling the `create` method before performing other operations.                                                                                                                                                                                                            |
| `-10002`   | `NOT_LOGIN`                                | The user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first.                                                                                                                                                                                                      |
| `-10003`   | `INVALID_APP_ID`                           | Invalid App ID: <br /> - Check that the App ID is correct. <br /> - Ensure that Signaling has been activated for the App ID.                                                                                                                                                                                                                         |
| `-10005`   | `INVALID_TOKEN`                            | Invalid Token: <br /> - The token is invalid, check whether the Token Provider generates a valid Signaling Token.                                                                                                                                                                                                                                    |
| `-10006`   | `INVALID_USER_ID`                          | Invalid User ID: <br /> - Check if user ID is empty. <br /> - Check if the user ID contains illegal characters.                                                                                                                                                                                                                                      |
| `-10007`   | `INIT_SERVICE_FAILED`                      | SDK initialization failed. Please reinitialize by calling the `create` method.                                                                                                                                                                                                                                                                       |
| `-10008`   | `INVALID_CHANNEL_NAME`                     | Invalid channel name: <br /> - Check if the channel name is empty. <br /> - Check if the channel name contains illegal characters.                                                                                                                                                                                                                   |
| `-10009`   | `TOKEN_EXPIRED`                            | Token expired. Call `renewToken` to reacquire the Token.                                                                                                                                                                                                                                                                                             |
| `-10010`   | `LOGIN_NO_SERVER_RESOURCES`                | Server resources are limited. It is recommended to log in again.                                                                                                                                                                                                                                                                                     |
| `-10011`   | `LOGIN_TIMEOUT`                            | Login timeout. Check whether the current network is stable and switch to a stable network environment.                                                                                                                                                                                                                                               |
| `-10012`   | `LOGIN_REJECTED`                           | SDK login rejected by the server: <br /> - Check tha Signaling is activated on your App ID. <br /> - Check if the token or `userId` is banned.                                                                                                                                                                                                       |
| `-10013`   | `LOGIN_ABORTED`                            | SDK login interrupted due to unknown problem: <br /> - Check that the current network is stable and switch to a stable network environment. <br /> - The current `userId` is logged in.                                                                                                                                                              |
| `-10014`   | `INVALID_PARAMETER`                        | Invalid parameter. Please check if the parameters you provided are correct.                                                                                                                                                                                                                                                                          |
| `-10015`   | `LOGIN_NOT_AUTHORIZED`                     | No RTM service permissions. Check that the console opens Signaling services.                                                                                                                                                                                                                                                                         |
| `-10016`   | `INCONSISTENT_APPID`                       | Inconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent.                                                                                                                                                                                                                           |
| `-10017`   | `DUPLICATE_OPERATION`                      | Duplicate operation.                                                                                                                                                                                                                                                                                                                                 |
| `-10018`   | `INSTANCE_ALREADY_RELEASED`                | Repeat `rtm` instantiation or `RTMStreamChannel` instantiation.                                                                                                                                                                                                                                                                                      |
| `-10019`   | `INVALID_CHANNEL_TYPE`                     | Invalid channel type. The SDK only supports the following channel types. Please use the correct value: <br /> - `MESSAGE`: Message Channel <br /> - `STREAM`: Stream Channel <br /> - `USER`: User Channel                                                                                                                                           |
| `-10020`   | `INVALID_ENCRYPTION_PARAMETER`             | Message encryption parameters are invalid. <br />- Check that the encryption key generated is a String. <br />- Check that the generated encryption salt is `Uint8Array` type and that the length is 32 bytes. <br />- Check that the encryption method matches the encryption key and the encryption salt.                                          |
| `-10021`   | `OPERATION_RATE_EXCEED_LIMITATION`         | Channel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second.                                                                                                                                                                                                            |
| `-10022`   | `SERVICE_NOT_SUPPORTED`                    | The service type is not supported. Check whether the service type you set in `RtmServiceType` is correct. This error code is only applicable to the private deployment function.                                                                                                                                                                     |
| `-10023`   | `LOGIN_CANCELED`                           | The login operation has been canceled. Possible reasons are as follows: <br />- After calling the `login` method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call. <br />- Calling the `logout` method to log out before successfully logging in. |
| `-10024`   | `INVALID_PRIVATE_CONFIG`                   | The private deployment parameter settings are invalid. Please check whether the service type and server address you set in `RtmPrivateConfig` are valid.                                                                                                                                                                                             |
| `-10025`   | `NOT_CONNECTED`                            | Not connected to the Signaling server. When you call APIs related to message subscription, metadata, or the Lock module, this error is reported if the Signaling service is not connected.                                                                                                                                                           |
| `-10026`   | `RENEW_TOKEN_TIMEOUT`                      | Token renewal timed out.                                                                                                                                                                                                                                                                                                                             |
| `-11001`   | `CHANNEL_NOT_JOINED`                       | The user has not joined the channel: <br /> - The user is not online, offline or has not joined the channel<br /> - Check for typos in `userId`.                                                                                                                                                                                                     |
| `-11002`   | `CHANNEL_NOT_SUBSCRIBED`                   | The user has not subscribed to the channel: <br /> - The user is not online, offline or has not joined the channel<br /> - Check for typos in `userId`.                                                                                                                                                                                              |
| `-11003`   | `CHANNEL_EXCEED_TOPIC_USER_LIMITATION`     | The number of subscribers to this topic exceeds the limit.                                                                                                                                                                                                                                                                                           |
| `-11004`   | `CHANNEL_IN_REUSE`                         | In co-channel mode, RTM released the Stream Channel.                                                                                                                                                                                                                                                                                                 |
| `-11005`   | `CHANNEL_INSTANCE_EXCEED_LIMITATION`       | The number of created or subscribed channels exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                                    |
| `-11006`   | `CHANNEL_IN_ERROR_STATE`                   | Channel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel.                                                                                                                                                                                                                                                  |
| `-11007`   | `CHANNEL_JOIN_FAILED`                      | Failed to join this channel: <br /> - Check if the number of joined channels exceeds the limit. <br /> - Check if the channel name is illegal. <br /> - Check if the network is disconnected.                                                                                                                                                        |
| `-11008`   | `CHANNEL_INVALID_TOPIC_NAME`               | Invalid topic name: <br /> - Check whether the topic name contains illegal characters. <br /> - Check if the topic name is empty.                                                                                                                                                                                                                    |
| `-11009`   | `CHANNEL_INVALID_MESSAGE`                  | Invalid message. Check whether the message type is legal, Signaling only supports `string`, `Uint8Array` type messages.                                                                                                                                                                                                                              |
| `-11010`   | `CHANNEL_MESSAGE_LENGTH_EXCEED_LIMITATION` | Message length exceeded limit. Check if the message payload size exceeds the limit: <br /> - Message Channel single message package limit is 32 KB. <br /> - Stream Channel single message package limit is 1 KB.                                                                                                                                    |
| `-11011`   | `CHANNEL_INVALID_USER_LIST`                | Invalid user list: <br /> - Check if the user list is empty. <br /> - Check if the user list contains invalid entries.                                                                                                                                                                                                                               |
| `-11012`   | `CHANNEL_NOT_AVAILABLE`                    | Invalid user list: <br /> - Check if the user list is empty<br /> - Check if the user list contains illegal items.                                                                                                                                                                                                                                   |
| `-11013`   | `CHANNEL_TOPIC_NOT_SUBSCRIBED`             | The topic is not subscribed.                                                                                                                                                                                                                                                                                                                         |
| `-11014`   | `CHANNEL_EXCEED_TOPIC_LIMITATION`          | The number of topics exceeds the limit.                                                                                                                                                                                                                                                                                                              |
| `-11015`   | `CHANNEL_JOIN_TOPIC_FAILED`                | Failed to join this topic. Check whether the number of added topics exceeds the limit.                                                                                                                                                                                                                                                               |
| `-11016`   | `CHANNEL_TOPIC_NOT_JOINED`                 | The topic has not been joined. To send a message, you need to join the Topic first.                                                                                                                                                                                                                                                                  |
| `-11017`   | `CHANNEL_TOPIC_NOT_EXIST`                  | The topic does not exist. Check that the topic name is correct.                                                                                                                                                                                                                                                                                      |
| `-11018`   | `CHANNEL_INVALID_TOPIC_META`               | The `meta` parameters in the topic are invalid. Check if the `meta` parameter exceeds 256 bytes.                                                                                                                                                                                                                                                     |
| `-11019`   | `CHANNEL_SUBSCRIBE_TIMEOUT`                | Channel subscription timed out. Check for broken connections.                                                                                                                                                                                                                                                                                        |
| `-11020`   | `CHANNEL_SUBSCRIBE_TOO_FREQUENT`           | The channel subscription operation is too frequent. Make sure that the subscription operation of the same channel within a 5 seconds interval does not exceed 2 attempts.                                                                                                                                                                            |
| `-11021`   | `CHANNEL_SUBSCRIBE_FAILED`                 | Channel subscription failed. Check if the number of subscribed channels exceeds the limit.                                                                                                                                                                                                                                                           |
| `-11022`   | `CHANNEL_UNSUBSCRIBE_FAILED`               | Failed to unsubscribe from the channel. Check if the connection is disconnected.                                                                                                                                                                                                                                                                     |
| `-11023`   | `CHANNEL_ENCRYPT_MESSAGE_FAILED`           | Message encryption failed: <br /> - Check that the `cipherKey` is valid. <br /> - Check that the `salt` is valid. <br /> - Check if `encryptionMode` mode matches the `cipherKey` and `salt`.                                                                                                                                                        |
| `-11024`   | `CHANNEL_PUBLISH_MESSAGE_FAILED`           | Message publishing failed. Check for broken connections.                                                                                                                                                                                                                                                                                             |
| `-11026`   | `CHANNEL_PUBLISH_MESSAGE_TIMEOUT`          | Message publishing timed out. Check for broken connections.                                                                                                                                                                                                                                                                                          |
| `-11027`   | `CHANNEL_NOT_CONNECTED`                    | The SDK is disconnected from the Signaling server. Please log in again.                                                                                                                                                                                                                                                                              |
| `-11028`   | `CHANNEL_LEAVE_FAILED`                     | Failed to leave the channel. Check for broken connections.                                                                                                                                                                                                                                                                                           |
| `-11029`   | `CHANNEL_CUSTOM_TYPE_LENGTH_OVERFLOW`      | Custom type length overflow. The length of the `customType` field must to be within 32 characters.                                                                                                                                                                                                                                                   |
| `-11030`   | `CHANNEL_INVALID_CUSTOM_TYPE`              | `customType` field is invalid. Check the `customType` field for illegal characters.                                                                                                                                                                                                                                                                  |
| `-11031`   | `CHANNEL_UNSUPPORTED_MESSAGE_TYPE`         | Message type is not supported.                                                                                                                                                                                                                                                                                                                       |
| `-11032`   | `CHANNEL_PRESENCE_NOT_READY`               | Presence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel.                                                                                                                                                                                                                                               |
| `-11033`   | `CHANNEL_RECEIVER_OFFLINE`                 | When sending a user message, the remote user is offline: <br /> - Check if the user ID set when calling the method is correct.<br /> - Check if the remote user is logged in and online.                                                                                                                                                             |
| `-11034`   | `CHANNEL_JOIN_CANCELED`                    | The join channel operation has been canceled. After calling the `joinTopic` method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call.                                                                                                              |
| `-12001`   | `STORAGE_OPERATION_FAILED`                 | Storage operation failed.                                                                                                                                                                                                                                                                                                                            |
| `-12002`   | `STORAGE_METADATA_ITEM_EXCEED_LIMITATION`  | The number of Storage Metadata Items exceeds the limit.                                                                                                                                                                                                                                                                                              |
| `-12003`   | `STORAGE_INVALID_METADATA_ITEM`            | Invalid Metadata Item.                                                                                                                                                                                                                                                                                                                               |
| `-12004`   | `STORAGE_INVALID_ARGUMENT`                 | Invalid argument.                                                                                                                                                                                                                                                                                                                                    |
| `-12005`   | `STORAGE_INVALID_REVISION`                 | Invalid Revision parameter.                                                                                                                                                                                                                                                                                                                          |
| `-12006`   | `STORAGE_METADATA_LENGTH_OVERFLOW`         | Metadata overflows.                                                                                                                                                                                                                                                                                                                                  |
| `-12007`   | `STORAGE_INVALID_LOCK_NAME`                | Invalid Lock name.                                                                                                                                                                                                                                                                                                                                   |
| `-12008`   | `STORAGE_LOCK_NOT_ACQUIRED`                | The Lock was not acquired.                                                                                                                                                                                                                                                                                                                           |
| `-12009`   | `STORAGE_INVALID_KEY`                      | Invalid Metadata key.                                                                                                                                                                                                                                                                                                                                |
| `-12010`   | `STORAGE_INVALID_VALUE`                    | Invalid metadata value.                                                                                                                                                                                                                                                                                                                              |
| `-12011`   | `STORAGE_KEY_LENGTH_OVERFLOW`              | Metadata key length overflow.                                                                                                                                                                                                                                                                                                                        |
| `-12012`   | `STORAGE_VALUE_LENGTH_OVERFLOW`            | Metadata value length overflow.                                                                                                                                                                                                                                                                                                                      |
| `-12013`   | `STORAGE_DUPLICATE_KEY`                    | Duplicate Metadata Item key.                                                                                                                                                                                                                                                                                                                         |
| `-12014`   | `STORAGE_OUTDATED_REVISION`                | Outdated Revision parameter.                                                                                                                                                                                                                                                                                                                         |
| `-12015`   | `STORAGE_NOT_SUBSCRIBE`                    | This channel is not subscribed.                                                                                                                                                                                                                                                                                                                      |
| `-12016`   | `STORAGE_INVALID_METADATA_INSTANCE`        | Metadata instance does not exist. Please create a Metadata instance.                                                                                                                                                                                                                                                                                 |
| `-12017`   | `STORAGE_SUBSCRIBE_USER_EXCEED_LIMITATION` | The number of subscribers exceeds the limit.                                                                                                                                                                                                                                                                                                         |
| `-12018`   | `STORAGE_OPERATION_TIMEOUT`                | Storage operation timed out.                                                                                                                                                                                                                                                                                                                         |
| `-12019`   | `STORAGE_NOT_AVAILABLE`                    | The Storage service is not available.                                                                                                                                                                                                                                                                                                                |
| `-13001`   | `PRESENCE_NOT_CONNECTED`                   | The user is not connected to the system.                                                                                                                                                                                                                                                                                                             |
| `-13002`   | `PRESENCE_NOT_WRITABLE`                    | Presence service is unavailable.                                                                                                                                                                                                                                                                                                                     |
| `-13003`   | `PRESENCE_INVALID_ARGUMENT`                | Invalid argument.                                                                                                                                                                                                                                                                                                                                    |
| `-13004`   | `PRESENCE_CACHED_TOO_MANY_STATES`          | The temporary user state cached before joining the channel exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                      |
| `-13005`   | `PRESENCE_STATE_COUNT_OVERFLOW`            | The number of temporary user state key/value pairs exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                              |
| `-13006`   | `PRESENCE_INVALID_STATE_KEY`               | Invalid state key.                                                                                                                                                                                                                                                                                                                                   |
| `-13007`   | `PRESENCE_INVALID_STATE_VALUE`             | Invalid state value.                                                                                                                                                                                                                                                                                                                                 |
| `-13008`   | `PRESENCE_STATE_KEY_SIZE_OVERFLOW`         | Presence key length overflow.                                                                                                                                                                                                                                                                                                                        |
| `-13009`   | `PRESENCE_STATE_VALUE_SIZE_OVERFLOW`       | Presence value overflow                                                                                                                                                                                                                                                                                                                              |
| `-13010`   | `PRESENCE_STATE_DUPLICATE_KEY`             | Repeated state key.                                                                                                                                                                                                                                                                                                                                  |
| `-13011`   | `PRESENCE_USER_NOT_EXIST`                  | The user does not exist.                                                                                                                                                                                                                                                                                                                             |
| `-13012`   | `PRESENCE_OPERATION_TIMEOUT`               | Presence operation timed out.                                                                                                                                                                                                                                                                                                                        |
| `-13013`   | `PRESENCE_OPERATION_FAILED`                | Presence operation failed.                                                                                                                                                                                                                                                                                                                           |
| `-14001`   | `LOCK_OPERATION_FAILED`                    | Lock operation failed.                                                                                                                                                                                                                                                                                                                               |
| `-14002`   | `LOCK_OPERATION_TIMEOUT`                   | Lock operation timed out.                                                                                                                                                                                                                                                                                                                            |
| `-14003`   | `LOCK_OPERATION_PERFORMING`                | Lock operation in progress.                                                                                                                                                                                                                                                                                                                          |
| `-14004`   | `LOCK_ALREADY_EXIST`                       | Lock already exists.                                                                                                                                                                                                                                                                                                                                 |
| `-14005`   | `LOCK_INVALID_NAME`                        | Invalid Lock name.                                                                                                                                                                                                                                                                                                                                   |
| `-14006`   | `LOCK_NOT_ACQUIRED`                        | The Lock was not acquired.                                                                                                                                                                                                                                                                                                                           |
| `-14007`   | `LOCK_ACQUIRE_FAILED`                      | Failed to acquire the Lock.                                                                                                                                                                                                                                                                                                                          |
| `-14008`   | `LOCK_NOT_EXIST`                           | The Lock does not exist.                                                                                                                                                                                                                                                                                                                             |
| `-14009`   | `LOCK_NOT_AVAILABLE`                       | Lock service is not available.                                                                                                                                                                                                                                                                                                                       |
