com.easemob.chat.EMGroupManager Java Examples

The following examples show how to use com.easemob.chat.EMGroupManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EaseChatFragment.java    From monolog-android with MIT License 5 votes vote down vote up
@Override
public void onDestroy() {
    super.onDestroy();
    if (groupListener != null) {
        EMGroupManager.getInstance().removeGroupChangeListener(groupListener);
    }
    if(chatType == EaseConstant.CHATTYPE_CHATROOM){
        EMChatManager.getInstance().leaveChatRoom(toChatUsername);
    }
}
 
Example #2
Source File: EaseChatFragment.java    From monolog-android with MIT License 5 votes vote down vote up
/**
 * 点击进入群组详情
 * 
 */
protected void toGroupDetails() {
    if (chatType == EaseConstant.CHATTYPE_GROUP) {
        EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
        if (group == null) {
            Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
            return;
        }
        if(chatFragmentListener != null){
            chatFragmentListener.onEnterToChatDetails();
        }
    }
}
 
Example #3
Source File: EaseConversationAdapater.java    From monolog-android with MIT License 4 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.ease_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_itease_layout = (RelativeLayout) convertView.findViewById(R.id.list_itease_layout);
        convertView.setTag(holder);
    }
    holder.list_itease_layout.setBackgroundResource(R.drawable.ease_mm_listitem);

    // 获取与此用户/群组的会话
    EMConversation conversation = getItem(position);
    // 获取用户username或者群组groupid
    String username = conversation.getUserName();

    if (conversation.getType() == EMConversationType.GroupChat) {
        // 群聊消息,显示群聊头像
        holder.avatar.setImageResource(R.drawable.ease_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.ease_group_icon);
        EMChatRoom room = EMChatManager.getInstance().getChatRoom(username);
        holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username);
    }else {
        EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
        EaseUserUtils.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(EaseSmileUtils.getSmiledText(getContext(), EaseCommonUtils.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);
        }
    }
    
    //设置自定义属性
    holder.name.setTextColor(primaryColor);
    holder.message.setTextColor(secondaryColor);
    holder.time.setTextColor(timeColor);
    if(primarySize != 0)
        holder.name.setTextSize(TypedValue.COMPLEX_UNIT_PX, primarySize);
    if(secondarySize != 0)
        holder.message.setTextSize(TypedValue.COMPLEX_UNIT_PX, secondarySize);
    if(timeSize != 0)
        holder.time.setTextSize(TypedValue.COMPLEX_UNIT_PX, timeSize);

    return convertView;
}
 
Example #4
Source File: ChatRoomSettingActivity.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
private void initData() {

        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        // 获取本地该群数据
        group = EMGroupManager.getInstance().getGroup(groupId);
        if (group == null) {
            try {
                // 去网络中查找该群
                group = EMGroupManager.getInstance()
                        .getGroupFromServer(groupId);
                if (group == null) {
                    Toast.makeText(ChatRoomSettingActivity.this, "该群已经被解散...",
                            Toast.LENGTH_SHORT).show();
                    setResult(100);
                    finish();
                    return;

                }
            } catch (EaseMobException e) {

                e.printStackTrace();
                return;
            }

        }

        // 获取封装的群名(里面封装了显示的群名和群组成员的信息)
        String group_name_temp = group.getGroupName();
        // 转化成json,然后解析
        jsonObject = JSONObject.parseObject(group_name_temp);
        // 获取显示的群名
        group_name = jsonObject.getString("groupname");
        // 获取群成员信息
        jsonarray = jsonObject.getJSONArray("jsonArray");

        tv_groupname.setText(group_name);
        m_total = jsonarray.size();
        tv_m_total.setText("(" + String.valueOf(m_total) + ")");
        // 解析群组成员信息
        for (int i = 0; i < m_total; i++) {
            JSONObject json = jsonarray.getJSONObject(i);
            User user = new User();
            user.setUsername(json.getString("hxid"));
            user.setAvatar(json.getString("avatar"));
            user.setNick(json.getString("nick"));
            members.add(user);
        }
        // 显示群组成员头像和昵称
        showMembers(members);
        // 判断是否是群主,是群主有删成员的权限,并显示减号按钮
        if (hxid.equals(group.getOwner())) {
            is_admin = true;
        }

        re_change_groupname.setOnClickListener(this);
        rl_switch_chattotop.setOnClickListener(this);
        rl_switch_block_groupmsg.setOnClickListener(this);

        re_clear.setOnClickListener(this);

        exitBtn.setOnClickListener(this);

    }
 
