Display of Huanxin's Avatar and nickname

Keywords: Database Fragment Mobile

Display of Huanxin's Avatar and nickname - based on Easeui

I am a college student. I used Huanxin to participate in the competition. I summarize and record the display method of Huanxin's head image and nickname (suffering).

1. First of all, you need to save your nickname and avatar locally when you log in successfully. When you send a message, you need to send your nickname and avatar to the other party.

SpUtils.getInstance().save("userNick",userInfo.getrNick());
SpUtils.getInstance().save("userAvatar",userInfo.getImage());

SpUtils is a tool class that uses SharedPreferences to cache information.

2. Then in the chat listening of EaseChatFragment, in the onSetMessageAttributes method, send your nickname and avatar as the extended message. (the fragment of my chat is user-defined, and does not inherit easechattfragment. Therefore, you need to set the listening, rewrite the callback method and replace my fragment separately for the defined easechattfragment. If you are the inherited easechattfragment, you can directly rewrite the onSetMessageAttributes callback method in the fragment class.)

easeChatFragment.setChatFragmentListener(new EaseChatFragment.EaseChatFragmentHelper() {
    @Override
    public void onSetMessageAttributes(EMMessage message) {
        //Set the user nickname to send the extended message
        message.setAttribute(Constant.ChatUserNick, SpUtils.getInstance().getString("userNick",""));
        //Set the profile of the user to send the extended message
        message.setAttribute(Constant.ChatUserPic, SpUtils.getInstance().getString("userAvatar",""));
    }
}

3. Next, prepare a display class based on the avatar and nickname processing, as follows:

public class HxEaseuiHelper {

    private static HxEaseuiHelper instance = null;
    protected EMMessageListener messageListener = null;
    private Context mContext;
    private String username;
    private EaseUI easeUI;
    private Map<String, EaseUser> contactList;

    public synchronized static HxEaseuiHelper getInstance() {
        if (instance == null) {
            instance = new HxEaseuiHelper();
        }
        return instance;
    }


    public void init(Context context) {
        EMOptions options = initChatOptions();
        //use default options if options is null
        mContext = context;

        //Get easeui instance
        easeUI = EaseUI.getInstance();
        //Initialize easeui
        easeUI.init(mContext,options);

        setEaseUIProviders();
        //Set global listening
        setGlobalListeners();

        //When making packaging confusion, turn off the debug mode to avoid unnecessary resource consumption
        EMClient.getInstance().setDebugMode(true);
    }


    private EMOptions initChatOptions(){
        EMOptions options = new EMOptions();
        options.setAcceptInvitationAlways(false);

        options.setAutoAcceptGroupInvitation(false);

        return options;
    }

    protected void setEaseUIProviders() {
        EaseUI easeUI1 = EaseUI.getInstance();
        // set profile provider if you want easeUI to handle avatar and nickname
        easeUI1.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
            @Override
            public EaseUser getUser(String username) {
                return getUserInfo(username);
            }
        });
    }

    public EaseUser getUserInfo(String username) {
        //Get the EaseUser instance, which is read from memory
        //If you read from the server, it's better to cache locally
        EaseUser user = null;
        if(username == null) {
            Toast.makeText(mContext, username+"", Toast.LENGTH_SHORT).show();
            return null;
        }
//If the user is himself / herself, set his / her own avatar
        if(username.equals(EMClient.getInstance().getCurrentUser())){
            user=new EaseUser(username);
            user.setAvatar((String) SpUtils.getInstance().getString("userAvatar",""));
            user.setNick((String)SpUtils.getInstance().getString("userName",""));
            return user;
        }
        //Receive other people's messages and set their avatars
        if (contactList!=null && contactList.containsKey(username)){
            user=contactList.get(username);
        }else { //If there is no in memory, take out the in local database to memory
            contactList=getContactList();
            user=contactList.get(username);
        }

        //Initialize if the user is not your contact
        if(user == null){
            user = new EaseUser(username);
            EaseCommonUtils.setUserInitialLetter(user);
        }else {
            if (TextUtils.isEmpty(user.getAvatar())){//If the name is blank, the ring letter number will be displayed
                user.setNick(user.getUsername());
            }
        }

        return user;
    }

    /**
     *Get all contact information
     *
     * @return
     */
    public Map<String, EaseUser> getContactList() {
        if (isLoggedIn() && contactList == null) {
            contactList = new HashMap<>();
 //UserInfo is your own user's bean class (defined user class)
//Get your own contact information through the local database
            List<UserInfo> users = Model.getInstance().getDBManager().getContactTableDao().getContacts();
            for (UserInfo userInfo: users){
                EaseUser easeUser = new EaseUser(userInfo.getHxid());
                easeUser.setNick(userInfo.getName());
                easeUser.setAvatar(userInfo.getImage());
                contactList.put(userInfo.getHxid(),easeUser);
            }
        }

        // return a empty non-null object to avoid app crash
        if(contactList == null){
            return new Hashtable<String, EaseUser>();
        }

        return contactList;
    }
    /**
     * if ever logged in
     *
     * @return
     */
    public boolean isLoggedIn() {
        return EMClient.getInstance().isLoggedInBefore();
    }

    /**
     * set global listener
     */
    protected void setGlobalListeners(){
        registerMessageListener();
    }

    /**
     * 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());

                    //Receive and process extended messages
                    String userName=message.getStringAttribute(Constant.ChatUserNick,"");
                    String userPic=message.getStringAttribute(Constant.ChatUserPic,"");
                    String hxIdFrom=message.getFrom();
                    EaseUser easeUser=new EaseUser(hxIdFrom);
                    easeUser.setAvatar(userPic);
                    easeUser.setNick(userName);


                    //Memory in memory
                    getContactList();
                    contactList.put(hxIdFrom,easeUser);

                    UserInfo userInfo = new UserInfo(hxIdFrom);
                    userInfo.setName(userName);
                    userInfo.setImage(userPic);

                    //Save to db, save the contact information to the local database. I create my own contact database for all users on my mobile phone
                    ContactTableDao dao = Model.getInstance().getDBManager().getContactTableDao();
                    List<UserInfo> users=new ArrayList<UserInfo>();
                    users.add(userInfo);
                    dao.saveContacts(users,true);

                    // in background, do not refresh UI, notify it in notification bar
                    //Set local message push notification
                    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
                    //end of red packet code
                    //Get extended properties omitted here
                    //maybe you need get extension of your message
                    //message.getStringAttribute("");

                    //Receive and process extended messages
                    String userName=message.getStringAttribute(Constant.ChatUserNick,"");
                    String userPic=message.getStringAttribute(Constant.ChatUserPic,"");
                    String hxIdFrom=message.getFrom();
                    EaseUser easeUser=new EaseUser(hxIdFrom);
                    easeUser.setAvatar(userPic);
                    easeUser.setNick(userName);


                    //Memory in memory
                    getContactList();
                    contactList.put(hxIdFrom,easeUser);

                    UserInfo userInfo = new UserInfo(hxIdFrom);
                    userInfo.setName(userName);
                    userInfo.setImage(userPic);

                    //Deposit in db
                    ContactTableDao dao = Model.getInstance().getDBManager().getContactTableDao();
                    List<UserInfo> users=new ArrayList<UserInfo>();
                    users.add(userInfo);
                    dao.saveContacts(users,true);

                    // in background, do not refresh UI, notify it in notification bar
                    //Set local message push notification
                    if(!easeUI.hasForegroundActivies()){
                        getNotifier().onNewMsg(message);
                    }
                }
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> list) {

            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> list) {

            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {

            }
        };

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }
    public EaseNotifier getNotifier(){
        return easeUI.getNotifier();
    }
}

4.After completion, you need to Application Class:
public class IMApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        HxEaseuiHelper.getInstance().init(this);
    }

}

5. At this point, the display of the avatar and nickname is completed. Finally, it is necessary to check the EaseChatRow class in the easeui:

private void setUpBaseView() {
     ......
     //set nickname and avatar
    if(message.direct() == Direct.SEND){
        EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
    }else{
        EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
        EaseUserUtils.setUserNick(message.getFrom(), usernickView);
    }
    ......
}

Posted by jacobelias on Thu, 02 Jan 2020 23:29:42 -0800