Android 集成环信昵称和头像显示问题

in Android with 0 comment

环信本身并不提供设置头像方法,但是已经提供思路来解决这个问题

chat_nick.png

方法一:从APP服务器获取昵称和头像

昵称和头像的获取:当收到一条消息(群消息)时,得到发送者的用户ID,然后查找手机本地数据库是否有此用户ID的昵称和头像,如没有则调用APP服务器接口通过用户ID查询出昵称和头像,然后保存到本地数据库和缓存,下次此用户发来信息即可直接查询缓存或者本地数据库,不需要再次向APP服务器发起请求。
昵称和头像的更新:当点击发送者头像时加载用户详情时从APP服务器查询此用户的具体信息然后更新本地数据库和缓存。当用户自己更新昵称或头像时,也可以发送一条透传消息到其他用户和用户所在的群,来更新该用户的昵称和头像。

方法二:从消息扩展中获取昵称和头像

昵称和头像的获取:把用户基本的昵称和头像的URL放到消息的扩展中,通过消息传递给接收方,当收到一条消息时,则能通过消息的扩展得到发送者的昵称和头像URL,然后保存到本地数据库和缓存。当显示昵称和头像时,请从本地或者缓存中读取,不要直接从消息中把赋值拿给界面(否则当用户昵称改变后,同一个人会显示不同的昵称)。
昵称和头像的更新:当扩展消息中的昵称和头像 URI 与当前本地数据库和缓存中的相应数据不同的时候,需要把新的昵称保存到本地数据库和缓存,并下载新的头像并保存到本地数据库和缓存。

这里环信只提供一些说明并没有Demo展示 这里通过扩展字段来实现头像和昵称展示,走到这里表示你已经集成过环信并且能通信。

扩展字段实现昵称和头像展示

第一步保存自己昵称和头像


    private void initListData(UserBean.DataBean data) {

        SharePrefUtil.saveString(mContext, Constant.USER_NAME, data.getUsername());
        SharePrefUtil.saveString(mContext, Constant.USER_ID, data.getUser_id());
        SharePrefUtil.saveString(mContext, Constant.USER_PHONE, data.getPhone());
        SharePrefUtil.saveString(mContext, Constant.USER_NUMBER, data.getUser_number());
        SharePrefUtil.saveString(mContext, Constant.USER_NICK, data.getUser_nick());
        SharePrefUtil.saveString(mContext, Constant.HEAD_IMG, data.getHead_img());
        SharePrefUtil.saveString(mContext, Constant.SEX, data.getSex());
        SharePrefUtil.saveString(mContext, Constant.SIGN_NAME, data.getSign_name());
        SharePrefUtil.saveString(mContext, Constant.TYPE, data.getType());
        SharePrefUtil.saveString(mContext, Constant.COMMISION, data.getCommision());
        SharePrefUtil.saveString(mContext, Constant.PASSWORD, data.getPassword());


        loginHX(data.getUser_number(), new String(Base64.decode(data.getPassword().getBytes(), Base64.DEFAULT)));

    }

    private void loginHX(final String user_number, final String password) {

        // After logout,the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(SharePrefUtil.getString(mContext, Constant.USER_NAME, ""));

        //login
        EMClient.getInstance().login(user_number, password, new EMCallBack() {

            @Override
            public void onSuccess() {

                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                // get user's info (this should be get from App's server or 3rd party service)
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, final String error) {
                LogUtil.i(user_number + "-------" + password + "-----------" + error);
                logOut();
                runOnUiThread(new Runnable() {
                    public void run() {
                        UIUtils.showToast(mContext, error);
                    }
                });
            }
        });
    }

这里保存登录信息到SP中,给对方发送消息时要用到,一下是SP工具类 用自己的也行这都无所谓了

package com.shangyukeji.lovehostel.utils;


