# Presence 基础 (/zh-CN/realtime-media/rtm/build/state-and-attributes/presence-basic/harmonyos) > For AI agents: see the complete documentation index at [llms.txt](/llms.txt). **Presence** 服务让你具备洞察用户在线状态及频道中用户状态的能力: - 查询用户在线状态 - 获取频道内在线用户列表 - 获取在线用户所在频道列表 - 动态监控在线用户临时状态变更 :::info[前提条件] 从 v2.3.0 起,声网控制台新增 Presence 服务开关,该开关默认开启。获取频道在线用户、查询用户所在频道、临时状态及依赖 Presence 的订阅选项需要开启该服务。 `getUserOnlineStatus` 不受此开关限制,也不依赖 Presence Sync Database 就绪;它仍要求调用方的 MESSAGE session 已连接。 ::: ## 查询用户在线状态 [#query-user-online-status-harmonyos] 调用 `getUserOnlineStatus`,可以查询当前 App ID 下指定用户是否存在有效的 RTM 登录连接。查询方和目标用户都无需加入或订阅频道。 选择接口时,请区分以下三个查询维度: | 需要了解的信息 | 查询接口 | 判断范围 | | --- | --- | --- | | 频道里有哪些在线用户 | `whoNow` | 指定频道的在线用户列表 | | 用户加入或订阅了哪些频道 | `whereNow` | 指定用户的频道列表 | | 用户当前是否在线 | `getUserOnlineStatus` | 当前 App ID 下该用户是否在线 | 用户没有加入任何频道,或查询到的频道列表为空,都不能据此判定用户离线。 #### 调用流程 [#调用流程-2] 1. 按[应用配置](/zh-CN/realtime-media/rtm/build/rtm-initialization/application-setup)初始化 RTM,并完成[登录](/zh-CN/realtime-media/rtm/build/authentication-and-connection/login)。调用方需要 MESSAGE service 可用且 MESSAGE session 已连接。 2. 获取该客户端的 Presence 实例。无需额外订阅频道或等待 Presence Sync 就绪。 3. 传入一个精确的目标 User ID。可以传入自己的 User ID;空字符串不是查询自己的快捷方式。 4. 在成功分支中分别处理 `online=true` 和 `online=false`;在失败分支中处理错误,不将失败当作离线。 以下示例假设客户端已初始化并登录成功,查询目标为 `userB`。查询结果的处理方式见本节末尾的“结果与错误处理”。 ```typescript import { RtmClient, RtmError } from '@shengwang/rtm-full'; async function queryOnlineStatus(rtmClient: RtmClient): Promise { try { const status = await rtmClient.presence.getUserOnlineStatus('userB'); console.info(status.online ? '用户在线' : '用户离线或不存在'); } catch (error) { const rtmError = error as RtmError; console.error( `查询失败:errorCode=${rtmError.errorCode}, reason=${rtmError.reason}` ); } } ``` #### 结果与错误处理 [#结果与错误处理-2] 根据以下三种情况处理查询结果: | 查询结果 | 应用处理 | | --- | --- | | 成功,`online=true` | 目标用户存在有效的 RTM 登录连接,可以更新为在线状态。 | | 成功,`online=false` | 目标用户离线或不存在,按离线结果处理。 | | 调用失败 | 无法确定目标的在线状态,请参照[错误码说明](/zh-CN/api-reference/rtm/harmonyos/presence#getUserOnlineStatus-errors)处理。 | ## 获取频道内在线用户 [#获取频道内在线用户] 在一些应用场景中,你可能想要知道某个频道有多少在线用户,并获取在线用户列表等。你可以通过 `whoNow` 方法实现此功能。根据你的参数设置,该方法可以返回当前频道在线用户的用户 ID 列表及其临时状态数据或者仅返回当前频道在线用户的数量等。调用此方法无需你加入该频道,只需要将频道名作为参数传入该方法即可。 :::info[使用参数区分频道类型] 该方法对 Message Channel 和 Stream Channel 都适用,你可以使用 `channelType` 参数加以区分。 ::: 获取到这些初始信息后,你可以通过 `presence` 事件通知实时更新频道中在线用户信息。 :::info[登录后查询 Presence] 从 v2.3.0 起,调用 `login` 成功后,如果 Presence 服务仍在准备,SDK 会暂时等待并在服务可用后自动执行 `whoNow`、`whereNow` 和远端用户 `getState` 查询。应用无需增加固定延迟、临时订阅频道或等待 Presence 事件来判断服务是否就绪。处于等待状态的请求可能比正常请求多出一小段初始化等待时间;如果服务在合理时间内仍不可用,或等待期间发生登出、释放实例、连接中断等情况,请求会返回失败。 ::: 下面是查询频道内在线用户列表及其临时状态的示例代码: ```typescript import { RtmChannelType, PresenceOptions } from '@shengwang/rtm-full'; import { RtmError } from '@shengwang/rtm-full'; const channelName = "chat_room"; const options: PresenceOptions = { includeUserId: true, includeState: true }; try { const result = await rtmClient.presence.whoNow(channelName, RtmChannelType.MESSAGE, options); console.log(`Total users in channel: ${result.totalOccupancy}`); // If nextPage exists, use it for the next whoNow call if (result.nextPage) { console.log("Next page bookmark:", result.nextPage); } result.userStateList.forEach(userState => { console.log(`User: ${userState.userId}`); userState.states.forEach(state => { console.log(` ${state.key}: ${state.value}`); }); }); } catch (error) { console.error("whoNow failed:", error); if (error instanceof RtmError) { console.error(`whoNow failed: ${error.reason} (code: ${error.errorCode})`); } } ``` `whoNow` 方法一次返回一页数据,一页数据最多包含 100 个在线用户信息,如果频道在线用户超过 100 人,则会在返回结果中的 `nextPage` 字段包含下一页数据的书签。你需要在每次查询后判断 `result.nextPage` 是否为空,从而判断是否还有下一页数据。查询下一页数据时,将 `result.nextPage` 的值填入 `whoNow` 方法的 `page` 字段即可实现分页查询,以此往复,直到 `result.nextPage` 的值为空便是最后一页。例如: :::info[大频道查询] 从 v2.3.0 起,当频道在线人数超过 512 人时,SDK 会自动采用大频道优化策略,持续同步的成员明细最多包含 512 名成员。该限制只影响客户端持续接收的成员明细,不会截断 `whoNow` 的主动查询结果。如果应用需要完整在线成员列表,请继续使用分页查询。 ::: ```typescript import { RtmChannelType, PresenceOptions } from '@shengwang/rtm-full'; import { RtmError } from '@shengwang/rtm-full'; const channelName = "chat_room"; const options: PresenceOptions = { includeUserId: true, includeState: true, page: "your_Next_Page_Bookmark" }; try { const result = await rtmClient.presence.whoNow(channelName, RtmChannelType.MESSAGE, options); console.log(`Total users in channel: ${result.totalOccupancy}`); // If nextPage exists, use it for the next whoNow call if (result.nextPage) { console.log("Next page bookmark:", result.nextPage); } result.userStateList.forEach(userState => { console.log(`User: ${userState.userId}`); userState.states.forEach(state => { console.log(` ${state.key}: ${state.value}`); }); }); } catch (error) { console.error("whoNow failed:", error); if (error instanceof RtmError) { console.error(`whoNow failed: ${error.reason} (code: ${error.errorCode})`); } } ``` 当频道中人数众多时,你可能只关心频道中在线用户数量,而不关心他们是谁及其临时状态如何。此时可以设置 `whoNow` 方法中的 `includeState` 和 `includeUserId` 字段为 `false`。例如: ```typescript import { RtmChannelType, PresenceOptions } from '@shengwang/rtm-full'; import { RtmError } from '@shengwang/rtm-full'; const channelName = "chat_room"; const options: PresenceOptions = { includeUserId: false, includeState: false }; try { const result = await rtmClient.presence.whoNow(channelName, RtmChannelType.MESSAGE, options); console.log(`Total users in channel: ${result.totalOccupancy}`); // userStateList will be empty when includeUserId is false } catch (error) { console.error("whoNow failed:", error); if (error instanceof RtmError) { console.error(`whoNow failed: ${error.reason} (code: ${error.errorCode})`); } } ``` 此时返回的 `result` 中只有 `totalOccupancy` 字段有效,表示当前频道总人数,而其他字段全部为空。 :::info[信息] 不可以同时设置 `includeState = true` 且 `includeUserId = false`,即获取用户的临时状态就必须要返回用户 ID,否则会设置失败并收到错误码。 ::: ## 获取在线用户所在频道 [#获取在线用户所在频道] 你可能需要查询某个用户当前在哪些频道中,例如订阅了哪些 Message Channel 或加入了哪些 Stream Channel。特别是作为 App 管理员想要追踪用户路径时,这个功能就显得特别重要,此时你可以调用 `whereNow` 方法来实现。 ```typescript import { RtmError } from '@shengwang/rtm-full'; const userId = "Tony"; try { const result = await rtmClient.presence.whereNow(userId); console.log(`User is in ${result.channels.length} channels`); result.channels.forEach(channel => { console.log(`Channel: ${channel.channelName}, Type: ${channel.channelType}`); }); } catch (error) { console.error("whereNow failed:", error); if (error instanceof RtmError) { console.error(`whereNow failed: ${error.reason} (code: ${error.errorCode})`); } } ``` `whereNow` 方法会返回查询用户所在频道及其类型的信息。该方法会一次性返回所有查询结果,不会进行分页。