Channel Management

getUserInfoByUid

Gets user information by passing in a user ID.

public abstract int getUserInfoByUid(int uid, UserInfo userInfo);

After a remote user joins the channel, the SDK retrieves the user's ID and account and caches them in a mapping table, while triggering the onUserInfoUpdated callback on the local client. After receiving this callback, you can call the getUserInfoByUid method and pass in the user ID to obtain the user account of the specified user from the UserInfo object.

Timing

Call this method after receiving the onUserInfoUpdated callback.

Parameters

uid
uid, representing the user ID.
userInfo
Input and output parameter. The UserInfo object identifying user information. See UserInfo.

Return Values

  • 0: Success.
  • < 0: Failure.

getUserInfoByUidEx

Gets the user information by user ID.

public abstract int getUserInfoByUidEx(int uid, UserInfo userInfo, RtcConnection connection);

After a remote user joins a channel, the SDK retrieves the user's ID and user account and caches them in a mapping table. At the same time, it triggers the onUserInfoUpdated callback on the local client. After receiving this callback, you can call getUserInfoByUidEx and pass in the user ID to get the user account from the UserInfo object.

Scenario

Applicable in multi-channel scenarios.

Parameters

uid
User ID.
userInfo
The object that identifies the user information. See UserInfo.
connection
Connection information. See RtcConnection.

Return Values

  • The UserInfo object, if the method call succeeds.
  • null, if the method call fails.

getUserInfoByUserAccount

Gets user information by passing in a user account.

public abstract int getUserInfoByUserAccount(String userAccount, UserInfo userInfo);

After a remote user joins the channel, the SDK retrieves the user's ID and account and caches them in a mapping table, while triggering the onUserInfoUpdated callback on the local client. After receiving this callback, you can call the getUserInfoByUserAccount method and pass in the user account to obtain the specified user's information from the UserInfo object.

Parameters

userAccount
The user account.
userInfo
The UserInfo object identifying user information. See UserInfo.

Return Values

  • 0: Success.
  • < 0: Failure.

getUserInfoByUserAccountEx

Gets user information by user account.

public abstract int getUserInfoByUserAccountEx(String userAccount, UserInfo userInfo, RtcConnection connection);

After a remote user joins the channel, the SDK retrieves the user ID and user account of the remote user and caches them in a mapping table, while triggering the onUserInfoUpdated callback on the local client. After receiving this callback, you can call getUserInfoByUserAccountEx and pass the user account to obtain the user's information from the UserInfo object.

Scenario

This method is applicable in multi-channel scenarios.

Parameters

userAccount
User account.
userInfo
Input and output parameter used to identify user information. See UserInfo.
connection
Connection information. See RtcConnection.

Return Values

  • 0: Success.
  • < 0: Failure.

joinChannel [1/2]

Joins a channel.

public abstract int joinChannel(String token, String channelId, String optionalInfo, int uid);

By default, the user subscribes to all other users' audio and video streams in the channel, which incurs usage and billing. To stop subscribing to specific or all remote streams, call muteRemoteAudio/VideoStream or muteAllRemoteAudio/VideoStreams.

Note:
  • This method only supports joining one channel at a time.
  • Users with different App IDs cannot communicate.
  • Before joining a channel, ensure the App ID used to generate the token matches the App ID passed in create [2/2], or the join may fail.

Timing

Call this method after calling create [2/2].

Parameters

token
The token generated on your server for authentication.
Note:
  • (Recommended) If your project uses the secure mode (App ID + Token), this parameter is required.
  • If only test mode is enabled (App ID only), this parameter is optional. The user will automatically leave the channel after 24 hours.
  • If you need to join multiple channels or switch between them, Agora recommends using a wildcard token to avoid requesting a new token each time.
channelId
Channel name. Users with the same App ID and channel name join the same channel for audio/video interaction. The string must be less than 64 bytes. Supported characters (89 total):
  • Lowercase letters: a to z.
  • Uppercase letters: A to Z.
  • Numbers: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
optionalInfo
(Optional) Reserved parameter.
uid
User ID. Used to identify the user in the channel for real-time audio/video interaction. You must set and manage the user ID yourself, ensuring uniqueness within the same channel. This parameter is a 32-bit signed integer, range: -2^31 to 2^31-1. If not specified (or set to 0), the SDK assigns a random user ID and returns it via the onJoinChannelSuccess callback. Your app must record and maintain this ID; the SDK does not store it.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter. For example, invalid token, uid not set as an integer, or invalid member values in ChannelMediaOptions. Pass valid parameters and rejoin the channel.
    • -3: RtcEngine initialization failed. Reinitialize the RtcEngine object.
    • -7: RtcEngine object is not initialized. Initialize the RtcEngine object before calling this method.
    • -8: Internal state error of RtcEngine. Common cause: calling this method to join a channel after startEchoTest without calling stopEchoTest. Call stopEchoTest before this method.
    • -17: Join request rejected. Common cause: user is already in the channel. Agora recommends using onConnectionStateChanged to determine if the user is in the channel. Only call this method when receiving CONNECTION_STATE_DISCONNECTED (1).
    • -102: Invalid channel name. Pass a valid channel name in channelId and rejoin the channel.
    • -121: Invalid user ID. Pass a valid user ID in uid and rejoin the channel.

joinChannel [2/2]

Joins a channel and sets media options.

public abstract int joinChannel(String token, String channelId, int uid, ChannelMediaOptions options);

