99 行
2.6 KiB
Plaintext
99 行
2.6 KiB
Plaintext
|
|
import { XuqmSDK, ImMessage } from '@xuqm/harmony-sdk'
|
||
|
|
import promptAction from '@ohos.promptAction'
|
||
|
|
|
||
|
|
@Entry
|
||
|
|
@Component
|
||
|
|
struct Index {
|
||
|
|
@State messages: ImMessage[] = []
|
||
|
|
@State inputText: string = ''
|
||
|
|
@State connected: boolean = false
|
||
|
|
private toUserId: string = 'user_002'
|
||
|
|
|
||
|
|
aboutToAppear(): void {
|
||
|
|
const im = XuqmSDK.im
|
||
|
|
im.delegate = {
|
||
|
|
onConnected: () => {
|
||
|
|
this.connected = true
|
||
|
|
promptAction.showToast({ message: 'IM 已连接' })
|
||
|
|
},
|
||
|
|
onDisconnected: (code, reason) => {
|
||
|
|
this.connected = false
|
||
|
|
console.log(`IM disconnected: ${code} ${reason}`)
|
||
|
|
},
|
||
|
|
onMessage: (msg) => {
|
||
|
|
this.messages = [...this.messages, msg]
|
||
|
|
},
|
||
|
|
onError: (err) => {
|
||
|
|
promptAction.showToast({ message: 'IM 错误: ' + err })
|
||
|
|
},
|
||
|
|
}
|
||
|
|
im.connect()
|
||
|
|
}
|
||
|
|
|
||
|
|
aboutToDisappear(): void {
|
||
|
|
XuqmSDK.im.disconnect()
|
||
|
|
}
|
||
|
|
|
||
|
|
build() {
|
||
|
|
Column({ space: 12 }) {
|
||
|
|
Row() {
|
||
|
|
Text('XuqmSDK 示例')
|
||
|
|
.fontSize(20)
|
||
|
|
.fontWeight(FontWeight.Bold)
|
||
|
|
Blank()
|
||
|
|
Text(this.connected ? '● 已连接' : '○ 未连接')
|
||
|
|
.fontSize(14)
|
||
|
|
.fontColor(this.connected ? Color.Green : Color.Gray)
|
||
|
|
}
|
||
|
|
.width('100%')
|
||
|
|
.padding({ left: 16, right: 16, top: 16 })
|
||
|
|
|
||
|
|
List({ space: 8 }) {
|
||
|
|
ForEach(this.messages, (msg: ImMessage) => {
|
||
|
|
ListItem() {
|
||
|
|
Column({ space: 4 }) {
|
||
|
|
Text(msg.fromId).fontSize(12).fontColor(Color.Gray)
|
||
|
|
Text(msg.content).fontSize(15)
|
||
|
|
}
|
||
|
|
.alignItems(HorizontalAlign.Start)
|
||
|
|
.width('100%')
|
||
|
|
.padding(10)
|
||
|
|
.backgroundColor('#F5F5F5')
|
||
|
|
.borderRadius(8)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
.layoutWeight(1)
|
||
|
|
.width('100%')
|
||
|
|
.padding({ left: 16, right: 16 })
|
||
|
|
|
||
|
|
Row({ space: 8 }) {
|
||
|
|
TextInput({ placeholder: '输入消息...', text: this.inputText })
|
||
|
|
.layoutWeight(1)
|
||
|
|
.onChange((val) => { this.inputText = val })
|
||
|
|
|
||
|
|
Button('发送')
|
||
|
|
.onClick(() => {
|
||
|
|
if (!this.inputText.trim()) return
|
||
|
|
try {
|
||
|
|
XuqmSDK.im.send({
|
||
|
|
toId: this.toUserId,
|
||
|
|
chatType: 'SINGLE',
|
||
|
|
msgType: 'TEXT',
|
||
|
|
content: this.inputText.trim(),
|
||
|
|
})
|
||
|
|
this.inputText = ''
|
||
|
|
} catch (e) {
|
||
|
|
promptAction.showToast({ message: (e as Error).message })
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
.width('100%')
|
||
|
|
.padding({ left: 16, right: 16, bottom: 16 })
|
||
|
|
}
|
||
|
|
.width('100%')
|
||
|
|
.height('100%')
|
||
|
|
.backgroundColor(Color.White)
|
||
|
|
}
|
||
|
|
}
|