1. 程式人生 > >android如何整合環信的聊天介面和訊息列表

android如何整合環信的聊天介面和訊息列表

使用拓展訊息實現聊天介面和訊息列表的頭像和暱稱的展示

上篇文章只是簡單的介紹怎麼整合環信,但是在自己的專案中涉及到聊天這一塊。在做android開發的時候,往往要考慮到怎麼展示使用者暱稱和頭像的問題。說明一點:我們這個專案的使用者頭像和暱稱是我們後臺返回給我們的。我們只需要給使用者設定拓展屬性。

一、首先整合環信:

app如何引入一個module作為依賴:

  1. 在自己的該app工作空間下,匯入easeui這個module

  2. 在專案選單的project structure中,app---dependencies--新增module依賴。

  3. clean工程—rebuild工程。

首先要解決架包衝突問題。(

v7衝突。)

解決方案:1.app下的架包放到easeUIgradle中。

2.實在不行,就檢視所有gradle下面時候有重複的架包及依賴。

二、整合環信的聊天介面:

由於要使用到拓展訊息,所以我們首先在工具類中定義一下我們自己和好友的屬性。from表示我,to表示好友。

        public static final String FROM_AVATER="from_avater";
	public static final String FROM_NICHENG="from_nicheng";
	public static final String TO_AVATER="to_avater";
	public static final String TO_NICHENG="to_nicheng";

在easeui的widget包下的chatrow包的EaseChatRow這個類中,在訊息的傳送和接收處將其更改為拓展屬性:

/**
 * 聊天介面
 * 聊天介面需要獲取使用者的頭像和暱稱
 * 方法:採用擴充套件屬性的方法。
 * 定義 自己和他人的屬性:from_avater from_nicheng自己的頭像和暱稱   
 * to_avater  to_nicheng 對方的頭像和暱稱
 * 自身頭像暱稱在進入應用的時候存到檔案中,待聊天介面直接從檔案中取出來。
 * 對方頭像從訊息列表中獲取
 */
//環信中的聊天頁面
//set nickname and avatar
        /**
         * 聊天頁面
         */
        if (message.direct() == Direct.SEND) {
            //  EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
            try {
                Glide.with(getContext()).load(message.getStringAttribute("from_avater")).into(userAvatarView);
             //   usernickView.setText(message.getStringAttribute("from_nicheng"));
                EaseUserUtils.setUserNick(message.getStringAttribute("from_nicheng"), usernickView);
                
            } catch (HyphenateException e) {

            }
        }
        //   
        else {
            //  EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
            //  EaseUserUtils.setUserNick(message.getFrom(), usernickView);
            try {
              //  usernickView.setText(message.getStringAttribute("from_nicheng"));
               EaseUserUtils.setUserNick(message.getStringAttribute("from_nicheng"), usernickView);
                Glide.with(getContext()).load(message.getStringAttribute("from_avater")).into(userAvatarView);
            } catch (HyphenateException e) {

            }
        }

在自己的app下定義聊天介面ChatActivity如下:

public class ChatActivity extends BaseActivity {
    private String logo;
    private static String name;
    private String logoPath;
    private String tradeName;
    public static ChatActivity activityInstance;
    private Bundle extras;

