场景一: 附件类文件存储在环信服务器
应用环信 EMChatManager#downloadAttachment
下载附件计划
(本篇文章以图片音讯为例,其余附件类音讯相似):
一、通过 EMFileMessageBody#getLocalUrl
判断有没有本地文件;
EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
// 本地文件的资源门路
String imageLocalUrl = imgBody.getLocalUrl();
1、如果存在本地门路,间接应用本地文件;(本案例应用的 Glide)
Glide.with(this).load(imageLocalUrl).into(image);
2. 如果不存在本地文件,调用 EMChatManager#downloadAttachment 下载,下载胜利后展现图片;(本案例应用的 Glide)
EMMessage msg = EMClient.getInstance().chatManager().getMessage(msgId);
EMCallBack callback = new EMCallBack() {public void onSuccess() {EMLog.e(TAG, "onSuccess");
runOnUiThread(new Runnable() {
@Override
public void run() {Uri localUrlUri = ((EMImageMessageBody) msg.getBody()).getLocalUri();
Glide.with(mContext)
.load(localUrlUri)
.apply(new RequestOptions().error(default_res))
.into(image);
}
});
}
public void onError(final int error, String message) {EMLog.e(TAG, "offline file transfer error:" + message);
}
public void onProgress(final int progress, String status) {EMLog.d(TAG, "Progress:" + progress);
}
};
msg.setMessageStatusCallback(callback);
EMClient.getInstance().chatManager().downloadAttachment(msg);
二、如果对本地存储的门路有特殊要求:
1 能够先通过 EMFileMessageBody#setlocalUrl
去批改门路;
2 而后再调用 EMChatManager#downloadAttachment
下载(下载操作能够参考上边);
EMImageMessageBody imgBody = (EMImageMessageBody) message.getBody();
// 本地文件的资源门路
imgBody.setLocalUrl(localUrl);
场景二: 附件类文件存储在本人服务器
一、发送自定义音讯时,携带文件存储的 url;
EMMessage customMessage =EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
// `event` 为须要传递的自定义音讯事件,比方礼物音讯,能够设置:String event = "gift";
EMCustomMessageBody customBody = new EMCustomMessageBody(event);
// `params` 类型为 `Map`。Map params = new HashMap<>();
params.put("imageUrl","服务器的图片 url");
customBody.setParams(params);
customMessage.addBody(customBody);
// `to` 指另一方环信用户 ID(或者群组 ID,聊天室 ID)customMessage.setTo(to);
// 如果是群聊,设置 `ChatType` 为 `GroupChat`,该参数默认是单聊(`Chat`)。customMessage.setChatType(chatType);
EMClient.getInstance().chatManager().sendMessage(customMessage);
二、接管音讯时,解析字段获取到 url,进行下载;
@Override
public void onMessageReceived(List messages) {super.onMessageReceived(messages);
for (EMMessage message : messages) {EMCustomMessageBody emCustomMessageBody = (EMCustomMessageBody) message.getBody();
Map params = emCustomMessageBody.getParams();
String imageUrl = params.get("imageUrl");
}
}