Example #5
Source File: ChatRoomSettingActivity.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
protected void updateGroup() {
    new Thread(new Runnable() {
        public void run() {
            try {
                EMGroup returnGroup = EMGroupManager.getInstance()
                        .getGroupFromServer(groupId);
                // 更新本地数据
                EMGroupManager.getInstance().createOrUpdateLocalGroup(
                        returnGroup);

                runOnUiThread(new Runnable() {
                    public void run() {

                        if (group != null) {
                            System.out.println("group msg is blocked:"
                                    + group.getMsgBlocked());
                            // 设置初始屏蔽初始状态
                            if (group.getMsgBlocked()) {
                                iv_switch_block_groupmsg
                                        .setVisibility(View.VISIBLE);
                                iv_switch_unblock_groupmsg
                                        .setVisibility(View.INVISIBLE);
                            } else {
                                iv_switch_block_groupmsg
                                        .setVisibility(View.INVISIBLE);
                                iv_switch_unblock_groupmsg
                                        .setVisibility(View.VISIBLE);
                            }
                            // 设置置顶的初始状态

                            if (topMap.containsKey(group.getGroupId())) {

                                // 当前状态是已经置顶

                                iv_switch_chattotop
                                        .setVisibility(View.VISIBLE);
                                iv_switch_unchattotop
                                        .setVisibility(View.INVISIBLE);

                            } else {
                                // 当前状态是未置顶
                                iv_switch_chattotop
                                        .setVisibility(View.INVISIBLE);
                                iv_switch_unchattotop
                                        .setVisibility(View.VISIBLE);

                            }
                        }

                    }
                });

            } catch (Exception e) {
                runOnUiThread(new Runnable() {
                    public void run() {

                    }
                });
            }
        }
    }).start();
}
 
Example #6
Source File: MainActivity.java    From FanXin-based-HuanXin with GNU General Public License v2.0 4 votes vote down vote up
private void initView() {
    unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
    unreadAddressLable = (TextView) findViewById(R.id.unread_address_number);

    homefragment = new FragmentCoversation();
    contactlistfragment = new FragmentFriends();
    findfragment = new FragmentFind();
    profilefragment = new FragmentProfile();
    fragments = new Fragment[] { homefragment, contactlistfragment,
            findfragment, profilefragment };
    imagebuttons = new ImageView[4];
    imagebuttons[0] = (ImageView) findViewById(R.id.ib_weixin);
    imagebuttons[1] = (ImageView) findViewById(R.id.ib_contact_list);
    imagebuttons[2] = (ImageView) findViewById(R.id.ib_find);
    imagebuttons[3] = (ImageView) findViewById(R.id.ib_profile);

    imagebuttons[0].setSelected(true);
    textviews = new TextView[4];
    textviews[0] = (TextView) findViewById(R.id.tv_weixin);
    textviews[1] = (TextView) findViewById(R.id.tv_contact_list);
    textviews[2] = (TextView) findViewById(R.id.tv_find);
    textviews[3] = (TextView) findViewById(R.id.tv_profile);
    textviews[0].setTextColor(0xFF45C01A);
    // 添加显示第一个fragment
    getSupportFragmentManager().beginTransaction()
            .add(R.id.fragment_container, homefragment)
            .add(R.id.fragment_container, contactlistfragment)
            .add(R.id.fragment_container, profilefragment)
            .add(R.id.fragment_container, findfragment)
            .hide(contactlistfragment).hide(profilefragment)
            .hide(findfragment).show(homefragment).commit();
    inviteMessgeDao = new InviteMessgeDao(this);
    userDao = new UserDao(this);

    // 注册一个接收消息的BroadcastReceiver
    msgReceiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager
            .getInstance().getNewMessageBroadcastAction());
    intentFilter.setPriority(3);
    registerReceiver(msgReceiver, intentFilter);

    // 注册一个ack回执消息的BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager
            .getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(3);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // 注册一个透传消息的BroadcastReceiver
    IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager
            .getInstance().getCmdMessageBroadcastAction());
    cmdMessageIntentFilter.setPriority(3);
    registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);
    // 注册一个离线消息的BroadcastReceiver
    // IntentFilter offlineMessageIntentFilter = new
    // IntentFilter(EMChatManager.getInstance()
    // .getOfflineMessageBroadcastAction());
    // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

    // setContactListener监听联系人的变化等
    EMContactManager.getInstance().setContactListener(
            new MyContactListener());
    // 注册一个监听连接状态的listener
    EMChatManager.getInstance().addConnectionListener(
            new MyConnectionListener());
    // 注册群聊相关的listener
    EMGroupManager.getInstance().addGroupChangeListener(
            new MyGroupChangeListener());
    // 通知sdk,UI 已经初始化完毕,注册了相应的receiver和listener, 可以接受broadcast了
    EMChat.getInstance().setAppInited();

}
 