This method adds the options parameter to set media options, such as whether to publish audio/video streams in the channel or automatically subscribe to all remote users' streams upon joining. By default, a user subscribes to all other users’ audio/video streams in the channel, which generates usage and billing. To stop subscribing to other streams, set the options parameter or call muteRemoteAudio/VideoStream or muteAllRemoteAudio/VideoStreams.

Note:
  • This method only supports joining one channel at a time.
  • Users with different App IDs cannot communicate with each other.
  • Before joining a channel, ensure the App ID used to generate the token matches the App ID passed in the create [2/2] method; otherwise, joining the channel may fail.

Timing

Call this method after calling the create [2/2] method.

Parameters

token
The token generated on your server for authentication.
Note:
  • (Recommended) If your project has enabled secure mode (authentication using App ID and Token), this parameter is required.
  • If only test mode is enabled (authentication using App ID), this parameter is optional. After successfully joining the channel, the user will automatically leave the channel after 24 hours.
  • If you need to join multiple channels or switch between channels, Agora recommends using a wildcard token so you don’t need to request a new token each time.
channelId
Channel name. Users with the same App ID who enter the same channel name will join the same channel for audio and video interaction. The string length must be less than 64 bytes. Supported characters (total 89):
  • All lowercase letters: a to z.
  • All uppercase letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ",".
uid
User ID. Used to identify users in the channel. You must set and manage the user ID yourself and ensure it is unique within the same channel. This parameter is a 32-bit signed integer with a range of -2³¹ to 2³¹-1. If not specified (or set to 0), the SDK automatically assigns a random user ID and returns it via the onJoinChannelSuccess callback. Your app must record and maintain this returned user ID; the SDK does not store it.
options
Channel media options. See ChannelMediaOptions.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter. For example, the token is invalid, the uid is not set as an integer, or a member value in options is invalid. Pass in valid parameters and rejoin the channel.
    • -3: RtcEngine object initialization failed. Reinitialize the RtcEngine object.
    • -7: RtcEngine object is not initialized. Initialize the RtcEngine object before calling this method.
    • -8: Internal state error of the RtcEngine object. A common cause is calling this method to join a channel after starting an echo test with startEchoTest without stopping it using stopEchoTest. Call stopEchoTest before calling this method.
    • -17: Join channel request is rejected. A common cause is the user is already in a channel. Agora recommends using the onConnectionStateChanged callback to determine whether the user is in a channel. Only call this method when receiving the CONNECTION_STATE_DISCONNECTED (1) state.
    • -102: Invalid channel name. Pass a valid channel name in channelId to rejoin the channel.
    • -121: Invalid user ID. Pass a valid user ID in uid to rejoin the channel.

joinChannelEx

Joins a channel.

public abstract int joinChannelEx(String token, RtcConnection connection, ChannelMediaOptions options, IRtcEngineEventHandler eventHandler);

You can call this method multiple times to join multiple channels. In multi-camera capture scenarios, after calling this method, you need to call startPreview and set sourceType to VIDEO_SOURCE_CAMERA_SECONDARY to ensure proper capture from the second camera.

Note: If you are already in a channel, you cannot rejoin the same channel using the same user ID. Before joining a channel, ensure that the App ID used to generate the Token is the same as the one passed to create [2/2], otherwise joining the channel may fail.

Scenario

This method applies to multi-channel scenarios.

Timing

Call this method after create [2/2].

Parameters

token
The token used for authentication.
Note:
  • (Recommended) If your project enables secure mode (App ID + Token authentication), this parameter is required.
  • If you only enable test mode (App ID authentication), this parameter is optional. You will automatically leave the channel after 24 hours.
  • If you need to join different channels simultaneously or switch between channels, Agora recommends using a wildcard Token so you don't need to request a new Token each time.
connection
Connection information. See RtcConnection.
options
Channel media options. See ChannelMediaOptions.
eventHandler
Callback class. See IRtcEngineEventHandler. You can use the eventHandler object passed in this parameter to receive callback events for multiple channels.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameters. For example, invalid Token, uid is not set to an integer, or invalid member value in ChannelMediaOptions. You need to pass valid parameters and rejoin the channel.
    • -3: Failed to initialize the RtcEngine object. You need to reinitialize the RtcEngine object.
    • -7: RtcEngine is not initialized. You must initialize the RtcEngine object before calling this method.
    • -8: Internal state error of the RtcEngine object. A typical reason is that startEchoTest was called but stopEchoTest was not called before joining the channel. You need to call stopEchoTest before calling this method.
    • -17: Join channel request is rejected. A typical reason is that the user is already in the channel. Agora recommends that you determine whether the user is in a channel by using the onConnectionStateChanged callback. Only call this method when you receive CONNECTION_STATE_DISCONNECTED (1).
    • -102: Invalid channel name. You need to pass a valid channel name in channelId to rejoin the channel.
    • -121: Invalid user ID. You need to pass a valid user ID in uid to rejoin the channel.

joinChannelWithUserAccount [1/2]

Joins a channel using a user account and token.

public abstract int joinChannelWithUserAccount(String token, String channelName, String userAccount);

Calling registerLocalUserAccount to register a user account before calling this method to join a channel may reduce the time required to join. If you have not called registerLocalUserAccount, the SDK automatically creates a user account when you call this method to join a channel. Once a user joins a channel, by default they subscribe to all other users’ audio and video streams, which generates usage and billing. To stop subscribing to specific or all remote streams, call muteRemoteAudio/VideoStream or muteAllRemoteAudio/VideoStreams.