    //給擴充套件屬性設定頭像和暱稱。
    EaseChatFragment.EaseChatFragmentHelper helper = new EaseChatFragment.EaseChatFragmentHelper() {
        @Override
        public void onSetMessageAttributes(EMMessage message) {
            // 附帶擴充套件屬性,頭像和暱稱他人的
            message.setAttribute(Utils.TO_AVATER, logo);
            message.setAttribute(Utils.TO_NICHENG, name);
          
            //我的頭像  存到自己的檔案中
            message.setAttribute(Utils.FROM_AVATER, logoPath);
            message.setAttribute(Utils.FROM_NICHENG, tradeName);
        }
        @Override
        public void onEnterToChatDetails() {
        }
        @Override
        public void onAvatarClick(String username) {
        }
        @Override
        public void onAvatarLongClick(String username) {
        }
        @Override
        public boolean onMessageBubbleClick(EMMessage message) {
            return false;
        }
        @Override
        public void onMessageBubbleLongClick(EMMessage message) {
        }
        @Override
        public boolean onExtendMenuItemClick(int itemId, View view) {
            return false;
        }
        @Override
        public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
            return null;
        }
    };
    
    @Override
    protected void init() {
        super.init();
        //在佈局中設定一個容器。整合環信的聊天介面新增進去
        setContentView(R.layout.activity_chat);
        initView();
    }
    private void initView() {
        //從訊息列表獲取頭像和暱稱
        logo = getIntent().getStringExtra(Utils.FROM_AVATER);
        name = getIntent().getStringExtra(Utils.FROM_NICHENG);
        //並從本地取出我的頭像
        logoPath = SpUtils.getLogoPath(this);
        tradeName = SpUtils.getTradeName(this);
        //將環信的聊天介面chatFragment整合進來
        initHx();
    }
    public void initHx() {
        activityInstance = this;
        ChatFragment chatf = new ChatFragment();
        //獲取從上個介面獲取的引數,傳給聊天介面。
        extras = getIntent().getExtras();
        chatf.setArguments(extras);
        //這個監聽是接收到訊息就給訊息設定拓展屬性。
        chatf.setChatFragmentListener(helper);
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatf).commit();

    }

    /**
     * 繼承環信的聊天頁面  
     * 實現訊息監聽和聊天頁面的標題上顯示的對方暱稱
     * 
     *
     */
    public static class ChatFragment extends EaseChatFragment implements EMMessageListener {
        /**
         * 設定聊天頁面的title上面的暱稱
         */
        @Override
        protected void setUpView() {
            super.setUpView();
            titleBar.setTitle(name);
            
        }

    }

}

當我們點選好友列表時(我的好友列表的資料是從伺服器獲取的。能夠獲取到好友的頭像和暱稱。自己的頭像和暱稱已進入自己的應用就儲存到自己的檔案中):

//則點選進入聊天介面,和環信id

//從伺服器獲取到暱稱頭像
                    String chatId = data.getChatId();
                    String name = data.getName();
                    String headerURL = data.getHeaderURL();


                    Log.i("shi",chatId+"#"+name+"#"+headerURL);
                    Intent intent = new Intent(this, ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(EaseConstant.EXTRA_USER_ID, chatId);  //傳遞使用者id
                    bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE); //傳遞是群聊還是單聊
                    intent.putExtras(bundle);
                    intent.putExtra(Utils.FROM_NICHENG, name);
                    intent.putExtra(Utils.FROM_AVATER, headerURL);
                    startActivity(intent);

三、整合環信的訊息列表:

在easeui中找到EaseConversationAdapter這個類。當接收到最後一條訊息的時候將其設定為對應的拓展屬性。(這樣在展示訊息列表時會展示好友的頭像暱稱)

 else if(conversation.getType() == EMConversationType.ChatRoom){
            holder.avatar.setImageResource(R.drawable.ease_group_icon);
            EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(username);
            holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
            holder.motioned.setVisibility(View.GONE);
        }else {/**
         * 獲取列表最後一條訊息是接收還是傳送
         * 然後設定暱稱和頭像
         */
            EMMessage lastMessage = conversation.getLastMessage();
            if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                try {
                    Glide.with(getContext()).load(lastMessage.getStringAttribute("from_avater")).into(holder.avatar);
                    EaseUserUtils.setUserNick(lastMessage.getStringAttribute("from_nicheng"), holder.name);
                } catch (HyphenateException e) {
                }
            } else {
                try {
                    EaseUserUtils.setUserNick(lastMessage.getStringAttribute("to_nicheng"), holder.name);
                    Glide.with(getContext()).load(lastMessage.getStringAttribute("to_avater")).into(holder.avatar);
                } catch (HyphenateException e) {
                }
            }
        }
        {
            // EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
            // EaseUserUtils.setUserNick(username, holder.name);
            holder.motioned.setVisibility(View.GONE);
        }

