android 环信更改用户列表显示uid与用户名与头像

    来了,兄弟。就知道你会出现这个问题,等你很长时间了。

                                                                                

   1.这三个类自己复制

/**
 * sqlite数据库辅助类
 */

public class SqliteHelper extends OrmLiteSqliteOpenHelper {

    private final String LOG_TAG = getClass().getSimpleName();

    // 数据库名字
    private static final String DATABASE_NAME = "im_user_cache.db";

    // 版本号
    private static final int DATABASE_VERSION = 1;

    private static SqliteHelper mInstance;

    private Dao<UserCacheInfo, Integer> mUserInfoDao = null;

    public SqliteHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public synchronized static SqliteHelper getInstance(){
        if (mInstance == null) {
            ///TODO:: 把这里的 DemoApplication.getInstance() 换成自己的Application类实例对象。例如:new MainApplication()
            mInstance = new SqliteHelper(CINAPP.getInstance());
        }

        return mInstance;
    }

    /**
     * 创建SQLite数据库
     */
    @Override
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, UserCacheInfo.class);
        } catch (SQLException e) {
            Log.e(LOG_TAG, "Unable to create datbases", e);
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新SQLite数据库
     */
    @Override
    public void onUpgrade(
            SQLiteDatabase sqliteDatabase,
            ConnectionSource connectionSource,
            int oldVer,
            int newVer) {
        try {
            TableUtils.dropTable(connectionSource, UserCacheInfo.class, true);

            onCreate(sqliteDatabase, connectionSource);
        } catch (SQLException e) {
            Log.e(LOG_TAG,
                    "Unable to upgrade database from version " + oldVer + " to new "
                            + newVer, e);
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }

    public Dao<UserCacheInfo,Integer> getUserDao() throws SQLException{
        if(mUserInfoDao == null){
            try {
                mUserInfoDao = getDao(UserCacheInfo.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mUserInfoDao;
    }

}
/**
 * 用户缓存信息类
 * 需要ormlite库支持
 * Created by Martin on 2017/4/24.
 */
@DatabaseTable(tableName="UserCacheInfo")
public class UserCacheInfo{

    @DatabaseField(generatedId=true)
    private int id;

    /*环信ID*/
    @DatabaseField(index = true)
    private String userId;

    /*昵称*/
    @DatabaseField
    private String nickName;

    /*头像*/
    @DatabaseField
    private String avatarUrl;

    /*数据过期时间*/
    @DatabaseField(canBeNull = false)
    private long expiredDate;

    // 必须顶一个无参数的构造函数,否则会报【virtual method】异常
    UserCacheInfo(){}

    /*将json字符串转换成model*/
    public static UserCacheInfo parse(String jsonStr) {
        return (new Gson()).fromJson(jsonStr, UserCacheInfo.class);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public long getExpiredDate() {
        return expiredDate;
    }

    public void setExpiredDate(long expiredDate) {
        this.expiredDate = expiredDate;
    }

}
/**
 * 用户缓存管理类
 */
public class UserCacheManager {

    /**
     * 消息扩展属性
     */
    private static final String kChatUserId = "ChatUserId";// 环信ID
    private static final String kChatUserNick = "ChatUserNick";// 昵称
    private static final String kChatUserPic = "ChatUserPic";// 头像Url

    /**
     * 获取所有用户信息
     *
     * @return
     */
    public static List<UserCacheInfo> getAll() {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            List<UserCacheInfo> list = dao.queryForAll();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户环信ID
     * @return
     */
    public static UserCacheInfo get(final String userId) {
        UserCacheInfo info = null;

        // 如果本地缓存不存在或者过期,则从存储服务器获取
      /*  if (notExistedOrExpired(userId)){
            UserWebManager.getUserInfoAync(userId, new UserWebManager.UserCallback() {
                @Override
                public void onCompleted(UserWebInfo info) {
                    if(info == null) return;

                    // 缓存到本地
                    // info.getOpenId() 为该用户的【环信ID】
                    save(info.getOpenId(), info.getNickName(),info.getAvatarUrl());
                }
            });
        }*/

        // 从本地缓存中获取用户数据
        info = getFromCache(userId);

        return info;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户环信ID
     * @return
     */
    public static UserCacheInfo getFromCache(String userId) {

        try {
            Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
            UserCacheInfo model = dao.queryBuilder().where().eq("userId", userId).queryForFirst();
            return model;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    public static EaseUser getEaseUser(String userId) {

        UserCacheInfo user = get(userId);
        if (user == null) return null;

        EaseUser easeUser = new EaseUser(userId);
        easeUser.setAvatar(user.getAvatarUrl());
        easeUser.setNickname(user.getNickName());

        return easeUser;
    }

    /**
     * 用户是否存在
     *
     * @param userId 用户环信ID
     * @return
     */
    public static boolean isExisted(String userId) {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            long count = dao.queryBuilder().where().eq("userId", userId).countOf();
            return count > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 用户不存在或已过期
     *
     * @param userId 用户环信ID
     * @return
     */
    public static boolean notExistedOrExpired(String userId) {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            long count = dao.queryBuilder().where()
                    .eq("userId", userId).and()
                    .gt("expiredDate", new Date().getTime())
                    .countOf();
            return count <= 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 缓存用户信息
     *
     * @param userId    用户环信ID
     * @param avatarUrl 头像Url
     * @param nickName  昵称
     * @return
     */
    public static boolean save(String userId, String nickName, String avatarUrl) {
        try {
            Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();

            UserCacheInfo user = getFromCache(userId);

            // 新增
            if (user == null) {
                user = new UserCacheInfo();
            }

            user.setUserId(userId);
            user.setAvatarUrl(avatarUrl);
            user.setNickName(nickName);
            user.setExpiredDate(new Date().getTime() + 30 * (24 * 60 * 60 * 1000));// 七天过期,单位:毫秒

            Dao.CreateOrUpdateStatus status = dao.createOrUpdate(user);

            if (status.getNumLinesChanged() > 0) {
                Log.i("UserCacheManager", "操作成功~");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("UserCacheManager", "操作异常~");
        }

        return false;
    }

    /**
     * 更新当前用户的昵称
     *
     * @param nickName 昵称
     */
    public static void updateMyNick(String nickName) {
        UserCacheInfo user = getMyInfo();
        if (user == null) return;

        save(user.getUserId(), nickName, user.getAvatarUrl());
    }


    /**
     * 更新当前用户的头像
     *
     * @param avatarUrl 头像Url(完成路径)
     */
    public static void updateMyAvatar(String avatarUrl) {
        UserCacheInfo user = getMyInfo();
        if (user == null) return;

        save(user.getUserId(), user.getNickName(), avatarUrl);
    }

    /**
     * 缓存用户信息
     *
     * @param model 用户信息
     * @return
     */
    public static boolean save(UserCacheInfo model) {

        if (model == null) return false;

        return save(model.getUserId(), model.getNickName(), model.getAvatarUrl());
    }

    /**
     * 缓存用户信息
     *
     * @param ext 用户信息
     * @return
     */
    public static boolean save(String ext) {
        if (ext == null) return false;

        UserCacheInfo user = UserCacheInfo.parse(ext);
        return save(user);
    }

    /**
     * 缓存用户信息
     *
     * @param ext 消息的扩展属性
     * @return
     */
    public static void save(Map<String, Object> ext) {

        if (ext == null) return;

        try {
            String userId = ext.get(kChatUserId).toString();
            String avatarUrl = ext.get(kChatUserPic).toString();
            ;
            String nickName = ext.get(kChatUserNick).toString();
            ;

            save(userId, nickName, avatarUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前环信用户信息
     *
     * @return
     */
    public static UserCacheInfo getMyInfo() {
        return get(EMClient.getInstance().getCurrentUser());
    }

    /**
     * 获取用户昵称
     *
     * @return
     */
    public static String getMyNickName() {
        UserCacheInfo user = getMyInfo();
        if (user == null) return EMClient.getInstance().getCurrentUser();

        return user.getNickName();
    }

    /**
     * 设置消息的扩展属性
     *
     * @param msg 发送的消息
     */
    public static void setMsgExt(EMMessage msg) {
        if (msg == null) return;
        UserCacheInfo user = getMyInfo();
        msg.setAttribute(kChatUserId, user.getUserId());
        msg.setAttribute(kChatUserNick, user.getNickName());
        msg.setAttribute(kChatUserPic, user.getAvatarUrl());
    }

    /**
     * 获取登录用户的昵称头像
     *
     * @return
     */
    public static String getMyInfoStr() {
        Map<String, Object> map = new HashMap<>();

        UserCacheInfo user = getMyInfo();
        map.put(kChatUserId, user.getUserId());
        map.put(kChatUserNick, user.getNickName());
        map.put(kChatUserPic, user.getAvatarUrl());

        return new Gson().toJson(map);
    }
}

 2.什么?复制完了,报错 

  compile 'com.j256.ormlite:ormlite-android:5.0'

 

 3.更改DemoHelp中getUserInfo()方法

 private EaseUser getUserInfo(String username) {
        EaseUser user = UserCacheManager.getEaseUser(username);

//        if(username.equals(EMClient.getInstance().getCurrentUser()))
//            return getUserProfileManager().getCurrentUserInfo();
//        user = getContactList().get(username);
//        if(user == null && getRobotList() != null){
//            user = getRobotList().get(username);
//        }

        // if user is not in your contacts, set inital letter for him/her
        if (user == null) {
            user = new EaseUser(username);
            EaseCommonUtils.setUserInitialLetter(user);
        }
        return user;
    }

 

4.找到消息监听,保存用户头像与用户名到本地数据库()

  protected void registerMessageListener() {
        messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d(TAG, "onMessageReceived id : " + message.getMsgId());
                    UserCacheManager.save(message.ext());
                    // in background, do not refresh UI, notify it in notification bar
                    if (!easeUI.hasForegroundActivies()) {
                        getNotifier().notify(message);
                    }
                  //  EventBus.getDefault().post(new EventUnreadMsg(2));
                }
            }

 UserCacheManager.save() 主要是这个方法。

 5. 发送消息是也把头像用户名带过去

    在环信demo中这个在chatFragment中每次发消息,把用户信息带过去就行了。 找到你项目对应这个回调在哪。

  @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            //set message extension
            message.setAttribute("em_robot_message", isRobot);
        }
        UserCacheManager.setMsgExt(message);
    }

  6.遇到的问题

     这个扩展消息的方式,我使用的是每次只有互发一次消息,才能正确的显示用户的头像。在我们项目的解决方案就是通过同意添加好友就默认发送一条消息。在添加好友监听中,如果你是粘环信demo中,这个回调在DemoHelp中找找。

    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
        

            //默认发送一条消息,显示名称
            EMMessage message = EMMessage.createTxtSendMessage("你好", username);
            UserCacheManager.setMsgExt(message);
            //如果是群聊,设置chattype,默认是单聊
        }

         ...........
}

 7.搞定没,搞定了还看着干嘛,给个赞啊。

 

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值