Note:
  • This method only supports joining one channel at a time.
  • Users with different App IDs cannot communicate with each other.
  • Before joining a channel, ensure the App ID used to generate the token matches the App ID passed in the create [2/2] method; otherwise, joining the channel with the token may fail.
  • To ensure smooth communication, use the same parameter type to identify users. For example, if one user joins using uid, other users should also use uid; if using a user account, others should also use a user account. If a user joins using the Agora Web SDK, ensure the user ID uses the same parameter type.

Timing

Call this method after calling the create [2/2] method.

Parameters

token
The token generated on your server for authentication.
Note:
  • (Recommended) If your project has enabled secure mode (authentication using App ID and Token), this parameter is required.
  • If only test mode is enabled (authentication using App ID), this parameter is optional. After successfully joining the channel, you will automatically leave the channel after 24 hours.
  • If you need to join different channels or switch between them, Agora recommends using a wildcard token so you don’t need to request a new token each time.
channelName
Channel name. Users with the same App ID who enter the same channel name will join the same channel for audio and video interaction. The string length must be less than 64 bytes. Supported characters (total 89):
  • All lowercase letters: a to z.
  • All uppercase letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
userAccount
The user account used to identify the user in the channel for real-time audio and video interaction. You must set and manage this account yourself and ensure it is unique within the same channel. The maximum length of this parameter is 255 bytes and it cannot be empty. Supported characters (total 89):
  • 26 lowercase letters: a to z.
  • 26 uppercase letters: A to Z.
  • All numeric characters: 0 to 9.
  • Space
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter. For example, the token is invalid, the uid is not set as an integer, or a member value in ChannelMediaOptions is invalid. Pass in valid parameters and rejoin the channel.
    • -3: RtcEngine object initialization failed. Reinitialize the RtcEngine object.
    • -7: RtcEngine object is not initialized. Initialize the RtcEngine object before calling this method.
    • -8: Internal state error of the RtcEngine object. A typical cause is calling this method to join a channel after starting an echo test with startEchoTest without stopping it using stopEchoTest. Call stopEchoTest before calling this method.
    • -17: Join channel request is rejected. A typical cause is the user is already in a channel. Agora recommends using the onConnectionStateChanged callback to determine whether the user is in a channel. Only call this method when receiving the CONNECTION_STATE_DISCONNECTED (1) state.
    • -102: Invalid channel name. Pass a valid channel name in channelId to rejoin the channel.
    • -121: Invalid user ID. Pass a valid user ID in uid to rejoin the channel.

joinChannelWithUserAccount [2/2]

Joins a channel using a user account and token, and sets media options.

public abstract int joinChannelWithUserAccount(String token, String channelName, String userAccount, ChannelMediaOptions options);
Since
Available since v3.3.0.

This method adds the options parameter to set media options, such as whether to publish audio and video streams in the channel. By default, the user subscribes to all other users' audio and video streams in the channel, which incurs usage and billing. To stop subscribing to other streams, set the options parameter or call muteRemoteAudio/VideoStream or muteAllRemoteAudio/VideoStreams.

Note:
  • This method only supports joining one channel at a time.
  • Users with different App IDs cannot communicate with each other.
  • Before joining a channel, ensure that the App ID used to generate the token is the same as the one passed in the create [2/2] method. Otherwise, joining the channel may fail due to token mismatch.
  • To ensure smooth communication, use the same identifier type for users. For example, if one user joins using a user ID, other users should also use a user ID; the same applies to user accounts. If a user joins the channel using the Agora Web SDK, ensure the user ID type is consistent.

Timing

Call this method after calling the create [2/2] method.

Parameters

token
The token generated on your server for authentication.
Note:
  • (Recommended) If your project enables secure mode (authentication using App ID and token), this parameter is required.
  • If you enable only test mode (authentication using App ID), this parameter is optional. The user will automatically leave the channel after 24 hours.
  • If you need to join multiple channels or switch between channels, Agora recommends using a wildcard token so you don't need to request a new token each time.
channelName
The channel name. Users with the same channel name under the same App ID will join the same channel for audio and video interaction. The string length must be less than 64 bytes. Supported characters (89 total):
  • All lowercase English letters: a to z.
  • All uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
userAccount
The user account. You need to set and manage user accounts yourself and ensure each user account is unique within the same channel. The maximum length of this parameter is 255 bytes and it cannot be empty. Supported characters (89 total):
  • 26 lowercase English letters: a to z.
  • 26 uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • Space
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
options
Channel media options. See ChannelMediaOptions.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter. For example, the token is invalid, the uid parameter is not set to an integer, or a member in ChannelMediaOptions has an invalid value. Pass in valid parameters and rejoin the channel.
    • -3: Failed to initialize the RtcEngine object. Reinitialize the RtcEngine object.
    • -7: The RtcEngine object is not initialized. Initialize the RtcEngine object before calling this method.
    • -8: The RtcEngine object is in an incorrect internal state. A typical cause is calling this method to join a channel after calling startEchoTest without stopping the test via stopEchoTest. Call stopEchoTest before calling this method.
    • -17: The join channel request was rejected. A typical cause is that the user is already in the channel. Agora recommends using the onConnectionStateChanged callback to determine whether the user is in the channel. Only call this method again when the state is CONNECTION_STATE_DISCONNECTED (1).
    • -102: Invalid channel name. Pass in a valid channel name in channelId and rejoin the channel.
    • -121: Invalid user ID. Pass in a valid user ID in uid and rejoin the channel.

joinChannelWithUserAccountEx

Joins a channel using a user account and token, and sets media options.

public abstract int joinChannelWithUserAccountEx(String token, String channelId, String userAccount, ChannelMediaOptions options, IRtcEngineEventHandler eventHandler);