Example #7
Source File: ChatAllHistoryAdapter.java    From school_shop with MIT License 4 votes vote down vote up
@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 = (CircleImageView) 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();
		Log.i("tag", "username=="+username);
		List<EMGroup> groups = EMGroupManager.getInstance().getAllGroups();
		EMContact contact = null;
		boolean isGroup = false;
		for (EMGroup group : groups) {
			if (group.getGroupId().equals(username)) {
				isGroup = true;
				contact = group;
				break;
			}
		}
		if (isGroup) {
			// 群聊消息,显示群聊头像
			holder.avatar.setImageResource(R.drawable.group_icon);
			holder.name.setText(contact.getNick() != null ? contact.getNick() : username);
		} else {
//		    UserUtils.setUserAvatar(getContext(), username, holder.avatar);
//			if (username.equals(Constants.GROUP_USERNAME)) {
//				holder.name.setText("群聊");
//
//			} else if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
//				holder.name.setText("申请与通知");
//			}
//			holder.name.setText(username);
		}

		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;
	}
 
Example #8
Source File: LoginActivity.java    From school_shop with MIT License 4 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
	if (resultCode == RESULT_OK) {
		if (requestCode == REQUEST_CODE_SETNICK) {
			MyApplication.currentUserNick = data.getStringExtra("edittext");

			progressShow = true;
			final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
			pd.setCanceledOnTouchOutside(false);
			pd.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					progressShow = false;
				}
			});
			pd.setMessage(getString(R.string.Is_landing));
			pd.show();

			// 调用sdk登陆方法登陆聊天服务器
			EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {

				@Override
				public void onSuccess() {
					
					if (!progressShow) {
						return;
					}
					// 登陆成功,保存用户名密码
					MyApplication.getInstance().setUserName(currentUsername);
					MyApplication.getInstance().setPassword(currentPassword);
					
					runOnUiThread(new Runnable() {
						public void run() {
							pd.setMessage(getString(R.string.list_is_for));
						}
					});
					try {
						// ** 第一次登录或者之前logout后再登录,加载所有本地群和回话
						// ** manually load all local groups and
						// conversations in case we are auto login
						EMGroupManager.getInstance().loadAllGroups();
						EMChatManager.getInstance().loadAllConversations();
						//处理好友和群组
						processContactsAndGroups();
					} catch (Exception e) {
						e.printStackTrace();
						//取好友或者群聊失败,不让进入主页面
						runOnUiThread(new Runnable() {
                               public void run() {
                                   pd.dismiss();
                                   MyApplication.getInstance().logout(null);
                                   Toast.makeText(getApplicationContext(), R.string.login_failure_failed, 1).show();
                               }
                           });
						return;
					}
					//更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
					boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(MyApplication.currentUserNick.trim());
					if (!updatenick) {
						Log.e("LoginActivity", "update current user nick fail");
					}
					if (!LoginActivity.this.isFinishing())
						pd.dismiss();
					// 进入主页面
					autoLogin = true;
					Intent intent = new Intent(LoginActivity.this, ChatActivity.class);
					intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
					intent.putExtra("userId", "test1");
					startActivity(intent);
					finish();
				}

                  

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

				@Override
				public void onError(final int code, final String message) {
					if (!progressShow) {
						return;
					}
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message, Toast.LENGTH_SHORT).show();
						}
					});
				}
			});

		}
	}
}
 
Example #9
Source File: LoginActivity.java    From school_shop with MIT License 4 votes vote down vote up
private void processContactsAndGroups() throws EaseMobException {
    // demo中简单的处理成每次登陆都去获取好友username,开发者自己根据情况而定
    List<String> usernames = EMContactManager.getInstance().getContactUserNames();
    EMLog.d("roster", "contacts size: " + usernames.size());
    Map<String, User> userlist = new HashMap<String, User>();
    for (String username : usernames) {
        User user = new User();
        user.setUsername(username);
        setUserHearder(username, user);
        userlist.put(username, user);
    }
    // 添加user"申请与通知"
    User newFriends = new User();
    newFriends.setUsername(Constants.NEW_FRIENDS_USERNAME);
    String strChat = getResources().getString(R.string.Application_and_notify);
    newFriends.setNick(strChat);
    
    userlist.put(Constants.NEW_FRIENDS_USERNAME, newFriends);
    // 添加"群聊"
    User groupUser = new User();
    String strGroup = getResources().getString(R.string.group_chat);
    groupUser.setUsername(Constants.GROUP_USERNAME);
    groupUser.setNick(strGroup);
    groupUser.setHeader("");
    userlist.put(Constants.GROUP_USERNAME, groupUser);

    // 存入内存
    MyApplication.getInstance().setContactList(userlist);
    System.out.println("----------------"+userlist.values().toString());
    // 存入db
    UserDao dao = new UserDao(LoginActivity.this);
    List<User> users = new ArrayList<User>(userlist.values());
    dao.saveContactList(users);
    
    //获取黑名单列表
    List<String> blackList = EMContactManager.getInstance().getBlackListUsernamesFromServer();
    //保存黑名单
    EMContactManager.getInstance().saveBlackList(blackList);

    // 获取群聊列表(群聊里只有groupid和groupname等简单信息,不包含members),sdk会把群组存入到内存和db中
    EMGroupManager.getInstance().getGroupsFromServer();
}