IMHelper.ets
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {
ConversationIdentifier,
ConversationType,
IAsyncResult,
IMEngine,
InitOption,
ISendMsgOption,
Message,
ReceivedInfo
} from '@rongcloud/imlib';
import { Context } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { CustomMessageContent } from './CustomMessageContent';
export class IMHelper {
private static appKey: string = "c9kqb3rdcfolj"
/**初始化*/
static initSdk(context: Context) {
let initOption = new InitOption();
let appKey = IMHelper.appKey;
IMEngine.getInstance().init(context, appKey, initOption);
}
/**注册消息监听*/
static registerMsgListener() {
IMEngine.getInstance().setMessageReceivedListener((message: Message, info: ReceivedInfo) => {
// 针对接收离线消息时,服务端会将 200 条消息打成一个包发到客户端,客户端对这包数据进行解析。该参数表示每个数据包数据逐条上抛后,还剩余的条数
let left = info.left;
// 消息是否离线消息
let isOffline = info.isOffline;
// 是否在服务端还存在未下发的消息包
let hasPackage = info.hasPackage;
hilog.info(0x0000, 'IM-App', 'message: ' + message + "//" + info.hasPackage);
});
}
/**建立 IM 连接*/
static creatSocket(iMToken: string) {
// let token = "m8KmlHGuI4wjGBr2sHaUAASYiD7nx6VZJ5vkHoVrMhU=@b20a.cn.rongnav.com;b20a.cn.rongcfg.com";
// iMToken = "m8KmlHGuI4zGTdp+DIN9qwSYiD7nx6VZmZKqed9uqUk=@b20a.cn.rongnav.com;b20a.cn.rongcfg.com";
let timeout = 5;
hilog.info(0x0000, 'IM-App', 'connect token:%{public}s', iMToken);
IMEngine.getInstance().connect(iMToken, timeout)
.then(result => {
hilog.info(0x0000, 'IM-App', 'connect result :%{public}s', JSON.stringify(result));
});
}
/**发送消息*/
static sendMsg(type: ConversationType, targetId: string, data: CustomMessageContent): Promise<IAsyncResult<Message>> {
let conId = new ConversationIdentifier();
conId.conversationType = type;
conId.targetId = targetId; // 按需填写实际的会话 id
let option: ISendMsgOption = {};
// 创建消息体
let msg = new Message(conId, data);
// IMEngine.getInstance().sendMessage(msg,option,(msg: Message) => {
// // 消息入库回调
// hilog.info(0x0000, 'IM-App', 'SendTextMessage onSave msg:%{public}s', JSON.stringify(msg));
// }).then(result => {
// // 消息发送结果
// hilog.info(0x0000, 'IM-App', 'SendTextMessage onResult :%{public}s', JSON.stringify(result));
// })
return IMEngine.getInstance().sendMessage(msg, option, () => {
});
}
}