Before calling this method, if you have not called registerLocalUserAccount to register a user account, the SDK will automatically create one when you join the channel. Calling registerLocalUserAccount in advance can shorten the time required to join the channel. Once a user joins a channel, by default, they subscribe to all other users' audio and video streams in the channel, which incurs usage and billing. If you want to stop subscribing to other users' media streams, you can set the options parameter or call muteRemoteAudio/VideoStream or muteAllRemoteAudio/VideoStreams.

Note:
  • This method only supports joining one channel at a time.
  • Users with different App IDs cannot communicate with each other.
  • Before joining a channel, make sure the App ID used to generate the token is the same as the one passed to the create [2/2] method; otherwise, joining the channel may fail.
  • To ensure smooth communication, use the same parameter type to identify users. For example, if one user joins with uid, others should also use uid; if using a user account, others should also use a user account. When using Agora Web SDK, ensure user ID parameter types are consistent.

Scenario

This method is applicable to multi-channel scenarios.

Timing

Call this method after calling create [2/2].

Parameters

token
Token generated on your server for authentication.
Note:
  • (Recommended) If your project has enabled secure mode (authentication using App ID and Token), this parameter is required.
  • If only test mode (authentication using App ID) is enabled, this parameter is optional. After successfully joining the channel, you will automatically leave after 24 hours.
  • If you need to join multiple channels or switch between channels, Agora recommends using wildcard tokens so you don’t need to request a new token each time.
channelId
Channel name. Under the same App ID, users with the same channel name will enter the same channel for audio and video interaction. The string length must be less than 64 bytes. Supported characters (89 total):
  • All lowercase English letters: a to z.
  • All uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
userAccount
User account. You need to set and manage user accounts yourself and ensure uniqueness within the same channel. The maximum length of this parameter is 255 bytes and it cannot be empty. Supported characters (89 total):
  • 26 lowercase English letters: a to z.
  • 26 uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • Space
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
options
Channel media options. See ChannelMediaOptions.
eventHandler
Callback class for RtcEngineEx. See IRtcEngineEventHandler. You can use the eventHandler object passed through this parameter to receive callback events from multiple channels.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameters. For example, invalid token, uid not set to an integer, or invalid values in ChannelMediaOptions. Please pass valid parameters and rejoin the channel.
    • -3: RtcEngine initialization failed. Please reinitialize the RtcEngine object.
    • -7: RtcEngine has not been initialized. Please initialize it before calling this method.
    • -8: Internal state error of RtcEngine. A typical reason is calling this method after starting an echo test with startEchoTest but without stopping it with stopEchoTest. Please call stopEchoTest before calling this method.
    • -17: Join channel request rejected. A typical reason is the user is already in the channel. It is recommended to confirm the user's presence in the channel via the onConnectionStateChanged callback. Unless you receive the CONNECTION_STATE_DISCONNECTED (1) state, do not call this method.
    • -102: Invalid channel name. Please pass a valid channel name in channelId and rejoin the channel.
    • -121: Invalid user ID. Please pass a valid user ID in uid and rejoin the channel.

leaveChannel [1/2]

Leaves the channel.

public abstract int leaveChannel();

After calling this method, the SDK stops all audio and video interactions and releases all resources related to the session. You must call this method after joining a channel to end the call; otherwise, you cannot start the next call.

Note:
  • If you call destroy [2/2] immediately after this method, the SDK does not trigger the onLeaveChannel callback.
  • This method is asynchronous. When it returns, it does not mean the user has completely left the channel.
  • If you joined multiple channels using joinChannelEx, calling this method leaves all the channels you joined.

Timing

Call this method after joining a channel.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -1: A general error occurs (no specific reason).
    • -2: Invalid parameter.
    • -7: SDK is not initialized.

leaveChannel [2/2]

Sets channel options and leaves the channel.

public abstract int leaveChannel(LeaveChannelOptions options);

After calling this method, the SDK stops all audio and video interactions, leaves the current channel, and releases all session-related resources. If you joined multiple channels using joinChannelEx, calling this method leaves all the channels you joined.

Note: If you call destroy [2/2] immediately after this method, the SDK does not trigger the onLeaveChannel callback. This method is asynchronous. When it returns, it does not necessarily mean the user has left the channel.

Timing

Call this method after joining a channel.

Parameters

options
Options for leaving the channel. See LeaveChannelOptions.

Return Values

  • 0: Success.
  • < 0: Failure.

leaveChannelEx [1/2]

Leaves a channel.

public abstract int leaveChannelEx(RtcConnection connection);

After calling this method, the SDK stops audio and video interactions, leaves the current channel, and releases all resources related to the session. After joining a channel using joinChannelEx, you must call this method or leaveChannelEx to end the call; otherwise, you cannot start the next call.

Note:

Scenario

This method applies to multi-channel scenarios.

Timing

Call this method after calling joinChannelEx.

Parameters

connection
Connection information. See RtcConnection.

Return Values

  • 0: Success.
  • < 0: Failure.

leaveChannelEx [2/2]

Sets channel parameters and leaves the channel.

public abstract int leaveChannelEx(RtcConnection connection, LeaveChannelOptions options);
Since
Added since v4.1.0.

After calling this method, the SDK stops audio and video interactions and releases all resources related to the session. After joining a channel using joinChannelEx, you must call this method or leaveChannelEx(RtcConnection connection) to end the call; otherwise, you cannot start the next call.

