以下全是基于单聊的操作
1.每次进入聊天室登录(我是这样操作的,要保证环信是登录状态)
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Constant.userInfo != null) {
friendUserid = bean.getUserid();
SharePrefUtil.saveString(getActivity(), "friendUserNick", bean.getNickname());
SharePrefUtil.saveString(getActivity(), "friendUserImg", getActivity().getResources().getString(R.string.service_host_address)+bean.getImg());
Map<String, EaseUser> contactList =DemoHelper.getInstance().getContactList();
if (!contactList.containsKey(bean.getUserid())){
EaseUser user = new EaseUser(bean.getUserid());
user.setNickname(bean.getNickname());
user.setAvatar(getActivity().getResources().getString(R.string.service_host_address)+bean.getImg());
contactList.put(bean.getUserid(),user);
DemoHelper.getInstance().setContactList(contactList);
// 存入db
UserDao dao = new UserDao(getActivity());
List<EaseUser> users = new ArrayList<EaseUser>();
users.add(user);
dao.saveContactList(users);
DemoHelper.getInstance().getModel().setContactSynced(true);
}
Utils.loginIM(getActivity(), Constant.userInfo.getUserId() + "", friendUserid);
} else {
Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
}
}
});
注意:存入数据库的数据方法dao.saveContactList(users);这个保存数据的方法需要修改
这是修改后的:
synchronized public void saveContactList(List<EaseUser> contactList) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
if (db.isOpen()) {
// db.delete(UserDao.TABLE_NAME, null, null);
for (EaseUser user : contactList) {
ContentValues values = new ContentValues();
values.put(UserDao.COLUMN_NAME_ID, user.getUsername());
if (user.getNickname() != null)
values.put(UserDao.COLUMN_NAME_NICK, user.getNickname());
if (user.getAvatar() != null)
values.put(UserDao.COLUMN_NAME_AVATAR, user.getAvatar());
// db.replace(UserDao.TABLE_NAME, null, values);
db.insert(UserDao.TABLE_NAME, null, values);
}
}
}
登录方法:
/**
* 环信 即时通讯 登录
*
* @param currentUsername 自己的userid
* @param friendUserid 就是对方的userid
*
*/
public static void loginIM(final Activity activity, String currentUsername, final String friendUserid) {
EMClient.getInstance().login(currentUsername, "123456", new EMCallBack() {
@Override
public void onSuccess() {
EMClient.getInstance().groupManager().loadAllGroups();
EMClient.getInstance().chatManager().loadAllConversations();
if (friendUserid != null && !friendUserid.isEmpty()) {
Intent intent = new Intent(activity, ChatActivity.class);
intent.putExtra("userId", friendUserid);
activity.startActivity(intent);
}
// 将自己服务器返回的环信账号、昵称和头像URL设置到帮助类中。
DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(Utils.getUsetname());
DemoHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(Utils.getUserimg());
DemoHelper.getInstance().setCurrentUserName(com.ylean.redshellapp.utils.Constant.userInfo.getUserId() + ""); // 环信Id
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(final int code, final String message) {
if (code == 200) {//用户已登录
if (friendUserid != null && !friendUserid.isEmpty()) {
Intent intent = new Intent(activity, ChatActivity.class);
intent.putExtra("userId", friendUserid);
activity.startActivity(intent);
}
// 将自己服务器返回的环信账号、昵称和头像URL设置到帮助类中。
DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(Utils.getUsetname());
DemoHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(Utils.getUserimg());
DemoHelper.getInstance().setCurrentUserName(com.ylean.redshellapp.utils.Constant.userInfo.getUserId() + ""); // 环信Id
}
}
});
}
2.发送消息的地方:
protected void sendMessage(EMMessage message) {
if (message == null) {
return;
}
if (chatFragmentHelper != null) {
//set extension
chatFragmentHelper.onSetMessageAttributes(message);
}
String usernick = SharePrefUtil.getString(getActivity(), "usernick", "");
String userimg = SharePrefUtil.getString(getActivity(), "userimg", "");
int userid = SharePrefUtil.getInt(getActivity(), "userid", -1);
SharePrefUtil.saveInt(getActivity(), "receuserid", userid);
message.setChatType(ChatType.Chat);
message.setAttribute("userimg", userimg);
message.setAttribute("usernick", usernick);
message.setAttribute("userid", userid);
message.setMessageStatusCallback(messageStatusCallback);
// Send message.
EMClient.getInstance().chatManager().sendMessage(message);
//refresh ui
if (isMessageListInited) {
messageList.refreshSelectLast();
}
}
3.接收消息的地方 onMessageReceived()
@Override
public void onMessageReceived(List<EMMessage> messages) {
Intent intent = new Intent();
//对应BroadcastReceiver中intentFilter的action
intent.setAction("com.yinlin.received.UnreadMsg");
//发送广播
appContext.sendBroadcast(intent);
for (EMMessage message : messages) {
EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());
//***********接收并处理扩展消息***********8 好友发送过来的数据
String userName = message.getStringAttribute("usernick", "");
String userPic = message.getStringAttribute("userimg", "");
SharePrefUtil.saveString(appContext, "friendUserNick", userName);
SharePrefUtil.saveString(appContext, "friendUserImg", userPic);
String hxIdFrom = message.getFrom();
EaseUser easeUser = new EaseUser(hxIdFrom);
easeUser.setAvatar(userPic);
easeUser.setNickname(userName);
// 存入内存
getContactList();
contactList.put(hxIdFrom, easeUser);
setContactList(contactList);
// 存入db
UserDao dao = new UserDao(MyApplication.getContext());
List<EaseUser> users = new ArrayList<EaseUser>();
users.add(easeUser);
dao.saveContactList(users);
getModel().setContactSynced(true);
// 通知listeners联系人同步完毕
notifyContactsSyncListener(true);
}
}
4.取出来用 getUserInfo
private EaseUser getUserInfo(String username) {
EaseUser user = null;
if (contactList != null && contactList.containsKey(username)) {
} else { // 如果内存中没有,则将本地数据库中的取出到内存中。
getContactList();
}
user = contactList.get(username);
if (user == null) {
user = new EaseUser(username);
if (user.getAvatar() == null && username.equals(com.ylean.redshellapp.utils.Constant.userInfo.getUserId() + "")) {
String usernick = "", userimg = "";
usernick = SharePrefUtil.getString(appContext, "usernick", "");
userimg = SharePrefUtil.getString(appContext, "userimg", "");
user.setAvatar(userimg);
user.setNickname(usernick);
contactList.put(username, user);
setContactList(contactList);
// 存入db
UserDao dao = new UserDao(appContext);
List<EaseUser> users = new ArrayList<EaseUser>();
users.add(user);
dao.saveContactList(users);
DemoHelper.getInstance().getModel().setContactSynced(true);
}
} else {
if (TextUtils.isEmpty(user.getNickname())) { // 如果名字为空,则显示环信号码
user.setNickname(user.getUsername());
}
}
return user;
}
5展示头像setUpBaseView()方法
private void setUpBaseView() {
// set nickname, avatar and background of bubble
TextView timestamp = (TextView) findViewById(R.id.timestamp);
if (timestamp != null) {
if (position == 0) {
timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
timestamp.setVisibility(View.VISIBLE);
} else {
// show time stamp if interval with last message is > 30 seconds
EMMessage prevMessage = (EMMessage) adapter.getItem(position - 1);
if (prevMessage != null && DateUtils.isCloseEnough(message.getMsgTime(), prevMessage.getMsgTime())) {
timestamp.setVisibility(View.GONE);
} else {
timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime())));
timestamp.setVisibility(View.VISIBLE);
}
}
}
if (userAvatarView != null) {
//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);
//
// SharePrefUtil.saveString(context, "direct", "RECEIVE");
// String friendUserImg = SharePrefUtil.getString(getContext(), "friendUserImg", null);
// String friendUserNick = SharePrefUtil.getString(getContext(), "friendUserNick", null);
// EaseUserUtils.setUserAvatar(context, friendUserImg, userAvatarView);
// EaseUserUtils.setUserNick(friendUserNick, usernickView);
}
}