主题
HarmonyOS 从零接入晞晗IM
本页面向 ArkTS Stage 工程。完成后,你可以安装 HAR、连接账号、监听事件并发送 第一条文字消息。
1. 准备接入信息
向服务端负责人领取 Server URL、App ID、当前用户 ID 和一个对端测试用户 ID。 正式环境还需要应用自己的后台提供短期 XHIM 凭证。
2. 安装 HAR
把 xhim.har 放入模块的 libs/,在 oh-package.json5 中添加:
json5
{
"dependencies": {
"@xihansoftware/xhim": "file:./libs/xhim.har"
}
}执行 ohpm install。完整 HAR 应同时包含 ArkTS 类型、N-API 与目标设备需要的 Native Runtime;不要只复制 Index.ets。
3. 配置网络权限
json5
{
"module": {
"requestPermissions": [
{ "name": "ohos.permission.INTERNET" },
{ "name": "ohos.permission.GET_NETWORK_INFO" }
]
}
}正式环境使用 HTTPS/WSS,不在应用中加入“忽略证书”开关。
4. 连接当前账号
Development Server 已开启测试登录时:
ts
import { XHIMClient } from '@xihansoftware/xhim'
const client = await XHIMClient.connect(
getContext(this),
'https://im-test.example.com',
currentUserId
)正式环境增加业务凭证提供器:
ts
import {
XHIMAuthentication,
XHIMClient
} from '@xihansoftware/xhim'
const client = await XHIMClient.connect(
getContext(this),
'https://im.example.com',
currentUserId,
{
appId: 'your-app',
authentication: XHIMAuthentication.business(
(): Promise<string> => accountApi.fetchXHIMCredential()
)
}
)把 Client 放在账号级 Store 中,不要在每个 Page 中重复连接。
5. 监听变化并发送消息
ts
const stopEvents = client.onEvent((event): void => {
messageStore.handleXHIMEvent(event)
})
const direct = await client.directConversation('bob')
await client.sendText(
direct.conversationId,
'你好,晞晗IM'
)收到事件后重新查询当前会话或消息。Page 不需要自己维护 WebSocket 或消息数据库。
6. 页面退出、登出与换号
普通 Page 销毁时只取消自己的监听:
ts
stopEvents()用户真正登出或切换账号时:
ts
await client.logout()
await client.shutdown()7. 常用功能入口
| 任务 | 方法 |
|---|---|
| 查询会话 | client.conversations(...) |
| 查询消息 | client.messages(...) |
| 标记已读 | client.markConversationRead(...) |
| 查询用户资料 | client.currentUserProfile() |
| 查询好友和群组 | client.friendships(...) / client.groups(...) |
| 创建群 | client.createGroup(...) |
| 查询在线状态 | client.queryPresence(...) |
完整参数、返回值与错误见 SDK API Reference。
8. 二次开发建议
把 Client 和长期事件监听放在账号 Store;Repository 负责查询,ArkUI Page 只渲染 不可变结果。需要自定义消息 Renderer 或页面结构时查看 客户端二次开发指南。
9. 常见问题
安装后找不到 Native Library
当前 HAR 不包含目标设备 ABI,或打包时漏掉 Native 文件。更换完整发行包,不要 手工复制其他版本 .so。
Development 可以连接,Production 不可以
正式环境必须使用业务凭证提供器和可信 HTTPS/WSS,不能只传 User ID。
收到事件但页面没变化
确认 messageStore.handleXHIMEvent 会重新查询当前会话,而不是只记录日志。