Note:
  • If you immediately call destroy() after this method, the SDK does not trigger the onLeaveChannel callback.
  • This method is asynchronous. The method return does not indicate that you have left the channel.
  • If you call leaveChannel() or leaveChannel(LeaveChannelOptions options), you will leave all channels joined via joinChannel [1/2], joinChannel [2/2], or joinChannelEx.

Scenario

This method applies to multi-channel scenarios.

Timing

Call this method after calling joinChannelEx.

Parameters

connection
Connection information. See RtcConnection.
options
Options for leaving the channel.
Note: This parameter only supports the stopMicrophoneRecording member in LeaveChannelOptions. Setting other members is ineffective.

Return Values

  • 0: Success.
  • < 0: Failure.

preloadChannel

Preloads the specified channel to reduce the time it takes for a viewer to join the channel.

public abstract int preloadChannel(String token, String channelName, int optionalUid);

When viewers need to switch between different channels frequently, calling this method can reduce the time to join a channel, thereby reducing the delay in hearing and seeing the host. If you rejoin a preloaded channel after leaving it, you do not need to call this method again unless the token used for preloading has expired.

Note:
  • When calling this method, ensure the user role is set to audience and the audio scenario is not set to AUDIO_SCENARIO_CHORUS, otherwise this method will not take effect.
  • You must also ensure that the channel name, user ID, and token used for preloading are the same as those used when joining the channel, otherwise the method will not take effect.
  • A single RtcEngine instance supports preloading up to 20 channels. If this limit is exceeded, only the most recent 20 preloaded channels take effect.
  • Failing to preload a channel does not mean the channel cannot be joined, nor does it increase the time required to join the channel.

Parameters

token
The token generated on your server for authentication. When the token used for preloading expires, you can update the token based on the number of preloaded channels:
  • To preload one channel, call this method with the new token.
  • To preload multiple channels:
    • If you use a wildcard token for all preloaded channels, call updatePreloadChannelToken to update the token. Note: When generating a wildcard token, make sure the user ID is not 0.
    • If you use different tokens for different channels, call this method with your user ID, channel name, and the new token.
channelName
The name of the channel you want to preload. This parameter represents the channel where users conduct real-time audio and video interactions. Users with the same channel name under the same App ID will join the same channel. The string length must be less than 64 bytes. Supported characters (89 total):
  • All lowercase English letters: a to z.
  • All uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ",".
optionalUid
User ID. Used to identify users in the channel for real-time audio and video interaction. You need to set and manage the user ID yourself and ensure that each user ID in the same channel is unique. This parameter is a 32-bit signed integer, ranging from -2^31 to 2^31-1. If the user ID is not specified (or set to 0), the SDK assigns a random user ID and returns it in the onJoinChannelSuccess callback. Your app must record and maintain the returned user ID; the SDK does not store it.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -7: The RtcEngine object is not initialized. Please initialize the RtcEngine object before calling this method.
    • -102: Invalid channel name. Please provide a valid channel name and rejoin the channel.

preloadChannelWithUserAccount

Preloads the specified channel to reduce the time it takes for a viewer to join the channel.

public abstract int preloadChannelWithUserAccount(String token, String channelName, String userAccount);

When viewers need to switch between different channels frequently, calling this method can reduce the time to join a channel, thereby reducing the delay in hearing and seeing the host. If you rejoin a preloaded channel after leaving it, you do not need to call this method again unless the token used for preloading has expired.

Note:
  • When calling this method, ensure the user role is set to audience and the audio scenario is not set to AUDIO_SCENARIO_CHORUS, otherwise this method will not take effect.
  • You must ensure that the User Account, channel name, and token used for preloading are the same as those used when joining the channel, otherwise the method will not take effect.
  • A single RtcEngine instance supports preloading up to 20 channels. If this limit is exceeded, only the most recent 20 preloaded channels take effect.
  • Failing to preload a channel does not affect the ability to join the channel, nor does it increase the time required to join the channel.

Timing

To enhance the user experience of preloading channels, Agora recommends calling this method as early as possible after confirming the channel name and user information.

Parameters

token
The token generated on your server for authentication. When the token used for preloading expires, you can update the token based on the number of preloaded channels:
  • To preload one channel, call this method with the new token.
  • To preload multiple channels:
    • If you use a wildcard token for all preloaded channels, call updatePreloadChannelToken to update the token. Note: When generating a wildcard token, make sure the user ID is not 0.
    • If you use different tokens for different channels, call this method with the User Account, channel name, and the new token.
channelName
The name of the channel you want to preload. The string length must be less than 64 bytes. Supported characters (89 total):
  • All lowercase English letters: a to z.
  • All uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
userAccount
The User Account used to identify the user in the channel. You need to set and manage the User Account yourself and ensure that each User Account in the same channel is unique. The maximum length of this parameter is 255 bytes and it cannot be empty. Supported characters (89 total):
  • 26 lowercase English letters: a to z.
  • 26 uppercase English letters: A to Z.
  • All numeric characters: 0 to 9.
  • Space
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter, such as an empty User Account. Please provide valid parameters and rejoin the channel.
    • -7: The RtcEngine object is not initialized. Please initialize the RtcEngine object before calling this method.
    • -102: Invalid channel name. Please provide a valid channel name and rejoin the channel.

registerLocalUserAccount

Registers a user account.

public abstract int registerLocalUserAccount(String appId, String userAccount);
This method registers a user account. After successful registration, the user account can be used to identify the local user when joining a channel. This method is optional. If you want to join a channel using a user account, you can choose either of the following:
  • Call registerLocalUserAccount first to register the user account, then call joinChannelWithUserAccount to join the channel. This may reduce the time required to join the channel.
  • Directly call joinChannelWithUserAccount to join the channel.

