如何修改TIM聊天头像
编者:李国帅
qq:9611153 微信lgs9611153
时间:2019/7/22
目录
背景原因:
腾讯的imsdk聊天程序中的会话和和个人头像需要手动设置。
所需资源:
前端设备
android
TIM版本
api 'com.tencent.imsdk:imsdk:4.4.716'
相关函数:
设置聊天头像
设置聊天头像
后台修改,暂时不需要前台修改
后台修改
{ "From_Account":"id", "ProfileItem": [ { "Tag":"Tag_Profile_IM_Nick", "Value":"MyNickName" }, { "Tag":" Tag_Profile_IM_Image", "Value":"http://xxxx" } ] } |
修改本地缓冲中的头像
private void updateMyInfo(String chatId,String userName,String userImage) { |
从后台拉取用户资料
//获取自己资料 * @param cb 回调 * @return 0表示成功,-1表示参数为空
public int getSelfProfile(@NonNull final TIMValueCallBack<TIMUserProfile> cb) {
//获取指定用户资料 * @param identifiers 用户的identifier列表 * @param forceUpdate 强制从后台拉取 * @param cb 回调
public void getUsersProfile(@NonNull List<String> identifiers, boolean forceUpdate, @NonNull TIMValueCallBack<List<TIMUserProfile>> cb) {
//获取好友列表 * @param cb 回调 TIMFriend 列表
public void getFriendList(@NonNull TIMValueCallBack<List<TIMFriend>> cb) {
从缓冲区获取用户资料
函数说明
//获取缓存中的关系链列表,缓存数据来自于上一次调用getFriendList,请确保已调用了获取好友列表方法
public List<TIMFriend> queryFriendList() {
//在缓存中查询用户的关系链数据,缓存数据来自于上一次调用getFriendList,请确保已调用了获取好友列表方法
public TIMFriend queryFriend(String identifier) {
从本地缓冲获取
//获取本地自己的资料,没有则返回 null
TIMUserProfile userInfo= TIMFriendshipManager.getInstance().querySelfProfile();
//获取本地用户资料,没有则返回 null
TIMUserProfile userInfo= TIMFriendshipManager.getInstance().queryUserProfile(chatId);
如果不行的话
TIMUserProfile userInfo= TIMFriendshipManager.getInstance().queryFriend(chatId).getTimUserProfile();
//获取用户的昵称
String name = userInfo.getNickName();
//获取用户头像URL
String face = userInfo.getFaceUrl();
设置头像基本策略:
1、IM登录之后,在获取会话的时候,获取一次用户信息和好友信息,不管是否成功
TIMFriendshipManager.getInstance().getSelfProfile(null);
TIMFriendshipManager.getInstance().getFriendList((listFriend)->{
TIMFriendshipManager.getInstance().getUsersProfile(friends,null);//查询所有的用户信息
});
2、当显示会话和聊天详情的时候,直接从本地缓冲获取。
public class TIMFriend implements Serializable {
...
private String identifier = "";
...
private TIMUserProfile timUserProfile;
public TIMUserProfile getTimUserProfile()
会话列表相关类
SessionPanel类
/**
* 会话面板类(SessionPanel)实现的业务接口
*/
public interface ISessionPanel {
/**
* 开放会话头像编辑功能,开发者可在头像的布局里添加元素(如添加挂件,头衔等)
* @param dynamicIconView
*/
void setSessionIconInvoke(DynamicSessionIconView dynamicIconView);
会话图像类
public class SessionIconView extends RelativeLayout {
设置图像
public void setProfileImageView(ImageView iconView) {
/**
* 设置会话头像的url
* @param iconUrls 头像url,最多只取前9个
*/
public void setIconUrls(List<String> iconUrls) {
public void setDefaultImageResId(int resId) {
会话信息类
public class SessionInfo implements Serializable, Comparable<SessionInfo> {
//会话头像url
private String iconUrl;
//会话头像
private Bitmap icon;
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
SessionAdapter中设置头像
public class SessionAdapter extends ISessionAdapter {
//if (session.isGroup()) {
// holder.sessionIconView.setDefaultImageResId(R.drawable.default_group);
// } else {
// holder.sessionIconView.setDefaultImageResId(R.drawable.default_head);
// }
holder.sessionIconView.setIconUrls(null);// 需要设置图标,需要把未读消息放在图标右上角
List<String> iconUrls = new ArrayList<>();
if (session.getIconUrl() != null) {
iconUrls.add(session.getIconUrl());
} else {
TIMUserProfile userInfo = null;
userInfo = TIMFriendshipManager.getInstance().queryUserProfile(session.getPeer());
if (userInfo != null) {
String face = userInfo.getFaceUrl();//获取用户头像URL
if (face.length() > 0) {
iconUrls.add(face);
}
QLog.i("TAG", "SessionAdapter getView " + userInfo.getNickName() + " " + userInfo.getIdentifier() + " " + face);
}
}
if (iconUrls.size() > 0) {
holder.sessionIconView.setIconUrls(iconUrls);
} else {
holder.sessionIconView.setDefaultImageResId(R.drawable.default_head);
}
聊天列表消息详情界面适配器
public class ChatAdapter extends IChatAdapter {
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
if (chatHolder.userIcon != null) {
chatHolder.userIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//点击图像
mListEvent.onUserIconClick(v, position, msg);
}
});
}
if (chatHolder.userIcon != null) {
if (mRecycleView.getUserChatIcon() != null) {
chatHolder.userIcon.setDynamicChatIconView(mRecycleView.getUserChatIcon());
}
chatHolder.userIcon.invokeInformation(msg);
TIMUserProfile userInfo;
if (msg.isSelf()) {
userInfo = TIMFriendshipManager.getInstance().querySelfProfile();
} else {
userInfo = TIMFriendshipManager.getInstance().queryUserProfile(msg.getPeer());
}
if (userInfo != null) {
String face = userInfo.getFaceUrl();//获取用户头像URL
if (face.length()>0) {
List<String> iconUrls = new ArrayList<>();
iconUrls.add(face);
chatHolder.userIcon.setIconUrls(iconUrls);
}
} else {
chatHolder.userIcon.setDefaultImageResId(R.drawable.default_head);
}
}
解决方案:
获取用户头像
1、当查询会话列表的时候,把头像路径从IM服务器上获取。
public class SessionPanel extends RelativeLayout implements ISessionPanel {
public void refresh() {
mAdapter.notifyDataSetChanged();
}
public void initDefault() {
...
mPresenter = new SessionPresenter(this);
mPresenter.loadSessionData();//加载会话数据
}
/**
* 加载会话数据
*/
public void loadSessionData() {
mManager.loadSession(new IUIKitCallBack() {
@Override
public void onSuccess(Object data) {
mSessionPanel.getSessionAdapter().setDataProvider((SessionProvider) data);
}
@Override
public void onError(String module, int errCode, String errMsg) {
UIUtils.toastLongMessage("加载消息失败");
}
});
}
public class SessionManager implements UIKitRequestHandler, TIMRefreshListener, UIKitMessageRevokedManager.MessageRevokeHandler {
// 加载会话信息
public void loadSession(IUIKitCallBack callBack) {
public void loadSession(IUIKitCallBack callBack) {
..
List<String> timUserAccounts = new ArrayList<>();
List<TIMConversation> TIMSessions = TIMManagerExt.getInstance().getConversationList();
ArrayList<SessionInfo> infos = new ArrayList<>();
for (int i = 0; i < TIMSessions.size(); i++) {
TIMConversation conversation = TIMSessions.get(i);
//将imsdk TIMConversation转换为UIKit SessionInfo
SessionInfo sessionInfo = TIMConversation2SessionInfo(conversation);
if (sessionInfo != null) {
..
String identifier = conversation.getPeer();
timUserAccounts.add(identifier);
}
}
if (timUserAccounts.size() > 0) {
TUIKit.getUserInfo(timUserAccounts);
}
2、在查询会话详情是获取最新的用户头像
public class C2CChatPanel extends ChatPanel implements IChatPanel {
public void setBaseChatId(String chatId) {
..
List<String> timUserAccounts = new ArrayList<>();
timUserAccounts.add(TUIKit.getUserAccount());
timUserAccounts.add(chatId);
TUIKit.getUserInfo(timUserAccounts);
...
}
3、把用户的头像路径设置到本地缓冲
public static void getUserInfo(List<String> timUserProfiles) {
List<String> timUserNeed = new ArrayList<>();
for (String identifier : timUserProfiles) {
TIMUserProfile userInfo;
userInfo = TIMFriendshipManager.getInstance().queryUserProfile(identifier);
//if (userInfo == null || userInfo.getFaceUrl() == null
// || userInfo.getFaceUrl().length() == 0) {//全部获取
timUserNeed.add(identifier);
//}
}
if (timUserNeed.size() == 0) {
return;
}
//查询所有的用户信息
TIMFriendshipManager.getInstance().getUsersProfile(timUserNeed, true, new TIMValueCallBack<List<TIMUserProfile>>() {
@Override
public void onError(int code, String desc) {
UIUtils.toastLongMessage("获取咨询的好友用户信息失败: " + code + "=" + desc);
}
@Override
public void onSuccess(List<TIMUserProfile> timUserProfiles) {
QLog.i("TAG", "imLogin getUsersProfile size=" + timUserProfiles.size());
if (timUserProfiles.size() > 0) {
for (TIMUserProfile userInfo : timUserProfiles) {
String face = userInfo.getFaceUrl();//获取用户头像URL
String nick = userInfo.getNickName();
String identifier = userInfo.getIdentifier();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_NICK, nick);
profileMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL, face);
if (identifier.equalsIgnoreCase(userAccount)) {
//每个用户设置自身名称和头像图片。
TIMFriendshipManager.getInstance().modifySelfProfile(profileMap, null);
} else {
//修改好友信息
TIMFriendshipManager.getInstance().modifyFriend(identifier, profileMap, null);
}
}
}
}
});
}
头像显示
1、在会话列表显示用户头像
sessionAdapter
holder.sessionIconView.setIconUrls(null);// 需要设置图标,需要把未读消息放在图标右上角
String iconUrl = "";
String nick = session.getTitle();
if (session.getIconUrl() != null) {
iconUrl = session.getIconUrl();
} else {
TIMUserProfile userInfo = null;
userInfo = TIMFriendshipManager.getInstance().queryUserProfile(session.getPeer());
if (userInfo != null) {
iconUrl = userInfo.getFaceUrl();//获取用户头像URL
if (userInfo.getNickName().length() > 0)
nick = userInfo.getNickName();
String identifier = userInfo.getIdentifier();
QLog.i("TAG", "Check UserIco SessionAdapter getView " +nick+" " +identifier+" " +iconUrl);
}
}
if (iconUrl.length() > 0) {
holder.sessionIconView.setIconUrl(iconUrl);
} else {
holder.sessionIconView.setDefaultImageResId(R.drawable.default_head);
}
if (mSessionPanel.getInfoView() != null) {
holder.sessionIconView.invokeInformation(session, mSessionPanel.getInfoView());
}
holder.titleText.setText(nick);
SessionIconView
public void setIconUrl(String iconUrl) {
((SynthesizedImageView) mIconView).defaultImage(iconUrl).load();;
}
2、在聊天详情显示用户头像
ChatAdapter
if (chatHolder.userIcon != null) {
if (mRecycleView.getUserChatIcon() != null) {
chatHolder.userIcon.setDynamicChatIconView(mRecycleView.getUserChatIcon());
}
chatHolder.userIcon.invokeInformation(msg);
TIMUserProfile userInfo;
if (msg.isSelf()) {
userInfo = TIMFriendshipManager.getInstance().querySelfProfile();
} else {
userInfo = TIMFriendshipManager.getInstance().queryUserProfile(msg.getPeer());
}
String iconUrl = "";
String nick = msg.getFromUser();
if (userInfo != null) {
iconUrl = userInfo.getFaceUrl();//获取用户头像URL
if (userInfo.getNickName().length() > 0)
nick = userInfo.getNickName();
String identifier = userInfo.getIdentifier();
QLog.i("TAG", "Check UserIco ChatAdapter getView " + nick + " " + identifier + " " + iconUrl);
}
if (iconUrl.length() > 0) {
chatHolder.userIcon.setIconUrl(iconUrl);
} else {
chatHolder.userIcon.setDefaultImageResId(R.drawable.default_head);
}
chatHolder.userName.setText(nick);
}
ChatIconView
public void setIconUrl(String face) {
mIconView.defaultImage(face);// mIconView就是一个SynthesizedImageView
}
3、修改显示的公共类
SynthesizedImageView
public class SynthesizedImageView extends ShadeImageView {
public SynthesizedImageView defaultImage(String imageUrl) {
teamHeadSynthesizer.setImageUrl(imageUrl);
return this;
}
TeamHeadSynthesizer
//同步加载图片
private Bitmap asyncLoadImage(String imageUrl, int targetImageSize) throws InterruptedException, ExecutionException {
return Glide.with(mContext).asBitmap()
.load(imageUrl)
.into(targetImageSize, targetImageSize)
.get();
}
public void setImageUrl(String imageUrl) {
multiImageData.setDefaultImage(imageUrl);
}
public String getImageUrl() {
return multiImageData.getDefaultImage();
}
public void setDefaultImage(int defaultImageResId) {
multiImageData.setDefaultImage("");//删除默认的图片url,因为先判断url,会导致设置resid失效
multiImageData.setDefaultImageResId(defaultImageResId);
}
群聊头像合成器MultiImageData
//默认的图片
String defaultImage="";
public void setDefaultImage(String defaultImage) {
this.defaultImage = defaultImage;
}
public String getDefaultImage() {
return defaultImage;
}
4、图像加载
因为我们的应用仅仅是两者对聊,而例子中包含的是群聊,头像显示不正确。所以很重要的工作是TeamHeadSynthesizer中临时判断和加载单一图片。
图片的判断顺序为:先判断组合图片是否存在,再判断单一图片String defaultImage是否存在,最后判断图片资源id是否存在.
直接加载头像
public void load() {
if (multiImageData.size() == 0) {
if (!getImageUrl().isEmpty()) {
new Thread() {
@Override
public void run() {
super.run();
String newTargetID = MD5Utils.getMD5String(getImageUrl());
currentTargetID = newTargetID;
final String targetID = currentTargetID;
targetImageSize = maxWidth;//图片尺寸
//根据id获取存储的文件路径
final File file = new File(UIKitConstants.IMAGE_BASE_DIR + TeamHeadSynthesizer.this.currentTargetID);
boolean cacheBitmapExists = false;
if (file.exists() && file.isFile()) {
//文件存在,加载到内存
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
if (options.outWidth > 0 && options.outHeight > 0) {
//当前文件是图片
cacheBitmapExists = true;
}
}
if (!cacheBitmapExists) {
//缓存文件不存在,需要加载读取
//下载图片
try {
final Bitmap bitmap = asyncLoadImage(getImageUrl(), targetImageSize);
//所有图片加载成功,则保存合成图片
BitmapUtils.storeBitmap(file, bitmap);
//执行回调
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(bitmap, targetID, true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(file, targetID, true);
}
});
}
}
}.start();
} else {
imageView.setImageResource(getDefaultImage());
}
return;
}
String newTargetID = buildTargetSynthesizedId();
/*if (loadOk && null != imageView.getDrawable() && TextUtils.equals(currentTargetID, newTargetID)) {
//两次加载的图片是一样的,而且已经加载成功了,图片没有被回收,此时无需重复加载
return;
}*/
currentTargetID = newTargetID;
//初始化图片信息
int[] gridParam = calculateGridParam(multiImageData.size());
mRowCount = gridParam[0];
mColumnCount = gridParam[1];
targetImageSize = (maxWidth - (mColumnCount + 1) * mGap) / (mColumnCount == 1 ? 2 : mColumnCount);//图片尺寸
//imageView.setImageResource(multiImageData.getDefaultImageResId());
new Thread() {
@Override
public void run() {
super.run();
final String targetID = currentTargetID;
//根据id获取存储的文件路径
//String absolutePath = mContext.getFilesDir().getAbsolutePath();
final File file = new File(UIKitConstants.IMAGE_BASE_DIR + TeamHeadSynthesizer.this.currentTargetID);
boolean cacheBitmapExists = false;
if (file.exists() && file.isFile()) {
//文件存在,加载到内存
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
if (options.outWidth > 0 && options.outHeight > 0) {
//当前文件是图片
cacheBitmapExists = true;
}
}
if (!cacheBitmapExists) {
//缓存文件不存在,需要加载读取
boolean loadSuccess = asyncLoadImageList();
final Bitmap bitmap = synthesizeImageList();
//保存合成的图片文件
if (loadSuccess) {
//所有图片加载成功,则保存合成图片
BitmapUtils.storeBitmap(file, bitmap);
}
//执行回调
//判断当前图片的多个小图是否全部加载完全的,如果加载完全的,complete=true;
final boolean complete = loadSuccess;
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(bitmap, targetID, complete);
}
});
} else {
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(file, targetID, true);
}
});
}
}
}.start();
}
Callback callback = new Callback() {
@Override
public void onCall(Object obj, String targetID, boolean complete) {
//判断回调结果的任务id是否为同一批次的任务
if (!TextUtils.equals(currentTargetID, targetID))
{
return;
}
if (obj instanceof File) {
if (complete) loadOk = true;
imageView.setImageBitmap(BitmapFactory.decodeFile(((File) obj).getAbsolutePath()));
/*
Glide.with(mContext)
.load(((File) obj))
.into(imageView);*/
} else if (obj instanceof Bitmap) {
if (complete) loadOk = true;
imageView.setImageBitmap(((Bitmap) obj));
}
}
};
/**
* 生成合成图片的id,保证唯一性
*/
public String buildTargetSynthesizedId() {
int size = multiImageData.size();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < size; i++) {
String imageUrl = multiImageData.getImageUrls().get(i);
buffer.append(i + imageUrl);
}
return MD5Utils.getMD5String(buffer.toString());
}
interface Callback {
void onCall(Object object, String targetID, boolean complete);
}
改进
不过如果图像为空,异步加载会出现问题。空的图像被设置为最后一个imageurl。
这个方案是个修修补补的方案,并非最好,但是也没有必要重构了。
修改如下:(TeamHeadSynthesizer.java)
public void load() {
if (multiImageData.size() > 0) {
loadMultiImage();
}
String imageUrl = getImageUrl();
if (imageUrl.isEmpty()) {
imageView.setImageResource(getDefaultImage());
} else {
loadImageUrl();
}
}
private void loadMultiImage() {
String newTargetID = buildTargetSynthesizedId();
/*if (loadOk && null != imageView.getDrawable() && TextUtils.equals(currentTargetID, newTargetID)) {
//两次加载的图片是一样的,而且已经加载成功了,图片没有被回收,此时无需重复加载
return;
}*/
currentTargetID = newTargetID;
//初始化图片信息
int[] gridParam = calculateGridParam(multiImageData.size());
mRowCount = gridParam[0];
mColumnCount = gridParam[1];
targetImageSize = (maxWidth - (mColumnCount + 1) * mGap) / (mColumnCount == 1 ? 2 : mColumnCount);//图片尺寸
//imageView.setImageResource(multiImageData.getDefaultImageResId());
//根据id获取存储的文件路径
//String absolutePath = mContext.getFilesDir().getAbsolutePath();
final File file = new File(UIKitConstants.IMAGE_BASE_DIR + TeamHeadSynthesizer.this.currentTargetID);
boolean cacheBitmapExists = false;
if (file.exists() && file.isFile()) {
//文件存在,加载到内存
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
if (options.outWidth > 0 && options.outHeight > 0) {
//当前文件是图片
cacheBitmapExists = true;
}
}
if (!cacheBitmapExists) {
//缓存文件不存在,需要加载读取
new Thread() {
@Override
public void run() {
super.run();
final String targetID = currentTargetID;
boolean loadSuccess = asyncLoadImageList();
final Bitmap bitmap = synthesizeImageList();
//保存合成的图片文件
if (loadSuccess) {
//所有图片加载成功,则保存合成图片
BitmapUtils.storeBitmap(file, bitmap);
}
//执行回调
//判断当前图片的多个小图是否全部加载完全的,如果加载完全的,complete=true;
final boolean complete = loadSuccess;
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(bitmap, targetID, complete);
}
});
}
}.start();
} else {
final String targetID = currentTargetID;
callback.onCall(file, targetID, true);
}
}
private void loadImageUrl() {
String imageUrl = getImageUrl();
String newTargetID = MD5Utils.getMD5String(imageUrl);
currentTargetID = newTargetID;
targetImageSize = maxWidth;//图片尺寸
//根据id获取存储的文件路径
final File file = new File(UIKitConstants.IMAGE_BASE_DIR + TeamHeadSynthesizer.this.currentTargetID);
boolean cacheBitmapExists = false;
if (file.exists() && file.isFile()) {
//文件存在,加载到内存
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
if (options.outWidth > 0 && options.outHeight > 0) {
//当前文件是图片
cacheBitmapExists = true;
}
}
if (!cacheBitmapExists) {
//缓存文件不存在,需要加载读取
//下载图片
new Thread() {
@Override
public void run() {
super.run();
String imageUrl = getImageUrl();
if (imageUrl.isEmpty()) {
return;
}
try {
final String targetID = currentTargetID;
final Bitmap bitmap = asyncLoadImage(imageUrl, targetImageSize);
//所有图片加载成功,则保存合成图片
BitmapUtils.storeBitmap(file, bitmap);
//执行回调
imageView.post(new Runnable() {
@Override
public void run() {
callback.onCall(bitmap, targetID, true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} else {
final String targetID = currentTargetID;
callback.onCall(file, targetID, true);
}
return;
}
Callback callback = new Callback() {
@Override
public void onCall(Object obj, String targetID, boolean complete) {
//判断回调结果的任务id是否为同一批次的任务
if (!TextUtils.equals(currentTargetID, targetID)) {
return;
}
String imageUrl = getImageUrl();
if (imageUrl.isEmpty()) {
return;
}
if (obj instanceof File) {
if (complete) loadOk = true;
imageView.setImageBitmap(BitmapFactory.decodeFile(((File) obj).getAbsolutePath()));
/*
Glide.with(mContext)
.load(((File) obj))
.into(imageView);*/
} else if (obj instanceof Bitmap) {
if (complete) loadOk = true;
imageView.setImageBitmap(((Bitmap) obj));
}
}
};
修改之后,用户头像能够正常使用了。
相关问题
测试,IM登录之后直接调用还获取不到头像
ImFuncition.imloginForDev(userId, userSig, ((code, msg) -> onResult(context, code, msg)));
private static void onResult(Context context, int code, String msg) {
MyToast.show(context, msg);
if (code == 0) {
}
}
TIMFriendshipManager.getInstance().getSelfProfile(new TIMValueCallBack<TIMUserProfile>() {
@Override
public void onError(int code, String desc) {
UIUtils.toastLongMessage("获取咨询的本地用户信息失败: " + code + "=" + desc);
}
@Override
public void onSuccess(TIMUserProfile timUserProfile) {
QLog.i("TAG", "imLogin getSelfProfile icourl=" + timUserProfile.getFaceUrl());
String face = timUserProfile.getFaceUrl();//获取用户头像URL
}
});
//查询所有的用户信息
String myAccount = INSTANCES.getImAccount();
List<String> myAccounts = new ArrayList<>();
myAccounts.add(myAccount);
myAccounts.add("sunshineim63");
TIMFriendshipManager.getInstance().getUsersProfile(myAccounts, true, new TIMValueCallBack<List<TIMUserProfile>>(){
@Override
public void onError(int code, String desc) {
}
@Override
public void onSuccess(List<TIMUserProfile> timUserProfiles) {
QLog.i("TAG", "imLogin getUsersProfile size=" + timUserProfiles.size());
}
});
TIMFriendshipManager.getInstance().getFriendList(new TIMValueCallBack<List<TIMFriend>>() {
@Override
public void onError(int code, String desc) {
UIUtils.toastLongMessage("获取咨询的好友用户信息失败: " + code + "=" + desc);
}
@Override
public void onSuccess(List<TIMFriend> timFriends) {
QLog.i("TAG", "imLogin getFriendList size=" + timFriends.size());
List<String> friends = new ArrayList<>();
for (TIMFriend friend : timFriends) {
friends.add(friend.getIdentifier());
}
//查询所有的用户信息
TIMFriendshipManager.getInstance().getUsersProfile(friends, true, new TIMValueCallBack<List<TIMUserProfile>>(){
@Override
public void onError(int code, String desc) {
UIUtils.toastLongMessage("获取咨询的好友用户信息失败: " + code + "=" + desc);
}
@Override
public void onSuccess(List<TIMUserProfile> timUserProfiles) {
QLog.i("TAG", "imLogin getUsersProfile size=" + timUserProfiles.size());
}
});
}
});
在ChatAdapter和SessionAdapter展示的时候可以获取到,但是应该避免列表刷新时频繁请求后台。
那么就需要在查询会话和打开会话详情的时候获取一次。
用户配置发生更新
userConfig.setRefreshListener(new TIMRefreshListener() {
@Override
public void onRefresh() {
}
@Override
public void onRefreshConversation(List<TIMConversation> conversations) {
SessionManager.getInstance().onRefreshConversation(conversations);
if (TUIKit.getBaseConfigs().getIMEventListener() != null) {
TUIKit.getBaseConfigs().getIMEventListener().onRefreshConversation(conversations);
}
}
});
当会话配置信息更新的时候,重新获取一遍用户信息,当用户更改图片,让重新进入才会改变。(刷新会话,或者重新进入聊天界面)
public class SessionManager implements UIKitRequestHandler, TIMRefreshListener, UIKitMessageRevokedManager.MessageRevokeHandler {
//部分会话刷新(包括多终端已读上报同步)
public void onRefreshConversation(List<TIMConversation> conversations) {
//会话中的未读消息
List<String> timUserAccounts = new ArrayList<>();
ArrayList<SessionInfo> infos = new ArrayList<>();
for (int i = 0; i < conversations.size(); i++) {
TIMConversation conversation = conversations.get(i);
QLog.i(TAG, "onRefreshConversation::" + conversation);
SessionInfo sessionInfo = TIMConversation2SessionInfo(conversation);
if (sessionInfo != null) {
infos.add(sessionInfo);
String identifier = conversation.getPeer();
timUserAccounts.add(identifier);
}
}
if (infos.size() == 0)
return;
if (timUserAccounts.size() > 0) {
TUIKit.getUserInfo(timUserAccounts);//更新用户信息
}
//..
mProvider.setDataSource(sortSessions(dataSource));
}
头像圆角问题和点击位置
public abstract class ChatPanel extends LinearLayout implements IChatPanel {
@Override
public void onUserIconClick(View view, int position, MessageInfo messageInfo) {
UIUtils.toastLongMessage("头像点击");
}
public abstract class DynamicChatUserIconView extends DynamicLayoutView<MessageInfo> {
//设置聊天头像圆角
public void setIconRadius(int iconRadius) {
this.iconRadius = UIUtils.getPxByDp(iconRadius);
}