@Override public void onResume() { super.onResume(); if (!hidden) { refresh(); if (adapter != null) { conversationList.clear(); conversationList.addAll(loadConversationsWithRecentChat()); if (conversationList.size() == 0) { return; } if (data == null || data.getSaledetail() == null) { return; } for (int i = 0; i < conversationList.size(); i++) { EMConversation emcon = conversationList.get(i); if (TextUtils.equals(emcon.getUserName(), data.getSaledetail().getS_imid())) { if (headView != null) { listView.removeHeaderView(headView); listView.setAdapter(adapter); } } } } } }
/** * 获取所有会话 * * @return */ private List<EMConversation> loadConversationsWithRecentChat() { // 获取所有会话,包括陌生人 Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations(); // 过滤掉messages size为0的conversation /** * 如果在排序过程中有新消息收到,lastMsgTime会发生变化 影响排序过程,Collection.sort会产生异常 保证Conversation在Sort过程中最后一条消息的时间不变 * 避免并发问题 */ List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>(); synchronized (conversations) { for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0) { // if(conversation.getType() != EMConversationType.ChatRoom){ sortList.add( new Pair<Long, EMConversation>( conversation.getLastMessage().getMsgTime(), conversation)); // } } } } try { sortConversationByLastChatTime(sortList); } catch (Exception e) { e.printStackTrace(); } List<EMConversation> list = new ArrayList<EMConversation>(); for (Pair<Long, EMConversation> sortItem : sortList) { list.add(sortItem.second); } return list; }
private void refreshLike(String like) { if (like != null) { try { JSONObject jsonObject = new JSONObject(like); String state = jsonObject.getString(JsonString.Return.STATE); if (state.equals("20002")) { // 对方已经Like过我 ToastUtil.prompt(this, "双方相互Like,你们已经是好友了"); Intent intent = new Intent(IntentString.Receiver.NEW_FRIEND); sendBroadcast(intent); EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT); TextMessageBody txtBody = new TextMessageBody("我们已经是好友了,可以开始聊天了"); message.addBody(txtBody); message.setReceipt(person.getId()); EMConversation conversation = EMChatManager.getInstance().getConversation(person.getId()); conversation.addMessage(message); finish(); } else if (state.equals("10004")) { ToastUtil.longPrompt(this, "检测到您的头像不是真人头像,Like操作无效"); } else { ToastUtil.prompt(this, "Like操作失败!"); } } catch (JSONException e) { e.printStackTrace(); } } else { ToastUtil.noNet(this); } }
@Override public boolean onContextItemSelected(MenuItem item) { boolean handled = false; boolean deleteMessage = false; if (item.getItemId() == R.id.delete_message) { deleteMessage = true; handled = true; } else if (item.getItemId() == R.id.delete_conversation) { deleteMessage = false; handled = true; } EMConversation tobeDeleteCons = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position); // 删除此会话 EMChatManager.getInstance() .deleteConversation(tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage); InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity()); inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName()); adapter.remove(tobeDeleteCons); adapter.notifyDataSetChanged(); // 更新消息未读数 ((MainActivity) getActivity()).updateUnreadLabel(); return handled ? true : super.onContextItemSelected(item); }
@Override public void onClick(DialogInterface dialog, int which) { EMConversation conversation = conversationList.get(deleteID); EMChatManager.getInstance().deleteConversation(conversation.getUserName()); // Utils.showLongToast((Activity) context, "删除成功"); conversationList.remove(deleteID); notifyDataSetChanged(); Tipdialog.dismiss(); }
/** * 获取未读消息数 * * @return */ public int getUnreadMsgCountTotal() { int unreadMsgCountTotal = 0; int chatroomUnreadMsgCount = 0; unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount(); for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) { if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount(); } return unreadMsgCountTotal - chatroomUnreadMsgCount; }
private void initChatView() { // TODO Auto-generated method stub EMConversation conversation = EMChatManager.getInstance().getConversation(hxusernameString); Log.d("test1", "对话初始化成功"); username.setText(nicknamrString); // 修改聊天对象名字 messages = conversation.getAllMessages(); // 向环信拉取聊天记录,进行初始化 conversation.resetUnreadMsgCount(); mAdapter = new ChatAdapter(ChatActivity.this, messages, myPictureString, friendPictureString); lv.setAdapter(mAdapter); lv.setSelection(lv.getCount() - 1); }
public void onReceive(Context context, Intent intent) { String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { EMMessage msg = conversation.getMessage(msgid); if (msg != null) { msg.isAcked = true; } } abortBroadcast(); }
/** * 获取所有会话 * * @param context * @return + */ private List<EMConversation> loadConversationsWithRecentChat() { // 获取所有会话,包括陌生人 Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations(); List<EMConversation> list = new ArrayList<EMConversation>(); // 过滤掉messages seize为0的conversation for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0) list.add(conversation); } // 排序 sortConversationByLastChatTime(list); return list; }
@Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mOriginalValues == null) { mOriginalValues = new ArrayList<EMConversation>(); } if (prefix == null || prefix.length() == 0) { results.values = copyConversationList; results.count = copyConversationList.size(); } else { String prefixString = prefix.toString(); final int count = mOriginalValues.size(); final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>(); for (int i = 0; i < count; i++) { final EMConversation value = mOriginalValues.get(i); String username = value.getUserName(); EMGroup group = EMGroupManager.getInstance().getGroup(username); if (group != null) { username = group.getGroupName(); } // First match against the whole ,non-splitted value if (username.startsWith(prefixString)) { newValues.add(value); } else { final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; }
/** * 获取所有会话 * * @param context * @return + */ private List<EMConversation> loadConversationsWithRecentChat() { // 获取所有会话,包括陌生人 Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations(); List<EMConversation> list = new ArrayList<EMConversation>(); List<EMConversation> topList1 = new ArrayList<EMConversation>(); // 置顶列表再刷新一次 // 过滤掉messages seize为0的conversation for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0) { // 不在置顶列表里面 if (!topMap.containsKey(conversation.getUserName())) { list.add(conversation); } else { // 在置顶列表里面 topList1.add(conversation); } // // for(EMMessage msg:conversation.getAllMessages()){ // if(msg.getFrom().equals("admin")){ // try { // Log.e("type--->>",msg.getStringAttribute("type")); // Log.e("groupid--->>",msg.getStringAttribute("groupid")); // } catch (EaseMobException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // } } } top_list.clear(); top_list.addAll(topList1); // 排序 sortConversationByLastChatTime(list); sortConversationByLastChatTime(top_list); return list; }
@Override protected synchronized FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mList == null) { mList = new ArrayList<User>(); } if (prefix == null || prefix.length() == 0) { results.values = copyUserList; results.count = copyUserList.size(); } else { String prefixString = prefix.toString(); final int count = mList.size(); final ArrayList<User> newValues = new ArrayList<User>(); for (int i = 0; i < count; i++) { final User user = mList.get(i); String username = user.getUsername(); EMConversation conversation = EMChatManager.getInstance().getConversation(username); if (conversation != null) { username = conversation.getUserName(); } if (username.startsWith(prefixString)) { newValues.add(user); } else { final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(user); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; }
@Override public void onReceive(Context context, Intent intent) { abortBroadcast(); String msgid = intent.getStringExtra("msgid"); String from = intent.getStringExtra("from"); EMConversation conversation = EMChatManager.getInstance().getConversation(from); if (conversation != null) { // 把message设为已读 EMMessage msg = conversation.getMessage(msgid); if (msg != null) { // 2014-11-5 修复在某些机器上,在聊天页面对方发送已读回执时不立即显示已读的bug if (ChatActivity.activityInstance != null) { if (msg.getChatType() == ChatType.Chat) { if (from.equals(ChatActivity.activityInstance.getToChatUsername())) return; } } msg.isAcked = true; } } }
/** * 获取有聊天记录的users和groups * * @param context * @return */ private List<EMContact> loadUsersWithRecentChat() { List<EMContact> resultList = new ArrayList<EMContact>(); // 获取有聊天记录的users,不包括陌生人 for (User user : contactList.values()) { EMConversation conversation = EMChatManager.getInstance().getConversation(user.getUsername()); if (conversation.getMsgCount() > 0) { resultList.add(user); } } for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) { EMConversation conversation = EMChatManager.getInstance().getConversation(group.getGroupId()); if (conversation.getMsgCount() > 0) { resultList.add(group); } } // 排序 sortUserByLastChatTime(resultList); return resultList; }
@Override public void handleMsg(Message msg) { String json = msg.getData().getString(Constant.JSON_DATA); if (TextUtils.equals(json, getString(R.string.try_agin))) { setRefreFalse(); return; } switch (msg.what) { case TAG_SALE_BUSSINESS_LIST: data = JosnUtil.gson.fromJson(json, new TypeToken<KeFuData>() {}.getType()); if (TextUtils.equals("0", data.getResult())) { break; } if (listView.getHeaderViewsCount() < 1) { break; } ((TextView) headView.findViewById(R.id.name)).setText(data.getSaledetail().getS_showname()); ((TextView) headView.findViewById(R.id.time)) .setText(MethodUtils.returnTime(data.getSaledetail().getS_lastim())); if (TextUtils.equals("0", data.getSaledetail().getS_sex())) { ((ImageView) headView.findViewById(R.id.avatar)).setImageResource(R.mipmap.male_yewu); } else { ((ImageView) headView.findViewById(R.id.avatar)).setImageResource(R.mipmap.meal_yewu); } if (adapter != null) { conversationList.clear(); conversationList.addAll(loadConversationsWithRecentChat()); for (int i = 0; i < conversationList.size(); i++) { EMConversation emcon = conversationList.get(i); if (TextUtils.equals(emcon.getUserName(), data.getSaledetail().getS_imid())) { if (headView != null) { listView.removeHeaderView(headView); listView.setAdapter(adapter); } } } } break; } }
@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub LogUtil.d("聊天界面收到消息", "消息"); int length = mAdapter.getCount(); String msgid = intent.getStringExtra("msgid"); String username = intent.getStringExtra("from"); EMMessage message = EMChatManager.getInstance().getMessage(msgid); JSONObject jsonObject; // try { // if(propellingMessageTurnTo.isAdv(message)){ // propellingMessageTurnTo.turnToActivity(message); // } // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if (message.getChatType() != ChatType.GroupChat && username.equals(hxusernameString)) { abortBroadcast(); Message message2 = new Message(); message2.what = 1; handler.sendMessage(message2); mAdapter.notifyDataSetChanged(); lv.setSelection(lv.getCount() - 1); LogUtil.d("长度", length + "ddd" + mAdapter.getCount()); // 设置消息已读 EMConversation conversation = EMChatManager.getInstance().getConversation(username); conversation.resetUnreadMsgCount(); } else { unRead.setVisibility(View.VISIBLE); unReadCount++; unRead.setText("聊天(" + unReadCount + ")"); return; } }
@Override public View getView(int position, View convertView, ViewGroup parent) { EMMessage message = conversation.getAllMessages().get(position); TextMessageBody body = (TextMessageBody) message.getBody(); if (message.direct == EMMessage.Direct.RECEIVE) { // 接收方 if (message.getType() == EMMessage.Type.TXT) { convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatmsg, null); username = (TextView) convertView.findViewById(R.id.tv_chatusername); username.setText(message.getFrom()); } } else { if (message.getType() == EMMessage.Type.TXT) { convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatmsg2, null); username = (TextView) convertView.findViewById(R.id.tv_chatusername); // username.setText(message.getFrom()); } } msg = (TextView) convertView.findViewById(R.id.tv_chatmsg); msg.setText(body.getMessage()); return convertView; }
@Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if (adpter.PublicMsg != null && position == 0) { // 打开订阅号列表页面 Utils.start_Activity(getActivity(), PublishMsgListActivity.class); } else { parentActivity.updateUnreadLabel(); EMConversation conversation = conversationList.get(position); Intent intent = new Intent(getActivity(), ChatActivity.class); Hashtable<String, String> ChatRecord = adpter.getChatRecord(); if (ChatRecord != null) { if (conversation.isGroup()) { GroupInfo info = GloableParams.GroupInfos.get(conversation.getUserName()); if (info != null) { intent.putExtra(Constants.TYPE, ChatActivity.CHATTYPE_GROUP); intent.putExtra(Constants.GROUP_ID, info.getGroup_id()); intent.putExtra(Constants.NAME, info.getGroup_name()); // 设置标题 getActivity().startActivity(intent); } else { intent.putExtra(Constants.TYPE, ChatActivity.CHATTYPE_GROUP); intent.putExtra(Constants.GROUP_ID, info.getGroup_id()); intent.putExtra(Constants.NAME, "群聊"); // 设置标题 getActivity().startActivity(intent); } } else { User user = GloableParams.Users.get(conversation.getUserName()); if (user != null) { intent.putExtra(Constants.NAME, user.getUserName()); // 设置昵称 intent.putExtra(Constants.TYPE, ChatActivity.CHATTYPE_SINGLE); intent.putExtra(Constants.User_ID, conversation.getUserName()); getActivity().startActivity(intent); } else { intent.putExtra(Constants.NAME, "好友"); intent.putExtra(Constants.TYPE, ChatActivity.CHATTYPE_SINGLE); intent.putExtra(Constants.User_ID, conversation.getUserName()); getActivity().startActivity(intent); } } } } }
@Override public Object getItem(int position) { return conversation.getAllMessages().get(position); }
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.row_chat_history, parent, false); } ViewHolder holder = (ViewHolder) convertView.getTag(); if (holder == null) { holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number); holder.message = (TextView) convertView.findViewById(R.id.message); holder.time = (TextView) convertView.findViewById(R.id.time); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); holder.msgState = convertView.findViewById(R.id.msg_state); holder.list_item_layout = (RelativeLayout) convertView.findViewById(R.id.list_item_layout); convertView.setTag(holder); } if (position % 2 == 0) { holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem); } else { holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem_grey); } // 获取与此用户/群组的会话 EMConversation conversation = getItem(position); // 获取用户username或者群组groupid String username = conversation.getUserName(); if (conversation.getType() == EMConversationType.GroupChat) { // 群聊消息,显示群聊头像 holder.avatar.setImageResource(R.drawable.group_icon); EMGroup group = EMGroupManager.getInstance().getGroup(username); holder.name.setText(group != null ? group.getGroupName() : username); } else if (conversation.getType() == EMConversationType.ChatRoom) { holder.avatar.setImageResource(R.drawable.group_icon); EMChatRoom room = EMChatManager.getInstance().getChatRoom(username); holder.name.setText( room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username); } else { UserUtils.setUserAvatar(getContext(), username, holder.avatar); if (username.equals(Constant.GROUP_USERNAME)) { holder.name.setText("群聊"); } else if (username.equals(Constant.NEW_FRIENDS_USERNAME)) { holder.name.setText("申请与通知"); } Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotList(); if (robotMap != null && robotMap.containsKey(username)) { String nick = robotMap.get(username).getNick(); if (!TextUtils.isEmpty(nick)) { holder.name.setText(nick); } else { holder.name.setText(username); } } else { UserUtils.setUserNick(username, holder.name); } } if (conversation.getUnreadMsgCount() > 0) { // 显示与此用户的消息未读数 holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount())); holder.unreadLabel.setVisibility(View.VISIBLE); } else { holder.unreadLabel.setVisibility(View.INVISIBLE); } if (conversation.getMsgCount() != 0) { // 把最后一条消息的内容作为item的message内容 EMMessage lastMessage = conversation.getLastMessage(); holder.message.setText( SmileUtils.getSmiledText( getContext(), getMessageDigest(lastMessage, (this.getContext()))), BufferType.SPANNABLE); holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime()))); if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) { holder.msgState.setVisibility(View.VISIBLE); } else { holder.msgState.setVisibility(View.GONE); } } return convertView; }
@Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.layout_item_msg, parent, false); } ImageView img_avar = ViewHolder.get(convertView, R.id.contactitem_avatar_iv); TextView txt_name = ViewHolder.get(convertView, R.id.txt_name); TextView txt_state = ViewHolder.get(convertView, R.id.txt_state); TextView txt_del = ViewHolder.get(convertView, R.id.txt_del); TextView txt_content = ViewHolder.get(convertView, R.id.txt_content); TextView txt_time = ViewHolder.get(convertView, R.id.txt_time); TextView unreadLabel = ViewHolder.get(convertView, R.id.unread_msg_number); SwipeLayout swipe = ViewHolder.get(convertView, R.id.swipe); if (PublicMsg != null && position == 0) { txt_name.setText("订阅号"); img_avar.setImageResource(R.drawable.icon_public); txt_time.setText(PublicMsg.getTime()); txt_content.setText(PublicMsg.getContent()); unreadLabel.setText("3"); unreadLabel.setVisibility(View.VISIBLE); swipe.setSwipeEnabled(false); } else { swipe.setSwipeEnabled(true); // 获取与此用户/群组的会话 final EMConversation conversation = conversationList.get(position); // 获取用户username或者群组groupid ChatID = conversation.getUserName(); txt_del.setTag(ChatID); if (conversation.isGroup()) { GroupInfo info = GloableParams.GroupInfos.get(ChatID); if (info != null) { txt_name.setText(info.getGroup_name()); img_avar.setImageResource(R.drawable.defult_group); // initGroupInfo(img_avar, txt_name);// 获取群组信息 } } else { User user = GloableParams.Users.get(ChatID); if (user != null) { txt_name.setText(user.getUserName()); // initUserInfo(img_avar, txt_name);// 获取用户信息 } } if (conversation.getUnreadMsgCount() > 0) { // 显示与此用户的消息未读数 unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount())); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.INVISIBLE); } if (conversation.getMsgCount() != 0) { // 把最后一条消息的内容作为item的message内容 EMMessage lastMessage = conversation.getLastMessage(); txt_content.setText( SmileUtils.getSmiledText(context, getMessageDigest(lastMessage, context)), BufferType.SPANNABLE); txt_time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime()))); if (lastMessage.status == EMMessage.Status.SUCCESS) { txt_state.setText("送达"); // txt_state.setBackgroundResource(R.drawable.btn_bg_orgen); } else if (lastMessage.status == EMMessage.Status.FAIL) { txt_state.setText("失败"); // txt_state.setBackgroundResource(R.drawable.btn_bg_red); } else if (lastMessage.direct == EMMessage.Direct.RECEIVE) { txt_state.setText("已读"); txt_state.setBackgroundResource(R.drawable.btn_bg_blue); } } txt_del.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { deleteID = position; Tipdialog = new WarnTipDialog((Activity) context, "您确定要删除该聊天吗?"); Tipdialog.setBtnOkLinstener(onclick); Tipdialog.show(); } }); } return convertView; }
@Override public int getCount() { return conversation.getAllMsgCount(); }