Parameters

appId
The App ID of your project in the Agora Console.
userAccount
The user account used to identify the user in the channel for real-time audio and video interaction. You must set and manage this account yourself and ensure it is unique within the same channel. The maximum length of this parameter is 255 bytes and it cannot be empty. Supported characters (total 89):
  • 26 lowercase letters: a to z.
  • 26 uppercase letters: A to Z.
  • All numeric characters: 0 to 9.
  • Space
  • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","

Return Values

  • 0: Success.
  • < 0: Failure.

renewToken

Updates the Token.

public abstract int renewToken(String token);
Call this method to update the Token. After a successful call, the SDK triggers the onRenewTokenResult callback. The Token expires after a certain period, after which the SDK cannot connect to the server. Agora recommends generating a new Token on your server and calling this method to update it in any of the following situations:

Parameters

token
The new Token.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter, e.g., the passed Token is empty.
    • -7: The RtcEngine object is not initialized. Please initialize the RtcEngine object before calling this method.
    • 110: Invalid Token. Please ensure the following:
      • The user ID specified when generating the Token matches the one used when joining the channel.
      • The generated Token is the same as the one passed when joining the channel.

setChannelProfile

Sets the channel profile.

public abstract int setChannelProfile(int profile);

The SDK applies different optimization strategies based on the channel profile. For example, in the live streaming profile, it prioritizes video quality. After initializing the SDK, the default channel profile is live streaming.

Note: To ensure communication quality, Agora recommends that all users in the same channel use the same channel profile. The SDK also uses different default audio routes for different channel profiles. See setDefaultAudioRouteToSpeakerphone.

Timing

Call this method before joining a channel.

Parameters

profile
Channel profile:
  • CHANNEL_PROFILE_COMMUNICATION (0): Communication profile. Agora recommends using CHANNEL_PROFILE_LIVE_BROADCASTING for better audio and video experience.
  • CHANNEL_PROFILE_LIVE_BROADCASTING (1): (Default) Live streaming profile.
  • CHANNEL_PROFILE_GAME (2): Game profile. Deprecated. Use CHANNEL_PROFILE_LIVE_BROADCASTING instead.
  • CHANNEL_PROFILE_CLOUD_GAMING (3): Interactive profile. This profile is optimized for low latency and suitable for scenarios requiring frequent interactions between users. Deprecated. Use CHANNEL_PROFILE_LIVE_BROADCASTING instead.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter.
    • -7: SDK not initialized.

setClientRole [1/2]

Sets the user role of the client instance.

public abstract int setClientRole(int role);
You can call this method to set the user role as either broadcaster or audience. The user role determines the user's privileges at the SDK level, including whether the user can publish audio and video streams in the channel. You can call this method either before or after joining a channel:
  • If you call this method before joining a channel and set the role as broadcaster, and also call setupLocalVideo to configure local video, the local video preview starts automatically when the user joins the channel.
  • If you call this method after joining a channel, the SDK automatically calls muteLocalAudioStream and muteLocalVideoStream to change the publishing state of audio and video streams.
Note: If you call this method before joining a channel and set the role to CLIENT_ROLE_BROADCASTER, the local client does not trigger the onClientRoleChanged callback. However, if you set the role to CLIENT_ROLE_AUDIENCE, the callback is triggered.

Timing

You can call this method before or after joining a channel.

Parameters

role
Note: If you set the user role to audience, you cannot publish audio or video streams in the channel.
User role:
  • CLIENT_ROLE_BROADCASTER (1): Broadcaster.
  • CLIENT_ROLE_AUDIENCE (2): Audience.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -1: A general error occurred (no specific reason).
    • -2: Invalid parameter.
    • -7: SDK not initialized.

setClientRole [2/2]

Sets the user role and audience latency level in live streaming.

public abstract int setClientRole(int role, ClientRoleOptions options);

By default, the SDK sets the user role to audience. You can call this method to set the role to broadcaster. The role determines the user's privileges at the SDK level, including whether the user can publish audio and video streams in the channel. This method differs from setClientRole(int role) in that it supports setting audienceLatencyLevel. audienceLatencyLevel must be used together with role to determine the service level available to the user. For example, audience users can choose to receive low or ultra-low latency streams.

Note: When the user role is set to broadcaster, the audience latency level must be AUDIENCE_LATENCY_LEVEL_ULTRA_LOW_LATENCY. If you call this method before joining a channel and set role to BROADCASTER, the local client does not trigger the onClientRoleChanged callback. If you call this method before joining a channel and set role to AUDIENCE, the callback is triggered.

Timing

You can call this method before or after joining a channel.
  • If you call this method before joining a channel and use setupLocalVideo to configure local video, the local video preview starts automatically when the user joins the channel.
  • If you call this method after joining a channel, the SDK automatically calls muteLocalAudioStream and muteLocalVideoStream to change the publishing state of audio and video streams.

Parameters

role
Note: If you set the user role to audience, you cannot publish audio or video streams in the channel. If you want to publish media streams during live streaming, make sure to set the role to broadcaster.
User role.
  • CLIENT_ROLE_BROADCASTER (1): Broadcaster.
  • CLIENT_ROLE_AUDIENCE (2): Audience (default).
options
Detailed user options. See ClientRoleOptions.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -1: A general error occurred (no specific reason).
    • -2: Invalid parameter.
    • -5: Request rejected.
    • -7: SDK not initialized.

updateChannelMediaOptions

Updates channel media options after joining a channel.

