前言
因日常工作需要使用鸿蒙版腾讯 IM 聊天功能,但是腾讯 IM 只提供了相关接口,并没有像安卓和 iOS 一样提供配套的 UI 页面。这点不得不吐槽一下腾讯,作为互联网巨头鸿蒙开发进度怎么就这么慢,没办法只能对比着微信自己一点点去实现相关功能,本篇文章将详细介绍聊天列表页面的搭建过程,建议点赞收藏!
实现效果
先看本文的最终实现效果如下:
需求分析
- 支持删除功能。
- 支持按照收到消息的时间排序。
支持消息更新及插入新消息。
技术实现
展示会话列表
- 首先获取默认会话列表,这里根据 IM 的 SDK 提供的方法,调用 V2TIMManager.getConversationManager获取默认会话列表数据。
V2TIMManager.getConversationManager()
.getConversationListByFilter(this.page, this.pageSize)
.then((result: V2TIMConversationResult) => {
})
- 得到默认会话列表数据后,需要将实现一个 List 列表展示会话列表,这里需要注意 keyGenerator 的定义。
List() {
LazyForEach(this.dateSource, (item: V2TIMConversation, index: number) => {
ListItem() {
this.ItemLayout(item)
}.swipeAction({
end: {
builder: () => {
this.DeleteView(index, () => {
this.deleteDialog.open()
})
}
}
})
}, (item: V2TIMConversation, index: number) => index + ""+ (item!=undefined&& item.lastMessage!=undefined &&item.lastMessage.timestamp !=undefined?item.lastMessage.timestamp:""))
}
lazyForEach 中的 keyGenerator 必须使用消息里面的时间戳作为唯一的键值,否则会报错。swipeAction 是侧滑删除功能。
新增会话
- 当收新联系人发来的信息或已经在列表中的联系人发来的信息时,需要将联系人插入到消息列表头部。首先增加实时会话监听,使用ConversationTestInterfaces.addConversationListener 监听实时会话。
/**
* 会话监听
*/
conversationListener: V2TIMConversationListener = {
onConversationChanged: (conversationList: V2TIMConversation[]) => {
//实时会话
},
};
ConversationTestInterfaces.addConversationListener(this.conversationListener)
- 首先需要对实时收到的会话进行过滤,判断新收到的会话是否已经存在在列表中,如果存在则将会话插入到列表头部,如果已经存在则需要将会话移动到列表头部。
let newList = this.dateSource.getDataAll().filter((item, index) => {
return conversationList[0].conversationID == item.conversationID
})
对得到的实时会话列表进行筛选,以conversationID 作为匹配条件。如果新收到的会话不存在,则将会话插入列表中。
this.dateSource.pushData(conversationList[0])
- 如果新收到的会话已经存在,则需要将新的会话插入到列表头部,这里先删除旧的会话数据,然后将新的会话数据插入列表中。
let index = this.dateSource.getDataAll().indexOf(newList[0])
this.dateSource.deleteData(index)
this.dateSource.pushData(conversationList[0])
- 新的会话数据插入列表后,数据并没有位于列表头部,最后需要对数据进行排序即可,这里以会话时间作为比较。
if (this.dateSource.getDataAll().length > 1) {
this.dateSource.getDataAll().sort((a, b) => (b!=undefined&& b.lastMessage!=undefined && b.lastMessage.timestamp!=undefined?b.lastMessage.timestamp:0 ) - (a!=undefined&& a.lastMessage!=undefined && a.lastMessage.timestamp!=undefined?a.lastMessage.timestamp:0 ))
}
删除会话
会话删除就比较简单了,直接根据会话 ID 进行删除即可。
V2TIMManager.getConversationManager()
.deleteConversation(conversation.conversationID)
.then(() => {
//更新列表
})
.catch((error: Error) => {
});
总结腾讯
IM 功能十分复杂,本篇文章仅仅实现了会话列表功能,所有代码逻辑都需要自己动手处理,鸿蒙版的 IM SDK 只提供了接口,所以在实际实现过程中肯定会遇到很多问题需要自己克服,最终实现和微信相同的功能。下篇文章开始搭建聊天详情功能,需要接入鸿蒙 IM 的小伙伴赶紧收藏起来吧 !
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。