Skip to main content

You are viewing Agora Docs forBetaproducts and features. Switch to Docs

Android
iOS
macOS
Web
Linux C++
Unity

API reference

The Signaling SDK API Reference lists the description, methods, basic usage, sample code, and return values. It is divided in to the following sections:

Setup

The API references for the Signaling SDK introduces the interface description, interface methods, basic usage example codes, and return values of Signaling APIs.

RtmConfig

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

You can create RtmConfig instances as follows:


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

PropertiesTypeRequiredDefaultDescription
appIdstringRequired-App ID obtained when creating a project in the Agora Console.
userIdstringRequired-User ID for identify a user or a device.
Information
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.
areaCodeRtmAreaCodeOptionalGLOBService area code, you can choose according to the region where your business is deployed. See RtmAreaCode.
eventListenerRtmEventListenerRequired-Signaling event notification listener settings. See Event listeners.
protocolTypeRtmProtocolTypeOptionalTCP_UDPProtocol 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.
presenceTimeoutintOptional300Presence 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.
heartbeatIntervalintOptional5Heartbeat 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.
useStringUserIdBoolOptionaltrueWhether to use string-type user IDs:
  • true: Use string-type user IDs.
  • 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.
logConfigRtmLogConfigOptional-Log configuration properties such as the log storage size, storage path, and level.
proxyConfigRtmProxyConfigOptional-When using the Proxy feature of Signaling, you need to configure this parameter.
encryptionConfigRtmEncryptionConfigOptional-When using the client-side encryption feature of Signaling, you need to configure this parameter.
privateConfigRtmPrivateConfigOptional-When using the private deployment feature of Signaling, you need to configure this parameter.
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:

PropertiesTypeRequiredDefaultDescription
filePathStringOptional-Log file storage paths.
fileSizeInKBintOptional1024Log file size in KB, with a value range of [128,1024].
  • If the value you enter is less than 128, the SDK sets the value to 128.
  • If the value you enter is greater than 1024, the SDK sets the value to 1024.
  • levelRtmLogLevelOptionalINFOOutput level of log information. See RtmLogLevel.
    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.
    Caution
    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.

    RtmProxyConfig contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    proxyTypeRtmProxyTypeOptionalNONEProxy protocol type. See RtmProxyType.
    serverStringOptional-Proxy server domain name or IP address.
    portintOptional-Proxy listening port.
    accountStringOptional-Proxy login account.
    passwordStringOptional-Proxy login password.
    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.
    Caution
    Once you set the encryption feature, all users must use the same encryption mode and key, otherwise users cannot communicate with each other.

    RtmEncryptionConfig contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    encryptionModeRtmEncryptionModeOptionalNONEEncryption mode. See RtmEncryptionMode.
    encryptionKeyStringOptional-User-defined encryption key, unlimited length. Agora recommends using a 32-byte key.
    encryptionKdfSaltbyte[]OptionalnullUser-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side.
    RtmPrivateConfig
    Use the RtmPrivateConfig instance to set the properties required for the private deployment.

    RtmPrivateConfig contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    serviceTypeEnumSet<RtmServiceType>Optional-Service type. See RtmServiceType.
    accessPointHostsArrayList<String>Optional-An array of server addresses, where you can fill in domain names or IP addresses.

    Basic usage


    _30
    RtmProxyConfig proxyConfig = new RtmProxyConfig();
    _30
    proxyConfig.setProxyType(RtmProxyType.HTTP);
    _30
    proxyConfig.setServer("x.x.x.x"); // your proxy server ip
    _30
    proxyConfig.setPort(8080); // your server port
    _30
    proxyConfig.setAccount("user_name");
    _30
    proxyConfig.setPassword("pass_word");
    _30
    _30
    RtmLogConfig logConfig = new RtmLogConfig();
    _30
    logConfig.setFilePath(""); // your log path
    _30
    logConfig.setFileSize(10*1024); // log file size
    _30
    logConfig.setLevel(RtmLogLevel.INFO);
    _30
    _30
    byte[] salt = {1, 2, 3, 4, 5};
    _30
    RtmEncryptionConfig encryptionConfig = new RtmEncryptionConfig();
    _30
    encryptionConfig.setEncryptionMode(RtmEncryptionMode.AES_256_GCM);
    _30
    encryptionConfig.setEncryptionKey("your_encryption_key");
    _30
    encryptionConfig.setEncryptionSalt(salt);
    _30
    _30
    RtmConfig rtmConfig = new RtmConfig.Builder("yourAppId", "Tony")
    _30
    .areaCode(EnumSet.of(RtmAreaCode.GLOB))
    _30
    .eventListener(eventListener)
    _30
    .protocolType(RtmProtocolType.TCP_UDP)
    _30
    .presenceTimeout(300)
    _30
    .heartbeatInterval(5)
    _30
    .useStringUserId(true)
    _30
    .proxyConfig(proxyConfig)
    _30
    .logConfig(logConfig)
    _30
    .encryptionConfig(encryptionConfig)
    _30
    .privateConfig(privateConfig)
    _30
    .build();

    create

    Description

    Call the create method to create and initialize the Signaling Client instance.
    Information
    • You need to create and initialize a client instance before calling other Signaling APIs.
    • 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.

    Method

    You can create and initialize an instance as follows:


    _1
    RtmClient create(RtmConfig config) throws Exception;

    ParametersTypeRequiredDefaultDescription
    configRtmConfigRequired-Initialize the configuration parameters of the Signaling Client. See RtmConfig.

    Basic usage


    _9
    RtmConfig rtmConfig = new RtmConfig.Builder("yourAppId", "Tony")
    _9
    .eventListener(eventListener)
    _9
    .build();
    _9
    _9
    try {
    _9
    rtmClient = RtmClient.create(rtmConfig);
    _9
    } catch (Exception e) {
    _9
    e.printStackTrace();
    _9
    }

    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

    Description

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

    Event TypeDescription
    onMessageEventReceive message notifications from all subscribed Message Channels or topic message notifications subscribed to, in all Stream Channels you join. See MessageEvent .
    onPresenceEventReceive presence event notifications in subscribed message channels and joined stream channels. See PresenceEvent
    onTopicEventReceive all topic event notifications in joined stream channels. See TopicEvent
    onStorageEventReceive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. See StorageEvent
    onLockEventReceive lock event notifications in subscribed message channels and joined stream channels. See LockEvent
    onConnectionStateChanged(Deprecated) Receive event notifications when client connection status changes. For details, see RtmConnectionState and RtmConnectionChangeReason.
    onLinkStateEventReceive event notifications when client connection status changes. See LinkStateEvent.
    onTokenPrivilegeWillExpireReceive event notifications when the client tokens are about to expire.

    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

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


    _43
    // Add the message event listener
    _43
    // Only override the events that you want to receive
    _43
    rtmConfig.eventListener = new RtmEventListener {
    _43
    @Override
    _43
    public void onMessageEvent(MessageEvent event) {
    _43
    // Your message event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onPresenceEvent(PresenceEvent event) {
    _43
    // Your presence event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onTopicEvent(TopicEvent event) {
    _43
    // Your topic event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onLockEvent(LockEvent event) {
    _43
    // Your lock event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onStorageEvent(StorageEvent event) {
    _43
    // Your storage event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
    _43
    // Your connection state change event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onLinkStateEvent(LinkStateEvent event) {
    _43
    // Your link state change event handler
    _43
    }
    _43
    _43
    @Override
    _43
    public void onTokenPrivilegeWillExpire(String channelName) {
    _43
    // Your token privilege will expire event handler
    _43
    }
    _43
    }

    Adding at Any Time
    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.

    _15
    // create event listener
    _15
    // only need to override the event which you want to receive
    _15
    RtmEventListener listener = new RtmEventListener() {
    _15
    @Override
    _15
    public void onMessageEvent(MessageEvent event) {
    _15
    }
    _15
    _15
    @Override
    _15
    public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
    _15
    }
    _15
    };
    _15
    _15
    // add listener
    _15
    rtmClient.addEventListener(listener);
    _15
    // ...

    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.

    _1
    rtmClient.removeEventListener(listener);

    MessageEvent

    MessageEvent contains the following properties:

    PropertiesTypeDescription
    channelTypeRtmChannelTypeChannel types. See RtmChannelType.
    channelNameStringChannel name.
    topicNameStringTopic name.
    messageRtmMessageMessage.
    publisherStringUser ID of the message publisher.
    customTypeStringA user-defined field. Only supports string type.
    timestamplongThe timestamp when the event occurs.

    RtmMessage contains the following properties:

    PropertiesTypeDescription
    messageStringString type message.
    databyte[]Byte type message.
    messageTypeRtmMessageTypeMessage type. See RtmMessageType.
    PresenceEvent

    PresenceEvent contains the following properties:

    PropertiesTypeDescription
    typeRtmPresenceEventTypePresence event type. See RtmPresenceEventType.
    channelTypeRtmChannelTypeChannel types. See RtmChannelType.
    channelNameStringChannel name.
    publisherStringUser ID of the message publisher.
    stateItemsArrayList<StateItem>Key-value pair that identifies the user's presence state.
    intervalIntervalInfoIn 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.
    snapshotSnapshotInfoWhen 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.
    timestamplongThe timestamp when the event occurred.

    IntervalInfo contains the following properties:

    PropertiesTypeDescription
    joinUserListArrayList<String>List of users who joined the channel in the previous cycle.
    leaveUserListArrayList<String>List of users who left the channel in the previous cycle.
    timeoutUserListArrayList<String>List of users who timed out joining the channel in the previous cycle.
    userStateListArrayList<UserState>List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs.

    SnapshotInfo contains the following properties:

    PropertiesTypeDescription
    userStateListArrayList<UserState>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:

    PropertiesTypeDescription
    keystringKey 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.
    valuestringValue of the user state.
    TopicEvent

    TopicEvent contains the following properties:

    PropertiesTypeDescription
    typeRtmTopicEventTypeTopic event type. See RtmTopicEventType.
    channelNameStringChannel name.
    publisherStringUser ID.
    topicInfosArrayList<TopicInfo>Topic information.
    timestamplongThe timestamp when the event occurs.

    TopicInfo data type contains the following properties:

    PropertiesTypeDescription
    topicNameStringTopic name.
    publishersArrayList<PublisherInfo>Message publisher array.

    PublisherInfo data type contains the following properties:

    PropertiesTypeDescription
    publisherUserIdStringUser ID of the message publisher.
    publisherMetaStringMetadata of the message publisher.
    StorageEvent

    StorageEvent contains the following properties:

    PropertiesTypeDescription
    channelTypeRtmChannelTypeChannel types. See RtmChannelType.
    storageTypeRtmStorageTypeStorage type. See RtmStorageType.
    eventTypeRtmStorageEventTypeStorage event type. See RtmStorageEventType.
    targetStringUser ID or channel name.
    dataMetadataMetadata item. See Metadata.
    timestamplongThe timestamp when the event occurs.
    LockEvent

    LockEvent contains the following properties:

    PropertiesTypeDescription
    channelTypeRtmChannelTypeChannel types. See RtmChannelType.
    eventTypeRtmLockEventTypeLock event type. See RtmLockEventType.
    channelNameStringChannel name.
    lockDetailListArrayList<LockDetail>Details of lock.
    timestamplongThe timestamp when the event occurs.

    The LockDetail data type contains the following properties:

    PropertiesTypeDescription
    lockNameStringLock name.
    lockOwnerStringThe ID of the user who has a lock.
    ttlintThe 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

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

    | Parameters | Type | Required | Default | Description | |:------------------:|:-------------------:| ----------------------------------------------------------------------------------------------------------------------------------- | | currentState | RtmLinkState | The current link state. See RtmLinkState. | | previousState | RtmLinkState | The previous link state. See RtmLinkState. | | serviceType | RtmServiceType | The network connection type. See RtmServiceType. | | operation | RtmLinkOperation | The operation that triggered the current state transition. See RtmLinkOperation. | | reason | String | The reason of the current state transition. | | affectedChannels | ArrayList<String> | The channels affected by the current state transition. | | unrestoredChannels | ArrayList<String> | 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. |

    login

    Description

    Information
    After the user successfully logs in to the Signaling service, the PCU of the application increases, which affects your billing data.

    Method

    You can log in to the Signaling system as follows:


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

    ParametersTypeRequiredDefaultDescription
    tokenconst char*Required-The token used for logging in to Signaling.
  • If you have enabled token authentication for your project, use either the Signaling temporary token or obtain a Signaling token generated by your token server.
  • If your project does not enable token authentication, use an empty string or the App ID of a project that has Signaling services enabled.
  • resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • 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:
    PropertiesTypeDescription
    errorCodeRtmErrorCodeError code for this operation.
    reasonStringError reason for this operation.
    operationStringOperation type.

    To find out the cause of the error and get the corresponding solution, use the errorCode field with the error codes table.

    Basic usage


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

    logout

    Description

    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

    You can log out as follows:


    _1
    void logout(ResultCallback<Void> resultCallback);

    ParametersTypeRequiredDefaultDescription
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _9
    rtmClient.logout(new ResultCallback<Void>() {
    _9
    @Override
    _9
    public void onSuccess(Void responseInfo) {
    _9
    }
    _9
    _9
    @Override
    _9
    public void onFailure(ErrorInfo errorInfo) {
    _9
    }
    _9
    });

    release

    Description

    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

    You can destroy the RtmClient instance as follows:


    _1
    void release();

    Basic usage


    _1
    rtmClient.release();

    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 join 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.

    RtmClient.renewToken

    Description

    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 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

    You can call the RtmClient.renewToken method as follows:


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

    ParametersTypeRequiredDefaultDescription
    tokenstringRequired-The newly generated Signaling token.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.renewToken("your_token", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    // Handle success
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    // Handle failure
    _11
    }
    _11
    });

    StreamChannel.renewToken

    Description

    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 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

    You can call the StreamChannel.renewToken method as follows:


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

    ParametersTypeRequiredDefaultDescription
    tokenstringRequired-The newly generated RTC token.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    streamChannel.renewToken("your_token", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    // Handle success
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    // Handle failure
    _11
    }
    _11
    });

    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 scenarios:

    • 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.
    • 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.

    subscribe

    Description

    By calling the subscribe 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.

    Information
    This method only applies to the message channel.

    Method

    You can call the subscribe method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    optionsSubscribeOptionsRequired-Options for subscribing to a channel.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • SubscribeOptions contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    withMessagebooleanOptionaltrueWhether to subscribe to message event notifications in the channel.
    withPresencebooleanOptionaltrueWhether to subscribe to presence event notifications in the channel.
    withMetadatabooleanOptionalfalseWhether to subscribe to storage event notifications in the channel.
    withLockbooleanOptionalfalseWhether to subscribe to lock event notifications in the channel.
    beQuietbooleanOptionalfalseWhether to enable silent mode. If you set this parameter to true, the SDK behaves as follows:
  • You still receive event notifications from other users.
  • 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.
  • When calling the getOnlineUsers method, your information is not included.
  • When calling the getUserChannels method, the channels that you subscribe to in silent mode are not included.
  • Basic usage


    _17
    SubscribeOptions options = new SubscribeOptions();
    _17
    options.setWithMessage(true);
    _17
    options.setWithPresence(true);
    _17
    options.setWithMetadata(false);
    _17
    options.setWithLock(false);
    _17
    _17
    rtmClient.subscribe("channel_name", options, new ResultCallback<Void>() {
    _17
    @Override
    _17
    public void onSuccess(Void responseInfo) {
    _17
    log(CALLBACK, "subscribe channel success");
    _17
    }
    _17
    _17
    @Override
    _17
    public void onFailure(ErrorInfo errorInfo) {
    _17
    log(ERROR, errorInfo.toString());
    _17
    }
    _17
    });

    unsubscribe

    Description

    If you no longer need to subscribe to a channel, you can call the unsubscribe 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.
    Information
    This method only applies to the message channel.

    Method

    You can call the unsubscribe method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.unsubscribe("channel_name", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "unsubscribe channel success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    createStreamChannel

    Description

    Before using a stream channel, you need to call the createStreamChannel 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.
    Information
    This method only applies to the stream channel.

    Method

    You can call the createStreamChannel method as follows:


    _1
    StreamChannel createStreamChannel(String channelName) throws Exception;

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.

    Basic usage


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

    Return Value

    The StreamChannel instance.

    join

    Description

    After successfully creating a stream channel, you can call the join 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.
    Information
    This method only applies to the stream channel.

    Method

    You can call the join method as follows:


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

    ParametersTypeRequiredDefaultDescription
    optionsJoinChannelOptionsRequired-Options for joining a channel.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The JoinChannelOptions data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    tokenStringRequired-An RTC token for joining a stream channel.
  • If you have enabled token authentication for your project, generate a temporary RTC token or obtain an RTC token generated by your token server.
  • 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.
  • withPresencebooleanOptionaltrueWhether to subscribe to presence event notifications in the channel.
    withMetadatabooleanOptionalfalseWhether to subscribe to storage event notifications in the channel.
    withLockbooleanOptionalfalseWhether to subscribe to lock event notifications in the channel.
    beQuietbooleanOptionalfalseWhether to enable silent mode. If you set this parameter to true, the SDK behaves as follows:
  • You still receive event notifications from other users.
  • 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.
  • When calling the getOnlineUsers method, your information is not included.
  • When calling the getUserChannels method, the channels that you subscribe to in silent mode are not included.
  • Basic usage


    _17
    JoinChannelOptions options = new JoinChannelOptions();
    _17
    options.setToken("yourToken")
    _17
    options.setWithPresence(true);
    _17
    options.setWithMetadata(false);
    _17
    options.setWithLock(false);
    _17
    _17
    streamChannel.join(options, new ResultCallback<Void>() {
    _17
    @Override
    _17
    public void onSuccess(Void responseInfo) {
    _17
    log(CALLBACK, "join stream channel success");
    _17
    }
    _17
    _17
    @Override
    _17
    public void onFailure(ErrorInfo errorInfo) {
    _17
    log(ERROR, errorInfo.toString());
    _17
    }
    _17
    });

    leave

    Description

    If you no longer need to stay in a channel, you can call the leave 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 join, 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.

    Information
    This method only applies to the stream channel.

    Method

    You can call the leave method as follows:


    _1
    void leave(ResultCallback<Void> resultCallback);

    ParametersTypeRequiredDefaultDescription
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    streamChannel.leave(new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "leave stream channel success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    release

    Description

    If you no longer need a channel, you can call the release method to destroy the corresponding stream channel instance and release resources. Calling the release method does not destroy the stream channel, and it can be re-joined later by calling createStreamChannel and join again.
    Information
    This method only applies to the stream channel. If you don't call leave to leave the channel before directly calling release to destroy the stream channel instance, the SDK automatically calls the leave and triggers the corresponding event.

    Method

    You can call the release method as follows:


    _1
    RtmErrorCode release();

    Basic usage


    _1
    RtmErrorCode errorCode = streamChannel.release();

    Return Value

    This operation returns the RtmErrorCode data type.

    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.

    Information
    Topics only exist in stream channels. Therefore, before using relevant features, you need to create the StreamChannel instance.

    joinTopic

    Description

    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.
    Information
    • 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 join method to join the channel.

    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.

    Method

    You can call the joinTopic method as follows:


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

    ParametersTypeRequiredDefaultDescription
    topicNameStringRequired-Topic name.
    optionsJoinTopicOptionsRequired-Options for joining a topic.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    messageQosRtmMessageQosOptionalUNORDEREDWhether the data transmitted in the topic is ordered. See RtmMessageQos.
    priorityRtmMessagePriorityOptionalNORMALThe priority of data transmission in the topic compared to other topics in the same channel. See RtmMessagePriority.
    topicMetaStringOptional-Adds additional metadata when joining the topic.
    syncWithMediabooleanOptionalfalseWhether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel.

    Basic usage


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

    publishTopicMessage

    Description

    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.

    Method

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


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


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

    ParametersTypeRequiredDefaultDescription
    topicNameStringRequired-Topic name.
    messageString\byte[]Required-Message payload.
    optionsTopicMessageOptionsRequired-Message options.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The TopicMessageOptions data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    sendTslongOptional0The 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.
    customTypeStringOptional-A user-defined field. Only supports string type.

    Basic usage

    Example 1: Send string messages to a specified channel.


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

    Example 2: Send byte messages to a specified channel.


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

    leaveTopic

    Description

    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.

    Method

    You can call the leaveTopic method as follows:


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

    ParametersTypeRequiredDefaultDescription
    topicNameStringRequired-Topic name.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    streamChannel.leaveTopic("topic_name", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "leave topic success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    subscribeTopic

    Description

    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.

    Method

    You can call the subscribeTopic method as follows:


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

    ParametersTypeRequiredDefaultDescription
    topicNameStringRequired-Topic name.
    optionsTopicOptionsRequired-Options for subscribing to a topic.
    resultCallbackResultCallback<SubscribeTopicResult>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the SubscribeTopicResult data.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    usersArrayList<String>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:

    PropertiesTypeDescription
    succeedUsersArrayList<String>A list of successfully subscribed users.
    failedUsersArrayList<String>A list of users that the SDK fails to subscribe to.

    Basic usage

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


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

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


    _12
    TopicOptions options = new TopicOptions();
    _12
    mStreamChannel.subscribeTopic("topic_name", options, new ResultCallback<SubscribeTopicResult>() {
    _12
    @Override
    _12
    public void onSuccess(SubscribeTopicResult responseInfo) {
    _12
    log(CALLBACK, "subscribe topic success");
    _12
    }
    _12
    _12
    @Override
    _12
    public void onFailure(ErrorInfo errorInfo) {
    _12
    log(ERROR, errorInfo.toString());
    _12
    }
    _12
    });

    unsubscribeTopic

    Description

    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

    You can call the unsubscribeTopic method as follows:


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

    ParametersTypeRequiredDefaultDescription
    topicNameStringRequired-Topic name.
    optionsTopicOptionsRequired-Options for unsubscribe from a topic.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    usersArrayList<String>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

    Example 1: Unsubscribe the specified message publisher in the topic


    _14
    TopicOptions options = new TopicOptions();
    _14
    options.users = new ArrayList<>(Arrays.asList("Tony","Bo"));
    _14
    _14
    streamChannel.unsubscribeTopic("topicName", options, new ResultCallback<Void>() {
    _14
    @Override
    _14
    public void onSuccess(Void responseInfo) {
    _14
    log(CALLBACK, "unsubscribe topic success");
    _14
    }
    _14
    _14
    @Override
    _14
    public void onFailure(ErrorInfo errorInfo) {
    _14
    log(ERROR, errorInfo.toString());
    _14
    }
    _14
    });

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


    _12
    TopicOptions options = new TopicOptions();
    _12
    streamChannel.unsubscribeTopic("topicName", options, new ResultCallback<Void>() {
    _12
    @Override
    _12
    public void onSuccess(Void responseInfo) {
    _12
    log(CALLBACK, "unsubscribe topic success");
    _12
    }
    _12
    _12
    @Override
    _12
    public void onFailure(ErrorInfo errorInfo) {
    _12
    log(ERROR, errorInfo.toString());
    _12
    }
    _12
    });

    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 publish 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 subscribe 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 publish 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.

    publish

    Description

    You can directly call the publish 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.
    Information
    The following practices can effectively improve the reliability of message transmission:
    • The message payload should be within 32 KB; otherwise, the sending will fail.
    • The upper limit of the rate at which messages are sent to a single channel is 30 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.

    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.

    Method

    You can call the publish method as follows:


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


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-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.
    messageString\byte[]Required-Message payload.
    optionsPublishOptionsRequired-Message options.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    customTypeStringOptional-A user-defined field. Only supports string type.

    Basic usage

    Example 1: Send string messages to a specified channel.


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

    Example 2: Send byte messages to a specified channel.


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

    Example 3: Send string messages to a specified user.


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

    Example 4: Send byte messages to a specified user.


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

    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:


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

    • Adding at any time:


      _16
      RtmEventListener listener = new RtmEventListener() {
      _16
      @Override
      _16
      public void onMessageEvent(MessageEvent event) {
      _16
      // User channel messages
      _16
      if (event.getChannelType() == RtmChannelType.USER) {
      _16
      log(CALLBACK, "receive message from " + event.getPublisherId() + ", message: " + event.getMessage().toString());
      _16
      }
      _16
      }
      _16
      _16
      @Override
      _16
      public void onConnectionStateChanged(String channelName, RtmConstants.RtmConnectionState state, RtmConstants.RtmConnectionChangeReason reason) {
      _16
      }
      _16
      };
      _16
      _16
      rtmClient.addEventListener(listener);
      _16
      // ...

    For information on how to add and set event listeners, see Event Listeners.

    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.
    Information
    Presence applies to both message channels and stream channels.

    getOnlineUsers

    Description

    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

    You can call the getOnlineUsers method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNamestringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    optionsGetOnlineUsersOptionsRequired-Query options.
    resultCallbackResultCallback<GetOnlineUsersResult>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the GetOnlineUsersResult query result.
  • Failure: Executes the onFailure method and return an error result.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    includeUserIdbooleanOptionaltrueWhether the returned result includes the user ID of online members.
    includeStatebooleanOptionalfalseWhether the returned result includes temporary state data of online users.
    pageStringOptional-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:

    PropertiesTypeDescription
    nextPageStringPage number of the next page. Confirm whether there is a next page:
  • A null value indicates that next page does not exist.
  • 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.
  • userStateListArrayList<UserState>List of online users and their temporary state information in a specified channel.
    totalOccupancylongThe 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:

    PropertiesTypeDescription
    userIdStringUser ID.
    statesHashMap<String, String>Temporary user state.

    Basic usage


    _22
    GetOnlineUsersOptions options = new GetOnlineUsersOptions();
    _22
    options.setIncludeUserId(true);
    _22
    options.setIncludeState(true);
    _22
    options.setPage("yourBookMark");
    _22
    _22
    rtmClient.getPresence().getOnlineUsers("channelName", RtmChannelType.MESSAGE, options, new ResultCallback<GetOnlineUsersResult>() {
    _22
    @Override
    _22
    public void onSuccess(GetOnlineUsersResult result) {
    _22
    log(CALLBACK, "getOnlineUsers success");
    _22
    for (UserState state : result.getUserStateList()) {
    _22
    log(INFO, "user id: " + state.getUserId());
    _22
    state.getStates().forEach((key, value) -> {
    _22
    log(INFO, "key: " + key + ", value: " + value);
    _22
    });
    _22
    }
    _22
    }
    _22
    _22
    @Override
    _22
    public void onFailure(ErrorInfo errorInfo) {
    _22
    log(ERROR, errorInfo.toString());
    _22
    }
    _22
    });

    getUserChannels

    Description

    In scenarios 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

    You can call the getUserChannels method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdstringRequired-User ID.
    resultCallbackResultCallback<ArrayList<ChannelInfo>>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the ArrayList<ChannelInfo> query result.
  • Failure: Executes the onFailure method.
  • ChannelInfo data type contains the following properties:

    PropertiesTypeDescription
    channelNameStringChannel name.
    channelTypeRtmChannelTypeChannel types. See RtmChannelType.

    Basic usage


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

    setState

    Description

    To meet different requirements in different business scenarios 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

    You can call the setState method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    itemsMap<String, String>Required-User state.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • StateItem data type contains the following properties:

    PropertiesTypeDescription
    keystringKey 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.
    valuestringValue of the user state.

    Basic usage


    _14
    HashMap<String, String> stateItems = new HashMap<String, String>();
    _14
    stateItems.put("mood", "pumped");
    _14
    _14
    rtmClient.getPresence().setState("channelName", RtmChannelType.MESSAGE, stateItems, new ResultCallback<Void>() {
    _14
    @Override
    _14
    public void onSuccess(Void responseInfo) {
    _14
    log(CALLBACK, "set state success");
    _14
    }
    _14
    _14
    @Override
    _14
    public void onFailure(ErrorInfo errorInfo) {
    _14
    log(ERROR, errorInfo.toString());
    _14
    }
    _14
    });

    getState

    Description

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

    Method

    You can call the getState method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    userIdStringRequired-User ID.
    resultCallbackResultCallback<UserState>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the UserState query result.
  • Failure: Executes the onFailure method.
  • The UserState data type contains the following properties:

    PropertiesTypeDescription
    userIdStringUser ID.
    statesHashMap<String, String>Temporary user state.

    Basic usage


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

    removeState

    Description

    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.

    Method

    You can call the removeState method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    keysArrayList<String>Required-List of keys to be deleted. If you do not provide this property, the SDK removes all states.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    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.

    setChannelMetadata

    Description

    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.

    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 scenario:

    • 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

    You can call the setChannelMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel type. See RtmChannelType.
    dataMetadataRequired-Metadata item. See Metadata.
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    lockNameStringRequired-Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The MetadataOptions data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _25
    // Create a metadata instance
    _25
    Metadata metadata = new Metadata();
    _25
    // Set the Major Revision
    _25
    metadata.setMajorRevision(174298270);
    _25
    // Add metadata item
    _25
    ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
    _25
    items.add(new MetadataItem("Apple", "100", 174298200));
    _25
    items.add(new MetadataItem("Banana", "200", 174298100));
    _25
    metadata.setItems(items);
    _25
    // Record who and when set the metadata
    _25
    MetadataOptions options = new MetadataOptions();
    _25
    options.setRecordTs(true);
    _25
    options.setRecordUserId(true);
    _25
    _25
    rtmClient.getStorage().setChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, options, "lockName", new ResultCallback<Void>() {
    _25
    @Override
    _25
    public void onSuccess(Void responseInfo) {
    _25
    log(CALLBACK, "set channel metadata success");
    _25
    }
    _25
    _25
    @Override
    _25
    public void onFailure(ErrorInfo errorInfo) {
    _25
    log(ERROR, errorInfo.toString());
    _25
    }
    _25
    });

    getChannelMetadata

    Description

    The getChannelMetadata method gets the metadata of the specified channel.

    Method

    You can call the getChannelMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel type. See RtmChannelType.
    resultCallbackResultCallback<Metadata>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the Metadata query result.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    removeChannelMetadata

    Description

    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.

    Method

    You can call the removeChannelMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel type. See RtmChannelType.
    dataMetadataRequired-Metadata item. See Metadata .
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    lockNameStringRequired-Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The MetadataOptions data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _23
    // Create a metadata instance
    _23
    Metadata metadata = new Metadata();
    _23
    // Set the Major Revision
    _23
    metadata.setMajorRevision(174298270);
    _23
    // Add a metadata item
    _23
    MetadataItem item = new MetadataItem();
    _23
    item.setKey("Apple");
    _23
    item.setRevision(174298200);
    _23
    metadata.getItems().add(item);
    _23
    //Record who and when set the metadata
    _23
    MetadataOptions options = new MetadataOptions();
    _23
    _23
    rtmClient.getStorage().removeChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, options, "", new ResultCallback<Void>() {
    _23
    @Override
    _23
    public void onSuccess(Void responseInfo) {
    _23
    log(CALLBACK, "remove channel metadata success");
    _23
    }
    _23
    _23
    @Override
    _23
    public void onFailure(ErrorInfo errorInfo) {
    _23
    log(ERROR, errorInfo.toString());
    _23
    }
    _23
    });

    updateChannelMetadata

    Description

    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.

    Information
    You cannot use this method to update metadata items which do not exist.

    Method

    You can call the updateChannelMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel type. See RtmChannelType.
    dataMetadataRequired-Metadata item. See Metadata .
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    lockNameStringRequired-Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _21
    // Create a metadata instance
    _21
    Metadata metadata = new Metadata();
    _21
    // Set the Major Revision
    _21
    metadata.setMajorRevision(174298270);
    _21
    // Add metadata item
    _21
    ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
    _21
    items.add(new MetadataItem("Apple", "120", 174298200));
    _21
    items.add(new MetadataItem("Banana", "220", 174298100));
    _21
    metadata.setItems(items);
    _21
    _21
    rtmClient.getStorage().updateChannelMetadata("channelName", RtmChannelType.MESSAGE, metadata, new MetadataOptions(true, true), "lockName", new ResultCallback<Void>() {
    _21
    @Override
    _21
    public void onSuccess(Void responseInfo) {
    _21
    log(CALLBACK, "update channel metadata success");
    _21
    }
    _21
    _21
    @Override
    _21
    public void onFailure(ErrorInfo errorInfo) {
    _21
    log(ERROR, errorInfo.toString());
    _21
    }
    _21
    });

    setUserMetadata

    Description

    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.

    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 scenario:

    • 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

    You can call the setUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    dataMetadataRequired-Metadata item. See Metadata .
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _21
    // Create a metadata instance
    _21
    Metadata metadata = new Metadata();
    _21
    // Set the Major Revision
    _21
    metadata.setMajorRevision(174298270);
    _21
    // Add metadata item
    _21
    ArrayList<MetadataItem> items = new ArrayList<MetadataItem>();
    _21
    items.add(new MetadataItem("Name", "Tony", 174298200));
    _21
    items.add(new MetadataItem("Mute", "true", 174298100));
    _21
    metadata.setItems(items);
    _21
    _21
    rtmClient.getStorage().setUserMetadata("userName", metadata, new MetadataOptions(true, true), new ResultCallback<Void>() {
    _21
    @Override
    _21
    public void onSuccess(Void responseInfo) {
    _21
    log(CALLBACK, "set user metadata success");
    _21
    }
    _21
    _21
    @Override
    _21
    public void onFailure(ErrorInfo errorInfo) {
    _21
    log(ERROR, errorInfo.toString());
    _21
    }
    _21
    });

    getUserMetadata

    Description

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

    Method

    You can call the getUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    resultCallbackResultCallback<Metadata>Required-Invocation result callback:
  • Success: Executes the onSuccess method and return the Metadata query result.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    removeUserMetadata

    Description

    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.

    Method

    You can call the removeUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    dataMetadataRequired-Metadata item. See Metadata .
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The options parameter contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _23
    // Create a metadata instance
    _23
    Metadata metadata = new Metadata();
    _23
    // Set the Major Revision
    _23
    metadata.setMajorRevision(174298270);
    _23
    // Add metadata item
    _23
    MetadataItem item = new MetadataItem();
    _23
    item.setKey("Mute");
    _23
    item.setRevision(174298100);
    _23
    metadata.getItems().add(item);
    _23
    // Record who and when set the metadata
    _23
    MetadataOptions options = new MetadataOptions();
    _23
    _23
    rtmClient.getStorage().removeUserMetadata("Tony", metadata, options, new ResultCallback<Void>() {
    _23
    @Override
    _23
    public void onSuccess(Void responseInfo) {
    _23
    log(CALLBACK, "remove user metadata success");
    _23
    }
    _23
    _23
    @Override
    _23
    public void onFailure(ErrorInfo errorInfo) {
    _23
    log(ERROR, errorInfo.toString());
    _23
    }
    _23
    });

    updateUserMetadata

    Description

    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.
    Information
    You cannot use this method to update metadata items which do not exist.

    Method

    You can call the updateUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    dataMetadataRequired-Metadata item. See Metadata .
    optionsMetadataOptionsRequired-Options for setting the channel metadata.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • The MetadataOptions data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    recordTsbooleanOptionalfalseWhether to record the timestamp of the edits.
    recordUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

    Basic usage


    _22
    // Create a metadata instance
    _22
    Metadata metadata = new Metadata();
    _22
    // Set the Major Revision
    _22
    metadata.setMajorRevision(174298270);
    _22
    // Add a metadata item
    _22
    metadata.getItems().add(new MetadataItem("Name", "Tony", 174298200));
    _22
    // Record who and when set the metadata
    _22
    MetadataOptions options = new MetadataOptions();
    _22
    options.setRecordTs(true);
    _22
    options.setRecordUserId(true);
    _22
    _22
    rtmClient.getStorage().updateUserMetadata("Tony", metadata, options, new ResultCallback<Void>() {
    _22
    @Override
    _22
    public void onSuccess(Void responseInfo) {
    _22
    log(CALLBACK, "update user metadata success");
    _22
    }
    _22
    _22
    @Override
    _22
    public void onFailure(ErrorInfo errorInfo) {
    _22
    log(ERROR, errorInfo.toString());
    _22
    }
    _22
    });

    subscribeUserMetadata

    Description

    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.

    Method

    You can call the subscribeUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.getStorage().subscribeUserMetadata("Tony", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "subscribe user metadata success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    unsubscribeUserMetadata

    Description

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

    Method

    You can call the unsubscribeUserMetadata method as follows:


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

    ParametersTypeRequiredDefaultDescription
    userIdStringRequired-User ID.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.getStorage().unsubscribeUserMetadata("Tony", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "unsubscribe user metadata success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    Metadata

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

    PropertiesTypeRequiredDefaultDescription
    majorRevisionlongOptional-1The version control switch:
  • -1: Disable the version verification.
  • > 0: Enable the version verification. The operation can only be performed if the target version number matches this value.
  • itemsArrayList<MetadataItem>OptionalnullMetadata items.

    The MetadataItem data type contains the following properties:

    PropertiesTypeRequiredDefaultDescription
    keyStringOptional-Key.
    valueStringOptional-Value.
    authorUserIdStringOptional-The user ID of the editor. This value is read-only and does not support writing.
    revisionlongOptional-1
  • Returns the real version number in read operations.
  • Serves as a version control switch in write operations:
    • -1: Disable the version verification.
    • > 0: Enable version verification, only perform the operation if the target version number matches this value.
    updateTslongOptional0Update timestamp. This value is read-only and does not support writing.

    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.

    Information
    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.

    setLock

    Description

    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.

    Method

    You can call the setLock method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    lockNameStringRequired-Lock name.
    ttllongRequired-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.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    acquireLock

    Description

    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.

    Method

    You can call the acquireLock method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    lockNameStringRequired-Lock name.
    retrybooleanRequired-If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    releaseLock

    Description

    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.

    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

    You can call the releaseLock method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    lockNameStringRequired-Lock name.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.getLock().releaseLock("chat_room", RtmChannelType.STREAM, "my_lock", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "release lock success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    revokeLock

    Description

    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.

    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

    You can call the revokeLock method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    lockNameStringRequired-Lock name.
    ownerStringRequired-The ID of the user who has a lock.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


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

    getLocks

    Description

    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 getLocks method on the client.

    Method

    You can call the getLocks method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    resultCallbackResultCallback<ArrayList<LockDetail>>Required-
  • Success: Executes the onSuccess method and return the LockDetail data type.
  • Failure: Executes the onFailure method.
  • The LockDetail data type contains the following properties:

    PropertiesTypeDescription
    lockNameStringLock name.
    lockOwnerStringThe ID of the user who has a lock.
    ttlintThe 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


    _15
    rtmClient.getLock().getLocks("chat_room", RtmChannelType.STREAM, new ResultCallback<ArrayList<LockDetail>>() {
    _15
    @Override
    _15
    public void onSuccess(ArrayList<LockDetail> details) {
    _15
    log(CALLBACK, "get channel locks success");
    _15
    _15
    for (LockDetail detail : details) {
    _15
    log(INFO, "lock name: " + detail.lockName + ", lock owner: " + detail.lockOwner + ", ttl: " + detail.ttl);
    _15
    }
    _15
    }
    _15
    _15
    @Override
    _15
    public void onFailure(ErrorInfo errorInfo) {
    _15
    log(ERROR, errorInfo.toString());
    _15
    }
    _15
    });

    removeLock

    Description

    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.

    Method

    You can call the removeLock method as follows:


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

    ParametersTypeRequiredDefaultDescription
    channelNameStringRequired-Channel name.
    channelTypeRtmChannelTypeRequired-Channel types. See RtmChannelType.
    lockNameStringRequired-Lock name.
    resultCallbackResultCallback<Void>Required-Invocation result callback:
  • Success: Executes the onSuccess method.
  • Failure: Executes the onFailure method.
  • Basic usage


    _11
    rtmClient.getLock().removeLock("chat_room", RtmChannelType.STREAM, "my_lock", new ResultCallback<Void>() {
    _11
    @Override
    _11
    public void onSuccess(Void responseInfo) {
    _11
    log(CALLBACK, "remove lock success");
    _11
    }
    _11
    _11
    @Override
    _11
    public void onFailure(ErrorInfo errorInfo) {
    _11
    log(ERROR, errorInfo.toString());
    _11
    }
    _11
    });

    Enumerated types

    Enum

    RtmAreaCode

    The region for connection, which is the region where the server the SDK connects to is located.
    ValueDescription
    CN0x00000001: Mainland China.
    NA0x00000002: North America.
    EU0x00000004: Europe.
    AS0x00000008: Asia, excluding Mainland China.
    JP0x00000010: Japan.
    IN0x00000020: India.
    GLOB0xFFFFFFFF: Global.

    RtmChannelType

    Channel types.
    ValueDescription
    MESSAGE1: Message channel.
    STREAM2: Stream channel.
    USER3: User Channel.

    RtmConnectionChangeReason

    Reasons causing the change of the connection state.
    ValueDescription
    CONNECTING0: The SDK is connecting with the server.
    JOIN_SUCCESS1: The SDK has joined the channel successfully.
    INTERRUPTED2: The connection between the SDK and the server is interrupted.
    BANNED_BY_SERVER3: The connection between the SDK and the server is banned by the server.
    JOIN_FAILED4: 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_CHANNEL5: The SDK has left the channel.
    INVALID_APP_ID6: The connection failed because the App ID is not valid.
    INVALID_CHANNEL_NAME7: The connection failed because the channel name is not valid.
    INVALID_TOKEN8: The connection failed because the token is not valid.
    TOKEN_EXPIRED9: The connection failed because the token is expired.
    REJECTED_BY_SERVER10: The connection is rejected by server.
    SETTING_PROXY_SERVER11: The connection state changed to reconnecting because the SDK has set a proxy server.
    RENEW_TOKEN12: The connection state changed because the token is renewed.
    CLIENT_IP_ADDRESS_CHANGED13: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed.
    KEEP_ALIVE_TIMEOUT14: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting.
    REJOIN_SUCCESS15: The user has rejoined the channel successfully.
    LOST16: The connection between the SDK and the server is lost.
    ECHO_TEST17: The connection state changes due to the echo test.
    CLIENT_IP_ADDRESS_CHANGED_BY_USER18: The local IP address was changed by the user. The connection state changes to reconnecting.
    SAME_UID_LOGIN19: The user joined the same channel from different devices with the same UID.
    TOO_MANY_BROADCASTERS20: The number of hosts in the channel has reached the upper limit.
    LICENSE_VALIDATION_FAILURE21: License validation failure.
    CERTIFICATION_VERIFY_FAILURE22: The server certificate verification has encountered an error.
    STREAM_CHANNEL_NOT_AVAILABLE23: The stream channel does not exist.
    INCONSISTENT_APPID24: The App ID does not match the token.
    LOGIN_SUCCESS10001: The SDK logs in to the Signaling system.
    LOGOUT10002: The SDK logs out from the Signaling system.
    PRESENCE_NOT_READY10003: 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

    SDK connection states.
    ValueDescription
    DISCONNECTED1: The SDK has disconnected with the server.
    CONNECTING2: The SDK is connecting with the server.
    CONNECTED3: The SDK has connected with the server.
    RECONNECTING4: The connection is lost. The SDK is reconnecting with the server.
    FAILED5: The SDK failed to connect with the server.

    RtmEncryptionMode

    Encryption mode.
    ValueDescription
    NONE0: No encryption.
    AES_128_GCM1: AES-128-GCM mode.
    AES_256_GCM2: AES-256-GCM mode.

    RtmLockEventType

    Lock event type.
    ValueDescription
    SNAPSHOT1: The snapshot of the lock when the user joined the channel.
    SET2: The lock is set.
    REMOVED3: The lock is removed.
    ACQUIRED4: The lock is acquired.
    RELEASED5: The lock is released.
    EXPIRED6: The lock expired.

    RtmLogLevel

    Log output levels.
    ValueDescription
    NONE0x0000: No log.
    INFO0x0001: Output the log at the FATAL, ERROR, WARN, or INFO level. We recommend you set to this value.
    WARN0x0002: Output the log at the FATAL, ERROR, WARN level.
    ERROR0x0004: Output the log at the FATAL, ERROR level.
    FATAL0x0008: Output the log at the FATAL level.

    RtmMessagePriority

    Message priority.
    ValueDescription
    HIGHEST0: Highest.
    HIGH1: High.
    NORMAL4: Normal.
    LOW8: Low.

    RtmMessageQos

    QoS guarantee when sending topic messages.
    ValueDescription
    UNORDERED0: Message data is not guaranteed to arrive in order.
    ORDERED1: Message data arrives in order.

    RtmMessageType

    Message type.
    ValueDescription
    BINARY0: Binary type.
    STRING1: String type.

    RtmPresenceEventType

    Presence event type.
    ValueDescription
    SNAPSHOT1: The snapshot of the presence when the user joined the channel.
    INTERVAL2: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time.
    REMOTE_JOIN3: A remote user joined the channel.
    REMOTE_LEAVE4: A remote user left the channel.
    REMOTE_TIMEOUT5: A remote user's connection timed out.
    REMOTE_STATE_CHANGED6: A remote user's temporary state changed.
    ERROR_OUT_OF_SERVICE7: The user did not enable presence when joining the channel.

    RtmLinkOperation

    Operation type.
    ValueDescription
    LOGIN0: The user logins to the Signaling system.
    LOGOUT1: The user logouts of the Signaling system.
    JOIN2: The user joins in a stream channel.
    LEAVE3: The user leaves a stream channel.
    SERVER_REJECT4: The Signaling server reject the connection.
    AUTO_RECONNECT5: The SDK is automatically reconnecting to the Signaling server.
    RECONNECTED6: The SDK is reconnected to the Signaling server.
    HEARTBEAT_TIMEOUT7: The Signaling server does not receive the heartbeat packet within the specified timeout period.
    SERVER_TIMEOUT8: The Signaling server has timed out.
    NETWORK_CHANGE9: The network status changes.

    RtmLinkState

    Link state type.
    ValueDescription
    IDLE0: The init state.
    CONNECTING1: Connecting.
    CONNECTED2: Connected.
    DISCONNECTED3: Disconnected.
    SUSPENDED4: Suspended.
    FAILED5: Failed.

    RtmProtocolType

    Protocol type.
    ValueDescription
    TCP_UDP0: Both TCP and UDP protocols.
    TCP_ONLY1: Only TCP protocol.

    RtmServiceType

    Service type
    ValueDescription
    MESSAGEThe foundational services comprise the message channel, user channel, presence, storage, and lock services.
    STREAMThe stream channel service.
    Information

    To fully utilize all services offered by Signaling, use bitwise operations to simultaneously configure two service types.

    RtmProxyType

    Proxy type.
    ValueDescription
    NONE0: Do not enable the proxy.
    HTTP1: Enable the proxy for the HTTP protocol.
    CLOUD_TCP2: Enable cloud proxy for the TCP protocol.

    RtmStorageEventType

    Storage event type.
    ValueDescription
    SNAPSHOT1: 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.
    SET2: Occurs when calling setChannelMetadata or setUserMetadata.
    Caution
    This event only occurs in incremental data update mode.
    UPDATE3: Occurs when calling methods to set, update, or delete the channel metadata or user metadata.
    REMOVE4: Occurs when calling removeChannelMetadata or removeUserMetadata.
    Caution
    This event only occurs in incremental data update mode.

    RtmStorageType

    Storage type.
    ValueDescription
    USER1: User metadata event.
    CHANNEL2: Channel metadata event.

    RtmTopicEventType

    Topic event type.
    ValueDescription
    SNAPSHOT1: The snapshot of the topic when the user joined the channel.
    REMOTE_JOIN2: A remote user joined the channel.
    REMOTE_LEAVE3: A remote user left the channel.

    Troubleshooting

    Refer to the following information for troubleshooting API calls.

    ErrorInfo

    PropertiesTypeDescription
    errorCodeRtmErrorCodeError code for this operation.
    reasonStringError reason for this operation.
    operationStringOperation 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

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

    Error codeError descriptionCause and solution
    0OKCorrect call
    -10001NOT_INITIALIZEDThe SDK is not initialized. Please initialize the RtmClient instance by calling the create method before performing other operations.
    -10002NOT_LOGINThe user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first.
    -10003INVALID_APP_IDInvalid App ID:
    - Check that the App ID is correct.
    - Ensure that Signaling has been activated for the App ID.
    -10005INVALID_TOKENInvalid Token:
    - The token is invalid, check whether the Token Provider generates a valid Signaling Token.
    -10006INVALID_USER_IDInvalid User ID:
    - Check if user ID is empty.
    - Check if the user ID contains illegal characters.
    -10007INIT_SERVICE_FAILEDSDK initialization failed. Please reinitialize by calling the create method.
    -10008INVALID_CHANNEL_NAMEInvalid channel name:
    - Check if the channel name is empty.
    - Check if the channel name contains illegal characters.
    -10009TOKEN_EXPIREDToken expired. Call renewToken to reacquire the Token.
    -10010LOGIN_NO_SERVER_RESOURCESServer resources are limited. It is recommended to log in again.
    -10011LOGIN_TIMEOUTLogin timeout. Check whether the current network is stable and switch to a stable network environment.
    -10012LOGIN_REJECTEDSDK login rejected by the server:
    - Check tha Signaling is activated on your App ID.
    - Check if the token or userId is banned.
    -10013LOGIN_ABORTEDSDK login interrupted due to unknown problem:
    - Check that the current network is stable and switch to a stable network environment.
    - The current userId is logged in.
    -10014INVALID_PARAMETERInvalid parameter. Please check if the parameters you provided are correct.
    -10015LOGIN_NOT_AUTHORIZEDNo RTM service permissions. Check that the console opens Signaling services.
    -10016INCONSISTENT_APPIDInconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent.
    -10017DUPLICATE_OPERATIONDuplicate operation.
    -10018INSTANCE_ALREADY_RELEASEDRepeat rtm instantiation or RTMStreamChannel instantiation.
    -10019INVALID_CHANNEL_TYPEInvalid channel type. The SDK only supports the following channel types. Please use the correct value:
    - MESSAGE: Message Channel
    - STREAM: Stream Channel
    - USER: User Channel
    -10020INVALID_ENCRYPTION_PARAMETERMessage encryption parameters are invalid.
    • Check that the encryption key generated is a String.
    • Check that the generated encryption salt is Uint8Array type and that the length is 32 bytes.
    • Check that the encryption method matches the encryption key and the encryption salt.
    -10021OPERATION_RATE_EXCEED_LIMITATIONChannel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second.
    -10022SERVICE_NOT_SUPPORTEDThe 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.
    -10023LOGIN_CANCELEDThe login operation has been canceled. Possible reasons are as follows:
    • 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.
    • Calling the logout method to log out before successfully logging in.
    -10024INVALID_PRIVATE_CONFIGThe private deployment parameter settings are invalid. Please check whether the service type and server address you set in RtmPrivateConfig are valid.
    -10025NOT_CONNECTEDNot connected to the Signaling server.
    -11001CHANNEL_NOT_JOINEDThe user has not joined the channel:
    - The user is not online, offline or has not joined the channel
    - Check for typos in userId.
    -11002CHANNEL_NOT_SUBSCRIBEDThe user has not subscribed to the channel:
    - The user is not online, offline or has not joined the channel
    - Check for typos in userId.
    -11003CHANNEL_EXCEED_TOPIC_USER_LIMITATIONThe number of subscribers to this topic exceeds the limit.
    -11004CHANNEL_IN_REUSEIn co-channel mode, RTM released the Stream Channel.
    -11005CHANNEL_INSTANCE_EXCEED_LIMITATIONThe number of created or subscribed channels exceeds the limit. See API usage limits for details.
    -11006CHANNEL_IN_ERROR_STATEChannel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel.
    -11007CHANNEL_JOIN_FAILEDFailed to join this channel:
    - Check if the number of joined channels exceeds the limit.
    - Check if the channel name is illegal.
    - Check if the network is disconnected.
    -11008CHANNEL_INVALID_TOPIC_NAMEInvalid topic name:
    - Check whether the topic name contains illegal characters.
    - Check if the topic name is empty.
    -11009CHANNEL_INVALID_MESSAGEInvalid message. Check whether the message type is legal, Signaling only supports string, Uint8Array type messages.
    -11010CHANNEL_MESSAGE_LENGTH_EXCEED_LIMITATIONMessage length exceeded limit. Check if the message payload size exceeds the limit:
    - Message Channel single message package limit is 32 KB.
    - Stream Channel single message package limit is 1 KB.
    -11011CHANNEL_INVALID_USER_LISTInvalid user list:
    - Check if the user list is empty.
    - Check if the user list contains invalid entries.
    -11012CHANNEL_NOT_AVAILABLEInvalid user list:
    - Check if the user list is empty
    - Check if the user list contains illegal items.
    -11013CHANNEL_TOPIC_NOT_SUBSCRIBEDThe topic is not subscribed.
    -11014CHANNEL_EXCEED_TOPIC_LIMITATIONThe number of topics exceeds the limit.
    -11015CHANNEL_JOIN_TOPIC_FAILEDFailed to join this topic. Check whether the number of added topics exceeds the limit.
    -11016CHANNEL_TOPIC_NOT_JOINEDThe topic has not been joined. To send a message, you need to join the Topic first.
    -11017CHANNEL_TOPIC_NOT_EXISTThe topic does not exist. Check that the topic name is correct.
    -11018CHANNEL_INVALID_TOPIC_METAThe meta parameters in the topic are invalid. Check if the meta parameter exceeds 256 bytes.
    -11019CHANNEL_SUBSCRIBE_TIMEOUTChannel subscription timed out. Check for broken connections.
    -11020CHANNEL_SUBSCRIBE_TOO_FREQUENTThe 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.
    -11021CHANNEL_SUBSCRIBE_FAILEDChannel subscription failed. Check if the number of subscribed channels exceeds the limit.
    -11022CHANNEL_UNSUBSCRIBE_FAILEDFailed to unsubscribe from the channel. Check if the connection is disconnected.
    -11023CHANNEL_ENCRYPT_MESSAGE_FAILEDMessage encryption failed:
    - Check that the cipherKey is valid.
    - Check that the salt is valid.
    - Check if encryptionMode mode matches the cipherKey and salt.
    -11024CHANNEL_PUBLISH_MESSAGE_FAILEDMessage publishing failed. Check for broken connections.
    -11026CHANNEL_PUBLISH_MESSAGE_TIMEOUTMessage publishing timed out. Check for broken connections.
    -11027CHANNEL_NOT_CONNECTEDThe SDK is disconnected from the Signaling server. Please log in again.
    -11028CHANNEL_LEAVE_FAILEDFailed to leave the channel. Check for broken connections.
    -11029CHANNEL_CUSTOM_TYPE_LENGTH_OVERFLOWCustom type length overflow. The length of the customType field must to be within 32 characters.
    -11030CHANNEL_INVALID_CUSTOM_TYPEcustomType field is invalid. Check the customType field for illegal characters.
    -11031CHANNEL_UNSUPPORTED_MESSAGE_TYPEMessage type is not supported.
    -11032CHANNEL_PRESENCE_NOT_READYPresence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel.
    -11033CHANNEL_RECEIVER_OFFLINEWhen sending a user message, the remote user is offline:
    - Check if the user ID set when calling the method is correct.
    - Check if the remote user is logged in and online.
    -11034CHANNEL_JOIN_CANCELEDThe join channel operation has been canceled. After calling the join 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.
    -12001STORAGE_OPERATION_FAILEDStorage operation failed.
    -12002STORAGE_METADATA_ITEM_EXCEED_LIMITATIONThe number of Storage Metadata Items exceeds the limit.
    -12003STORAGE_INVALID_METADATA_ITEMInvalid Metadata Item.
    -12004STORAGE_INVALID_ARGUMENTInvalid argument.
    -12005STORAGE_INVALID_REVISIONInvalid Revision parameter.
    -12006STORAGE_METADATA_LENGTH_OVERFLOWMetadata overflows.
    -12007STORAGE_INVALID_LOCK_NAMEInvalid Lock name.
    -12008STORAGE_LOCK_NOT_ACQUIREDThe Lock was not acquired.
    -12009STORAGE_INVALID_KEYInvalid Metadata key.
    -12010STORAGE_INVALID_VALUEInvalid metadata value.
    -12011STORAGE_KEY_LENGTH_OVERFLOWMetadata key length overflow.
    -12012STORAGE_VALUE_LENGTH_OVERFLOWMetadata value length overflow.
    -12013STORAGE_DUPLICATE_KEYDuplicate Metadata Item key.
    -12014STORAGE_OUTDATED_REVISIONOutdated Revision parameter.
    -12015STORAGE_NOT_SUBSCRIBEThis channel is not subscribed.
    -12016STORAGE_INVALID_METADATA_INSTANCEMetadata instance does not exist. Please create a Metadata instance.
    -12017STORAGE_SUBSCRIBE_USER_EXCEED_LIMITATIONThe number of subscribers exceeds the limit.
    -12018STORAGE_OPERATION_TIMEOUTStorage operation timed out.
    -12019STORAGE_NOT_AVAILABLEThe Storage service is not available.
    -13001PRESENCE_NOT_CONNECTEDThe user is not connected to the system.
    -13002PRESENCE_NOT_WRITABLEPresence service is unavailable.
    -13003PRESENCE_INVALID_ARGUMENTInvalid argument.
    -13004PRESENCE_CACHED_TOO_MANY_STATESThe temporary user state cached before joining the channel exceeds the limit. See API usage limits for details.
    -13005PRESENCE_STATE_COUNT_OVERFLOWThe number of temporary user state key/value pairs exceeds the limit. See API usage limits for details.
    -13006PRESENCE_INVALID_STATE_KEYInvalid state key.
    -13007PRESENCE_INVALID_STATE_VALUEInvalid state value.
    -13008PRESENCE_STATE_KEY_SIZE_OVERFLOWPresence key length overflow.
    -13009PRESENCE_STATE_VALUE_SIZE_OVERFLOWPresence value overflow
    -13010PRESENCE_STATE_DUPLICATE_KEYRepeated state key.
    -13011PRESENCE_USER_NOT_EXISTThe user does not exist.
    -13012PRESENCE_OPERATION_TIMEOUTPresence operation timed out.
    -13013PRESENCE_OPERATION_FAILEDPresence operation failed.
    -14001LOCK_OPERATION_FAILEDLock operation failed.
    -14002LOCK_OPERATION_TIMEOUTLock operation timed out.
    -14003LOCK_OPERATION_PERFORMINGLock operation in progress.
    -14004LOCK_ALREADY_EXISTLock already exists.
    -14005LOCK_INVALID_NAMEInvalid Lock name.
    -14006LOCK_NOT_ACQUIREDThe Lock was not acquired.
    -14007LOCK_ACQUIRE_FAILEDFailed to acquire the Lock.
    -14008LOCK_NOT_EXISTThe Lock does not exist.
    -14009LOCK_NOT_AVAILABLELock service is not available.

    Signaling