public abstract int updateChannelMediaOptions(ChannelMediaOptions options);

Parameters

options
The channel media options. See ChannelMediaOptions.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: A member value in ChannelMediaOptions is invalid, such as an invalid token or user ID. You need to provide valid parameters.
    • -7: The RtcEngine object is not initialized. You need to initialize it before calling this method.
    • -8: Internal state error of the RtcEngine object. This may occur if the user is not in a channel. Agora recommends using the onConnectionStateChanged callback to check whether the user is in a channel. If you receive CONNECTION_STATE_DISCONNECTED (1) or CONNECTION_STATE_FAILED (5), the user is not in a channel. Call joinChannel before calling this method.

updateChannelMediaOptionsEx

Updates the channel media options after joining a channel.

public abstract int updateChannelMediaOptionsEx(ChannelMediaOptions options, RtcConnection connection);

Scenario

This method applies to multi-channel scenarios.

Parameters

options
Channel media options. See ChannelMediaOptions.
connection
Connection information. See RtcConnection.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid member value in ChannelMediaOptions, such as an invalid token or user ID. You need to provide valid parameters.
    • -7: RtcEngine is not initialized. You must initialize the RtcEngine object before calling this method.
    • -8: Internal state error of the RtcEngine object, possibly because the user is not in a channel. Agora recommends that you determine whether the user is in a channel by using the onConnectionStateChanged callback. If you receive CONNECTION_STATE_DISCONNECTED (1) or CONNECTION_STATE_FAILED (5), the user is not in a channel. You need to call joinChannel before calling this method.

updatePreloadChannelToken

Updates the wildcard token used for preloading a channel.

public abstract int updatePreloadChannelToken(String token);

You need to manage the lifecycle of the wildcard token yourself. When the token expires, generate a new wildcard token and call this method with the new token.

Scenario

Applicable to scenarios involving multiple channels. For example, when switching between different channels, using a wildcard token allows you to avoid requesting a new token each time a user joins a new channel, thereby saving channel switching time and reducing the load on your token server.

Parameters

token
The new token.

Return Values

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter, such as an invalid token. You need to pass a valid parameter and rejoin the channel.
    • -7: RtcEngine object is not initialized. You need to initialize the RtcEngine object before calling this method.

onClientRoleChanged

Callback triggered when the user role or audience latency level changes.

public void onClientRoleChanged(int oldRole, int newRole, ClientRoleOptions newRoleOptions)
Note: This callback is not triggered if you call setClientRole [1/2] or setClientRole [2/2] before joining the channel and set the user role to broadcaster.

Trigger Timing

This callback is triggered in either of the following scenarios:

Parameters

oldRole
The user's role before the change:
  • CLIENT_ROLE_BROADCASTER (1): Broadcaster.
  • CLIENT_ROLE_AUDIENCE (2): Audience.
newRole
The user's role after the change:
  • CLIENT_ROLE_BROADCASTER (1): Broadcaster.
  • CLIENT_ROLE_AUDIENCE (2): Audience.
newRoleOptions
The role options after the change. See ClientRoleOptions.

onClientRoleChangeFailed

Callback triggered when switching user roles fails.

public void onClientRoleChangeFailed(int reason, int currentRole)

This callback notifies the reason for the failure to switch user roles and the current user role.

Trigger Timing

This callback is triggered when the local user joins a channel and calls setClientRole [1/2] or setClientRole [2/2] (with ClientRoleOptions parameter) to switch roles and the operation fails.

Parameters

reason
Note: This enum value is returned only when the 128-user feature is enabled. The broadcaster limit depends on the actual configuration when the 128-user feature is enabled.
The reason for the role switch failure.
  • CLIENT_ROLE_CHANGE_FAILED_TOO_MANY_BROADCASTERS (1): The number of broadcasters in the channel has reached the limit. This enum value is returned only when the 128-user feature is enabled.
  • CLIENT_ROLE_CHANGE_FAILED_NOT_AUTHORIZED (2): The request was rejected by the Agora server. It is recommended to prompt the user to retry switching roles.
  • CLIENT_ROLE_CHANGE_FAILED_REQUEST_TIME_OUT (3): Request timed out. It is recommended to prompt the user to check the network connection and retry switching roles. Deprecated since v4.4.0.
  • CLIENT_ROLE_CHANGE_FAILED_CONNECTION_FAILED (4): SDK connection failed. You can troubleshoot using the reason reported in the onConnectionStateChanged callback. Deprecated since v4.4.0.
currentRole
Current user role.
  • CLIENT_ROLE_BROADCASTER (1): Broadcaster, can send and receive audio and video streams.
  • CLIENT_ROLE_AUDIENCE (2): Audience, can only receive audio and video streams.

onError

Callback triggered when an error occurs during SDK runtime.

public void onError(int err)

This callback indicates that a network or media-related error has occurred during SDK runtime. In most cases, the SDK cannot automatically recover from the issue and continue running, so you need to handle it at the application level or notify the user.

Trigger Timing

This callback is triggered when an error occurs during SDK runtime.

Parameters