import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class SharePrefUtil {

    private static String tag = SharePrefUtil.class.getSimpleName();
    private final static String SP_NAME = "user_info";
    private static SharedPreferences sp;


    /**
     * 保存布尔值
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveBoolean(Context context, String key, boolean value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putBoolean(key, value).apply();
    }

    /**
     * 保存字符串
     *
     * @param context
     * @param key
     * @param value
     */

    public static void saveString(Context context, String key, String value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putString(key, value).apply();

    }

    public static void clear(Context context) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().clear().apply();
    }

    /**
     * 清除某一个sp
     *
     * @param context
     * @param key
     */
    public static void clear(Context context, String key) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().remove(key).apply();
    }

    /**
     * 保存long型
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveLong(Context context, String key, long value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putLong(key, value).apply();
    }

    /**
     * 保存int型
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveInt(Context context, String key, int value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putInt(key, value).apply();
    }

    /**
     * 保存float型
     *
     * @param context
     * @param key
     * @param value
     */
    public static void saveFloat(Context context, String key, float value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putFloat(key, value).apply();
    }

    /**
     * 获取字符值
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static String getString(Context context, String key, String defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getString(key, defValue);
    }

    /**
     * 获取int值
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static int getInt(Context context, String key, int defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getInt(key, defValue);
    }

    /**
     * 获取long值
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static long getLong(Context context, String key, long defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getLong(key, defValue);
    }

    /**
     * 获取float值
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static float getFloat(Context context, String key, float defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getFloat(key, defValue);
    }

    /**
     * 获取布尔值
     *
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static boolean getBoolean(Context context, String key,
                                     boolean defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getBoolean(key, defValue);
    }

}

发送消息 EaseChatFragment

    protected void sendMessage(EMMessage message){
        if (message == null) {
            return;
        }
        if(chatFragmentHelper != null){
            //set extension
            chatFragmentHelper.onSetMessageAttributes(message);
        }
        message.setChatType(ChatType.Chat);
        message.setAttribute("userPic", Urls.IMAGE_URL + SharePrefUtil.getString(getContext(), "head_img", ""));
        message.setAttribute("userName", SharePrefUtil.getString(getContext(), "user_nick", ""));
//        if (chatType == EaseConstant.CHATTYPE_GROUP){
//            message.setChatType(ChatType.GroupChat);
//        }else if(chatType == EaseConstant.CHATTYPE_CHATROOM){
//            message.setChatType(ChatType.ChatRoom);
//        }
        //Add to conversation
        EMClient.getInstance().chatManager().saveMessage(message);
        //refresh ui
        if(isMessageListInited) {
            messageList.refreshSelectLast();
        }
    }

我这里集成的是easeui EaseChatFragment 搜索sendMessage()方法,这里就是我们发送消息必须经过的方法,不管是音频,视频, 文字,图片... 通过message封装扩展消息字段, 上面我们添加两个字段 userPic(用户头像)userName(用户昵称),跟IOS那边通好气双方字段统一

接收消息 DemoHelper

    
     /**
     * Global listener
     * If this event already handled by an activity, you don't need handle it again
     * activityList.size() <= 0 means all activities already in background or not in Activity Stack
     */
    protected void registerMessageListener() {
        messageListener = new EMMessageListener() {
            private BroadcastReceiver broadCastReceiver = null;

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());


                    message.setMsgTime(System.currentTimeMillis());
                    //************接收并处理扩展消息***********************
                    String userName = message.getStringAttribute("userName", "");
                    String userPic = message.getStringAttribute("userPic", "");
                    String hxIdFrom = message.getFrom();
                    EaseUser easeUser = new EaseUser(hxIdFrom);
                    easeUser.setAvatar(userPic);
                    easeUser.setNick(userName);

                    // 存入内存
                    getContactList();
                    contactList.put(hxIdFrom, easeUser);
                    // 存入db
                    UserDao dao = new UserDao(appContext);
                    List<EaseUser> users = new ArrayList<EaseUser>();
                    users.add(easeUser);
                    dao.saveContactList(users);

                    getModel().setContactSynced(true);





                    // in background, do not refresh UI, notify it in notification bar
                    if(!easeUI.hasForegroundActivies()){
                        getNotifier().onNewMsg(message);
                    }
                }
            }
            
            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d(TAG, "receive command message");
                    //get message body
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                    final String action = cmdMsgBody.action();//获取自定义action
                    //red packet code : 处理红包回执透传消息