在app專案中整合環信的訊息列表:

1.	寫一個佈局檔案,佈局檔案中設定一個容器,用來接收 環信的訊息列表。
EaseConversationListFragment  cf = new EaseConversationListFragment();
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fl_contains,cf).commit();
2.	給訊息列表設定一個訊息到來的監聽。
MClient.getInstance().chatManager().addMessageListener(emMessageListener);
private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> list) {
            //在環信包下的訊息列表中對訊息物件進行了篩選。將第0個訊息存為32個8賬號的訊息,
            // 從訊息列表中取出第0個訊息物件。(第0個訊息就是存有32個8該賬號的訊息物件)
            EMMessage emMessage = list.get(0);
            String s = emMessage.getBody().toString();
            try {
                //這裡是訂單訊息
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation("88888888888888888888888888888888");
                //未讀的訊息數量普通訊息
                unreadMsgCount = conversation.getUnreadMsgCount();
                Log.i("123---", s + "---from:" + emMessage.getFrom() + "---to:" + emMessage.getTo() + "---nicheng:" + emMessage.getStringAttribute("from_nicheng"));
            } catch (Exception e) {
                cf.refresh();
                Log.i("123---", s + "---from:" + emMessage.getFrom() + "---to:" + emMessage.getTo());
            }
                cf.refresh();
        }
        //透傳訊息的
        @Override
        public void onCmdMessageReceived(List<EMMessage> list) {
            EMMessage emMessage = list.get(0);
            try{
                EMCmdMessageBody body = (EMCmdMessageBody) emMessage.getBody();
                String action = body.action();
                if (action.equals("isDisable")){//啟用和禁止 退出
                   //直接退出app和環信。
                    exitLogin();
                }else if (action.equals("changePassword")){//修改密碼  退出
                    exitLogin();
                }else if (action.equals("setRights")){//許可權   
                    EventBus.getDefault().post("修改許可權");
                    //接收到修改許可權的訊息。立馬去重新獲取許可權資訊
                    reGetRight();
                }else if (action.equals("reloadNickname")){//修改使用者資料  重新整理個人中心和首頁
                    EventBus.getDefault().post("修改資料");
                    //重新整理本頁面
                    requestInfo();
                }
               
            }catch (Exception e){
                
            }
            
        }

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

        }

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

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }
    };

給訊息列表新增點選監聽:

3.給訊息列表設定點選事件,點選跳到聊天介面。(先從好友列表聊天才會產生訊息列表)
cf.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation) {
                // 聊天需要的bundle物件
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(EaseConstant.EXTRA_USER_ID, conversation.getLastMessage().getUserName());
                bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                intent.putExtras(bundle);
                /**
                 * 從會話列表跳轉到聊天頁面
                 * 首先要判斷最後一條資訊是接收還是傳送訊息
                 * 然後分情況傳遞頭像和暱稱
                 *
                 */
                EMMessage lastMessage = conversation.getLastMessage();
                if (lastMessage.direct() == EMMessage.Direct.RECEIVE) {
                    try {
                        intent.putExtra(Utils.FROM_AVATER, lastMessage.getStringAttribute(Utils.FROM_AVATER));
                        intent.putExtra(Utils.FROM_NICHENG, lastMessage.getStringAttribute(Utils.FROM_NICHENG));
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        intent.putExtra(Utils.FROM_AVATER, lastMessage.getStringAttribute(Utils.TO_AVATER));
                        intent.putExtra(Utils.FROM_NICHENG, lastMessage.getStringAttribute(Utils.TO_NICHENG));
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
                startActivity(intent);
            }
        });

activity銷燬的時候記得移除訊息的監聽:

EMClient.getInstance().chatManager().removeMessageListener(emMessageListener);

四、結束語

大致整合步驟就是這樣的,整合環信之前如果對環信一點都不瞭解建議先去環信上看一下文件。文章純屬按照自己的專案開發需求寫的。大家可做參考。