err
Error code. See the [Error Codes](https://doc.shengwang.cn/api-ref/rtc/android/error-code) documentation.

onJoinChannelSuccess

Callback triggered when a remote user successfully joins a channel.

public void onJoinChannelSuccess(String channel, int uid, int elapsed)

Trigger Timing

This callback is triggered when you call joinChannel, joinChannelWithUserAccount, joinChannelEx, or joinChannelWithUserAccountEx to join a channel.

Parameters

channel
Channel name.
uid
User ID of the user who joined the channel.
elapsed
Time elapsed (in milliseconds) from the local user calling joinChannel to the SDK triggering this callback.

onLocalUserRegistered

Callback triggered when the local user registers a User Account.

public void onLocalUserRegistered(int uid, String userAccount)
Since
Added since v2.8.0.

When the local user successfully calls registerLocalUserAccount to register a User Account or calls joinChannelWithUserAccount to join a channel, the SDK triggers this callback and returns the local user's user ID and User Account.

Trigger Timing

This callback is triggered when the local user successfully registers a User Account or joins a channel.

Parameters

uid
User ID of the local user.
userAccount
User Account of the local user.

onRejoinChannelSuccess

Callback triggered when a user rejoins a channel.

public void onRejoinChannelSuccess(String channel, int uid, int elapsed)

This callback is triggered when the user gets disconnected from the server due to network issues and the SDK automatically attempts and succeeds in reconnecting.

Trigger Timing

This callback is triggered when the user gets disconnected from the server due to network issues and the SDK automatically attempts and succeeds in reconnecting.

Parameters

channel
Channel name.
uid
User ID of the user who rejoined the channel.
elapsed
Time elapsed (in milliseconds) from the local user calling joinChannel to the SDK triggering this callback.

onRenewTokenResult

renewToken result callback.

public void onRenewTokenResult(String token, Constants.RenewTokenErrorCode code)
Since
Available since v4.6.0.

This callback is triggered after calling the renewToken method to notify the update result.

Trigger Timing

This callback is triggered after you call the renewToken method.

Parameters

token
Token used for authentication.
code
Error code. See RenewTokenErrorCode.

onRequestToken

Token expiration callback.

public void onRequestToken() {}
This callback is triggered when the token expires. When you receive this callback, you need to generate a new token on your token server and update the token using one of the following methods:
  • Single-channel scenario:
    • Call renewToken to update the token.
    • Call leaveChannel to leave the current channel, then pass the new token when calling joinChannel to rejoin the channel.
  • Multi-channel scenario: Call updateChannelMediaOptionsEx with the new token.

Trigger Timing

This callback is triggered when the token expires.

onRtcStats

Callback that reports statistics of the current call.

public void onRtcStats(RtcStats stats) {}

Trigger Timing

This callback is triggered every two seconds after the user joins the channel.

Parameters

stats
RTC engine statistics. See RtcStats.

onTokenPrivilegeWillExpire

Callback triggered when the token is about to expire in 30 seconds.

public void onTokenPrivilegeWillExpire(String token)
When you receive this callback, you need to generate a new token on your token server and update the token using one of the following methods:
  • Single-channel scenario:
    • Call renewToken with the new token.
    • Call leaveChannel to leave the current channel, then pass the new token when calling joinChannel to rejoin the channel.
  • Multi-channel scenario: Call updateChannelMediaOptionsEx with the new token.

Trigger Timing

This callback is triggered 30 seconds before the token expires.

Parameters

token
The token that is about to expire.

onUserInfoUpdated

Callback triggered when the remote user’s user ID and User Account are updated.

public void onUserInfoUpdated(int uid, UserInfo userInfo) {}
Since
Added since v2.8.0.

After the remote user joins the channel, the SDK obtains the user’s user ID and User Account, caches them in a mapping table, and then triggers this callback on the local client.

Trigger Timing

This callback is triggered after the remote user joins the channel and the SDK obtains their user ID and User Account.

Parameters

uid
User ID of the remote user.
userInfo
Contains the user ID and User Account of the remote user. See UserInfo.

onUserJoined

Callback triggered when a remote user or broadcaster joins the channel.

public void onUserJoined(int uid, int elapsed)

In a communication channel, this callback indicates that a remote user has joined the channel. When the local user joins the channel, the SDK also triggers this callback to report users already in the channel. In a live streaming channel, this callback indicates that a broadcaster has joined. Agora recommends limiting the number of co-hosts to 32, with a maximum of 17 video broadcasters.

Trigger Timing

This callback is triggered in any of the following scenarios:
  • A remote user or broadcaster joins the channel.
  • A remote user switches their role to broadcaster after joining the channel.
  • A remote user or broadcaster rejoins the channel after a network interruption.

Parameters

uid
User ID of the user who joined the channel.
elapsed
Delay (in milliseconds) from the local user calling joinChannel to this callback being triggered.

onUserOffline

Callback triggered when a remote user or host leaves the channel.

public void onUserOffline(int uid, int reason)
A user going offline is typically due to one of the following reasons:
  • Leaving the channel: When the user or host leaves the channel, a leave message is sent.
  • Dropped: If no data packet is received from the user or host for a period of time (20 seconds in a channel scenario, longer in a live streaming scenario), the SDK considers them dropped. Poor network conditions may cause misjudgment. It is recommended to use the Agora RTM SDK for reliable offline detection.

Trigger Timing

This callback is triggered when a remote user (in a channel scenario) or host (in a live streaming scenario) leaves the channel.

Parameters

uid
The user ID of the user who left the channel or went offline.
reason
The reason why the remote user (in a channel scenario) or host (in a live streaming scenario) went offline:
  • USER_OFFLINE_QUIT (0): The user voluntarily left the call and sent a leave message.
  • USER_OFFLINE_DROPPED (1): The SDK timed out without receiving any data packets, and the user was considered dropped. Poor network conditions may cause misjudgment. It is recommended to use the Agora RTM SDK for reliable offline detection.
  • USER_OFFLINE_BECOME_AUDIENCE (2): The user switched their role from host to audience.