鸿蒙开发融云demo发送图片消息
融云鸿蒙版是不带UI的,得自己一步步搭建。
这次讲如何发送图片消息,选择图片,显示图片消息。
还是有点难度的,好好看,好好学。
一、思路:
选择图片用:photoViewPicker.select
二、效果图:
三、关键代码:
/**
* 选择图片
* 注:官方说不用申请权限
*/
public static openGallery(maxSelectNumber:number,callBack:(result:string[])=>void) {
if(maxSelectNumber){
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = maxSelectNumber; // 选择媒体文件的最大数目
const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
if (photoSelectResult.photoUris.length > 0) {
callBack(photoSelectResult.photoUris)
}
}).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
}else {
showToast('已选素材数量达到上限')
}
}
public static sendImageMessage(targetId: string, localPath: string,successCallBack?:()=>void) {
let conId = new ConversationIdentifier();
conId.conversationType = ConversationType.Private;
conId.targetId = targetId;
let imageMsg = new ImageMessage();
imageMsg.localPath = localPath;
let msgSrc = new Message(conId, imageMsg);
let option: ISendMsgOption = {};
let msgAfter: Message = msgSrc
IMEngine.getInstance().sendMediaMessage(msgSrc, option, (msg: Message) => {
// 消息保存到数据库
msgAfter = msg
msgAfter.sentStatus = SentStatus.Sending
// 这边会填消息
EventKeys.postEvent(EventKeys.ReceivedImMessageEvents,ReceivedImMessageEvent(msgAfter))
}, (msg: Message, progress: number) => {
// 媒体上传进度 [1 ~ 100]
}).then(result => {
if (EngineError.Success !== result.code) {
//发送消息失败
msgAfter.sentStatus = SentStatus.Failed
EventKeys.postEvent(EventKeys.ReceivedImMessageEvents,ReceivedImMessageEvent(msgAfter))
return;
}
if (!result.data) {
// 消息为空
// 成功的状态,但是理论上不会出现发送消息成功,但是消息体为空的情况,暂时不处理,避免发送多次通知
// msgAfter.sentStatus = SentStatus.Sent
// emitter.emit(EventKeys.RECEIVED_IM_MESSAGE_EVENT, ReceivedImMessageEvent(msgAfter))
return;
}
let msg = result.data as Message;
EventKeys.postEvent(EventKeys.ReceivedImMessageEvents,ReceivedImMessageEvent(msg))
// 刷新会话列表,不打算自己插入会话
EventKeys.postEvent(EventKeys.RefreshMsgListEvents)
successCallBack?.()
})
}
四、整个鸿蒙融云Demo源码结构图:
有问题或者需要完整源码的私信我