//                    if(!easeUI.hasForegroundActivies()){
//                        if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)){
//                            RedPacketUtil.receiveRedPacketAckMessage(message);
//                            broadcastManager.sendBroadcast(new Intent(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION));
//                        }
//                    }

                    if (action.equals("__Call_ReqP2P_ConferencePattern")) {
                        String title = message.getStringAttribute("em_apns_ext", "conference call");
                        Toast.makeText(appContext, title, Toast.LENGTH_LONG).show();
                    }
                    //end of red packet code
                    //获取扩展属性 此处省略
                    //maybe you need get extension of your message
                    //message.getStringAttribute("");
                    EMLog.d(TAG, String.format("Command:action:%s,message:%s", action,message.toString()));
                }
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
            }
            
            @Override
            public void onMessageDelivered(List<EMMessage> message) {
            }

            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                for (EMMessage msg : messages) {
                    if(msg.getChatType() == ChatType.GroupChat && EaseAtMessageHelper.get().isAtMeMsg(msg)){
                        EaseAtMessageHelper.get().removeAtMeGroup(msg.getTo());
                    }
                    EMMessage msgNotification = EMMessage.createReceiveMessage(Type.TXT);
                    EMTextMessageBody txtBody = new EMTextMessageBody(String.format(appContext.getString(R.string.msg_recall_by_user), msg.getFrom()));
                    msgNotification.addBody(txtBody);
                    msgNotification.setFrom(msg.getFrom());
                    msgNotification.setTo(msg.getTo());
                    msgNotification.setUnread(false);
                    msgNotification.setMsgTime(msg.getMsgTime());
                    msgNotification.setLocalTime(msg.getMsgTime());
                    msgNotification.setChatType(msg.getChatType());
                    msgNotification.setAttribute(Constant.MESSAGE_TYPE_RECALL, true);
                    msgNotification.setStatus(Status.SUCCESS);
                    EMClient.getInstance().chatManager().saveMessage(msgNotification);
                }
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                EMLog.d(TAG, "change:");
                EMLog.d(TAG, "change:" + change);
            }
        };
        
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }


搜索registerMessageListener()方法,通过注释我们可以知道这个方法是用来监听消息的。 这里我们只需要关注onMessageReceived()回调方法,接收消息也是个EMMessage对象,这里封装这对方发送数据当然包括扩展字段,这里将消息封装到EaseUser对象中并缓存到本地,通知刷新UI。这里我们不必关心只需要取出来存起来即可。

取出來用 DemoHelper

    private EaseUser getUserInfo(String username){
        // To get instance of EaseUser, here we get it from the user list in memory
        // You'd better cache it if you get it from your server
        EaseUser user = null;
        if (contactList != null && contactList.containsKey(username)) {

        } else { // 如果内存中没有,则将本地数据库中的取出到内存中。
            getContactList();
        }

        user = contactList.get(username);
        if(user == null){
            user = new EaseUser(username);
        } else {
            if(TextUtils.isEmpty(user.getNick())){ // 如果名字为空,则显示环信号码
                user.setNick(user.getUsername());
            }
        }

//        if(username.equals(EMClient.getInstance().getCurrentUser()))
//            return getUserProfileManager().getCurrentUserInfo();
//        user = getContactList().get(username);
//        if(user == null && getRobotList() != null){
//            user = getRobotList().get(username);
//        }

        // if user is not in your contacts, set inital letter for him/her
//        if(user == null){
//            user = new EaseUser(username);
//            EaseCommonUtils.setUserInitialLetter(user);
//        }
        return user;
    }
    

不管你是发送者亦或者是接受者都需要取,取得就是存到本地的数据,在DemoHelper中搜索此方法,展示头像则在EaseRowChat 我们找到setUpBaseView()方法,我们只需找到一下方法即可

        }
//*********************************展示头像*******************************************//        
        if(userAvatarView != null) {
            //set nickname and avatar
            if (message.direct() == Direct.SEND) {
//                EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
                EaseUserUtils.setUserAvatarExtend(context, SharePrefUtil.getString(context, "head_img", ""), userAvatarView);

//                EaseUserUtils.setUserAvatarExtend(context, SharePrefUtil.getString(context, "head_img", ""), userAvatarView);
            } else {
                EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);

//                EaseUserUtils.setUserAvatarExtend(context, SharePrefUtil.getString(context, "from_head_img", ""), userAvatarView);
//                EaseUserUtils.setUserNick(message.getFrom(), usernickView);
            }
        }
//*********************************展示头像*******************************************//  

这里展示的一个发送者头像一个接受者头像,如果只显示对方头像自己可以通过展示保存到SP中的自己的头像就行了

Responses