环信自定义消息类型——名片

名片分享.jpg

近来的需求需要对环信进行定制化,实现如图所示的名片分享功能。
环信聊天中的每一种消息类型都由一种对应的ChatRow来控制,相当于adapter里的Holder。

自定义GroupCardChatRow继承EaseChatRow,在 onBubbleClick()中重写消息的点击事件。

public class GroupCardChatRow extends EaseChatRow {

    private TextView contentView;
    private TextView tvGroupName;
    private ImageView imgGroup;
    private TextView tvIntroduce;
    private TextView tvNember;
    private String gid;

    public GroupCardChatRow(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

   //接收和发送名片消息的布局
    @Override
    protected void onInflateView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                R.layout.ease_row_received_group_card : R.layout.ease_row_sent_group_card, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);
        tvGroupName = (TextView) findViewById(R.id.tv_group_name);
        imgGroup = (ImageView) findViewById(R.id.img_group);
        tvIntroduce = (TextView) findViewById(tv_introduce);
        tvNember = (TextView) findViewById(R.id.tv_number);
    }

    @Override
    public void onSetUpView() {

        try {
            Map<String, String> map = new HashMap<>();
            map = new Gson().fromJson(message.getStringAttribute(EaseConstant.EXTRA_GROUP_CARD), Map.class);
            String name = map.get("name");
            String description = map.get("description");
            String pic = map.get("pic");
            String memberCount = map.get("member_count");
            gid = map.get("gid");
            tvGroupName.setText(name);
            ImageUtil.loadImageWithView(context, pic, imgGroup);
            tvIntroduce.setText(description);
            tvNember.setText("群成员人数:" + memberCount + "人");

        } catch (HyphenateException e) {
            e.printStackTrace();
        }
        handleTextMessage();
    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
            setMessageSendCallback();
            switch (message.status()) {
                case CREATE:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.GONE);
                    break;
                case FAIL:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS:
                    progressBar.setVisibility(View.VISIBLE);
                    statusView.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        } else {
            if (!message.isAcked() && message.getChatType() == ChatType.Chat) {
                try {
                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        // TODO Auto-generated method stub

        Intent intent = new Intent(context, GroupCardActivity.class);
        intent.putExtra("gid", gid);
        context.startActivity(intent);


    }
}

环信中消息类型包括txt、音频、位置、文件、图片、视频类型,群名片也属于txt类型,我们通过message的拓展字段来区分消息类型是否为名片。

发送群名片消息的时候给message添加群名片拓展字段,发送正常txt消息时不添加拓展字段,在adapter中根据拓展字段是否为空来判断消息类型


protected void sendMessage(UserPageBean userPageBean) {

        EMMessage message = EMMessage.createTxtSendMessage("群邀请", userPageBean.getIm_namelogin());

        message.setAttribute(EaseConstant.EXTRA_GROUP_CARD, groupMessage);
        EMClient.getInstance().chatManager().sendMessage(message);

    }

在EaseMessageAdapter中新添加两种消息类型
MESSAGE_TYPE_SENT_GROUP_CARD 、 MESSAGE_TYPE_RECV_GROUP_CARD

修改 getItemViewType和createChatRow方法,在其中添加这两种消息类型

public class EaseMessageAdapter extends BaseAdapter {

    private final static String TAG = "msg";

    private Context context;
    private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
    private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
    private static final int HANDLER_MESSAGE_SEEK_TO = 2;

    private static final int MESSAGE_TYPE_RECV_TXT = 0;
    private static final int MESSAGE_TYPE_SENT_TXT = 1;
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
    private static final int MESSAGE_TYPE_SENT_LOCATION = 3;
    private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 5;
    private static final int MESSAGE_TYPE_SENT_VOICE = 6;
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;
    private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
    private static final int MESSAGE_TYPE_SENT_FILE = 10;
    private static final int MESSAGE_TYPE_RECV_FILE = 11;
    private static final int MESSAGE_TYPE_SENT_EXPRESSION = 12;
    private static final int MESSAGE_TYPE_RECV_EXPRESSION = 13;
    private static final int MESSAGE_TYPE_SENT_GROUP_CARD = 14;
    private static final int MESSAGE_TYPE_RECV_GROUP_CARD = 15;



    public int itemTypeCount;

    // reference to conversation object in chatsdk
    private EMConversation conversation;
    EMMessage[] messages = null;

    private String toChatUsername;
    private boolean isTrueName;
    private boolean isBidTureName;

    private MessageListItemClickListener itemClickListener;
    private EaseCustomChatRowProvider customRowProvider;

    private boolean showUserNick;
    private boolean showAvatar;
    private Drawable myBubbleBg;
    private Drawable otherBuddleBg;
    private String orderId;
    private String type;

    private ListView listView;
    private boolean isbidded;
    private boolean isbiddedMessage;

    public EaseMessageAdapter(Context context, String username, int chatType, ListView listView, boolean isTrueName, String orderId, boolean isBidTureName, String type, boolean isBidded) {
        this.context = context;
        this.listView = listView;
        toChatUsername = username;
        this.isTrueName = isTrueName;
        this.orderId = orderId;
        this.isBidTureName = isBidTureName;
        this.type = type;
        this.conversation = EMClient.getInstance().chatManager().getConversation(username, EaseCommonUtils.getConversationType(chatType), true);
        this.isbidded = isBidded;
    }

    List<EMMessage> msgs1;
    Handler handler = new Handler() {
        private void refreshList() {
            // you should not call getAllMessages() in UI thread
            // otherwise there is problem when refreshing UI and there is new message arrive
            List<EMMessage> msgs = conversation.getAllMessages();

            List<String> friendsMessageList = new ArrayList<>();
            List<String> orderUnBidMessageList = new ArrayList<>();
            List<String> orderBidMessageList = new ArrayList<>();
            String msgId;
            for (int i = 0; i < msgs.size(); i++) {
                msgId = msgs.get(i).getMsgId();
                String msgOrderId = null;

//                      try {
                msgOrderId = (String) msgs.get(i).ext().get(EaseConstant.EXTRA_ORDER_ID);
                isbiddedMessage = (boolean) msgs.get(i).ext().get(EaseConstant.EXTRA_IS_BIDDED);

//                          msgOrderId = msgs.get(i).getStringAttribute(EaseConstant.EXTRA_ORDER_ID);
//                      } catch (HyphenateException e) {
//                          e.printStackTrace();
//                      }

                if (msgOrderId == null || msgOrderId.equals("")) {
                    friendsMessageList.add(msgId);
                } else if (msgOrderId.equals(orderId)) {
                    if (isbidded){
                        if (isbiddedMessage){
                            orderBidMessageList.add(msgId);
                        }
                    }else {
                        if (!isbiddedMessage){
                            orderUnBidMessageList.add(msgId);
                        }
                    }

                }

            }

            if (orderId == null) {
                msgs1 = conversation.loadMessages(friendsMessageList);
            } else {
                if (isbidded){
                    msgs1 = conversation.loadMessages(orderBidMessageList);
                }else {
                    msgs1 = conversation.loadMessages(orderUnBidMessageList);
                }
            }


            messages = msgs1.toArray(new EMMessage[msgs1.size()]);
            conversation.markAllMessagesAsRead();
            notifyDataSetChanged();


        }


        @Override
        public void handleMessage(android.os.Message message) {
            switch (message.what) {
                case HANDLER_MESSAGE_REFRESH_LIST:
                    refreshList();
                    break;
                case HANDLER_MESSAGE_SELECT_LAST:
                    if (messages.length > 0) {
                        listView.setSelection(messages.length - 1);
                    }
                    break;
                case HANDLER_MESSAGE_SEEK_TO:
                    int position = message.arg1;
                    listView.setSelection(position);
                    break;
                default:
                    break;
            }
        }
    };

    public void refresh() {
        if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
            return;
        }
        android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
        handler.sendMessage(msg);

    }

    /**
     * refresh and select the last
     */
    public void refreshSelectLast() {
        final int TIME_DELAY_REFRESH_SELECT_LAST = 100;
        handler.removeMessages(HANDLER_MESSAGE_REFRESH_LIST);
        handler.removeMessages(HANDLER_MESSAGE_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_REFRESH_LIST, TIME_DELAY_REFRESH_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SELECT_LAST, TIME_DELAY_REFRESH_SELECT_LAST);
    }

    /**
     * refresh and seek to the position
     */
    public void refreshSeekTo(int position) {
        handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
        android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_SEEK_TO);
        msg.arg1 = position;
        handler.sendMessage(msg);
    }


    public EMMessage getItem(int position) {
        if (messages != null && position < messages.length) {
            return messages[position];
        }
        return null;
    }

    public long getItemId(int position) {
        return position;
    }

    /**
     * get count of messages
     */
    public int getCount() {
        return messages == null ? 0 : messages.length;
    }

    /**
     * get number of message type, here 14 = (EMMessage.Type) * 2
     */
    public int getViewTypeCount() {
        if (customRowProvider != null && customRowProvider.getCustomChatRowTypeCount() > 0) {
            return customRowProvider.getCustomChatRowTypeCount() + 16;
        }
        return 16;
    }


    /**
     * get type of item
     */
    public int getItemViewType(int position) {
        EMMessage message = getItem(position);
        if (message == null) {
            return -1;
        }

        if (customRowProvider != null && customRowProvider.getCustomChatRowType(message) > 0) {
            return customRowProvider.getCustomChatRowType(message) + 13;
        }

        if (message.getType() == EMMessage.Type.TXT) {
            if (message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_EXPRESSION : MESSAGE_TYPE_SENT_EXPRESSION;
            }

            try {
                if (!TextUtils.isEmpty(message.getStringAttribute(EaseConstant.EXTRA_GROUP_CARD))){
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_GROUP_CARD : MESSAGE_TYPE_SENT_GROUP_CARD;
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
        }
        if (message.getType() == EMMessage.Type.IMAGE) {
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SENT_IMAGE;

        }
        if (message.getType() == EMMessage.Type.LOCATION) {
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LOCATION : MESSAGE_TYPE_SENT_LOCATION;
        }
        if (message.getType() == EMMessage.Type.VOICE) {
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SENT_VOICE;
        }
        if (message.getType() == EMMessage.Type.VIDEO) {
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO : MESSAGE_TYPE_SENT_VIDEO;
        }
        if (message.getType() == EMMessage.Type.FILE) {
            return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_FILE : MESSAGE_TYPE_SENT_FILE;
        }

        return -1;// invalid
    }

    protected EaseChatRow createChatRow(Context context, EMMessage message, int position) {
        EaseChatRow chatRow = null;
        if (customRowProvider != null && customRowProvider.getCustomChatRow(message, position, this) != null) {
            return customRowProvider.getCustomChatRow(message, position, this);
        }
        message.ext().put(EaseConstant.EXTRA_IS_TRUENAME, isTrueName);
        switch (message.getType()) {
            case TXT:
                if (message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                    chatRow = new EaseChatRowBigExpression(context, message, position, this);
                } else {

                    try {
                        if (TextUtils.isEmpty(message.getStringAttribute(EaseConstant.EXTRA_GROUP_CARD))) {
                            chatRow = new EaseChatRowText(context, message, position, this);
                        }else {
                            chatRow = new GroupCardChatRow(context, message, position, this);
                        }
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        chatRow = new EaseChatRowText(context, message, position, this);
                    }
                }
                break;
            case LOCATION:
                chatRow = new EaseChatRowLocation(context, message, position, this);
                break;
            case FILE:
                chatRow = new EaseChatRowFile(context, message, position, this);
                break;
            case IMAGE:
                chatRow = new EaseChatRowImage(context, message, position, this);
                break;
            case VOICE:
                chatRow = new EaseChatRowVoice(context, message, position, this);
                break;
            case VIDEO:
                chatRow = new EaseChatRowVideo(context, message, position, this);
                break;
            default:
                break;
        }

        return chatRow;
    }


    @SuppressLint("NewApi")
    public View getView(final int position, View convertView, ViewGroup parent) {
        EMMessage message = getItem(position);
        if (convertView == null) {
            convertView = createChatRow(context, message, position);
        }

        //refresh ui with messages
        ((EaseChatRow) convertView).setUpView(message, position, itemClickListener, isTrueName, isBidTureName, type);

        return convertView;
    }


    public String getToChatUsername() {
        return toChatUsername;
    }


    public void setShowUserNick(boolean showUserNick) {
        this.showUserNick = showUserNick;
    }


    public void setShowAvatar(boolean showAvatar) {
        this.showAvatar = showAvatar;
    }


    public void setMyBubbleBg(Drawable myBubbleBg) {
        this.myBubbleBg = myBubbleBg;
    }


    public void setOtherBuddleBg(Drawable otherBuddleBg) {
        this.otherBuddleBg = otherBuddleBg;
    }


    public void setItemClickListener(MessageListItemClickListener listener) {
        itemClickListener = listener;
    }

    public void setCustomChatRowProvider(EaseCustomChatRowProvider rowProvider) {
        customRowProvider = rowProvider;
    }


    public boolean isShowUserNick() {
        return showUserNick;
    }


    public boolean isShowAvatar() {
        return showAvatar;
    }


    public Drawable getMyBubbleBg() {
        return myBubbleBg;
    }


    public Drawable getOtherBuddleBg() {
        return otherBuddleBg;
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 207,113评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,644评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,340评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,449评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,445评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,166评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,442评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,105评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,601评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,066评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,161评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,792评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,351评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,352评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,584评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,618评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,916评论 2 344

推荐阅读更多精彩内容