30.融云即时通讯基本的收发消息(IMLib)

转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/51208203
本文出自:猴菇先生的博客

1.集成:按照融云官网文档集成即可;
2.在BaseApplication中初始化:

    /**
     * 初始化融云即时通讯
     */
    private void initRongIm() {
        /**
         * OnCreate 会被多个进程重入,这段保护代码,确保只有您需要使用 RongIMClient 的进程和 Push 进程执行了 init。
         * io.rong.push 为融云 push 进程名称,不可修改。
         */
        if(getApplicationInfo().packageName.equals( 
            SysInfoUtils.getCurProcessName(getApplicationContext())) 
            ||"io.rong.push".equals(
            SysInfoUtils.getCurProcessName(getApplicationContext()))) {
                RongIMClient.init(this);
            }
        }
    }

     /**
     * 获得当前进程的名字
     *
     * @param context context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

3.在MainActivity.java中连接、接收消息、发送消息:

    /**
     * 融云相关
     */
    private void setRongIm() {
        getToken();
        receiveMsg();
        RongIMClient.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
            @Override
            public void onChanged(ConnectionStatus connectionStatus) {
                LogMessage.e("monkey", "融云连接状态监听--> " + connectionStatus.toString());
            }
        });
        RongIMClient.setOnReceivePushMessageListener(new RongIMClient.OnReceivePushMessageListener() {
            @Override
            public boolean onReceivePushMessage(PushNotificationMessage pushNotificationMessage) {
                LogMessage.e("monkey", "融云离线通知监听--> " + pushNotificationMessage.getPushContent());
                //返回true可以不显示融云离线消息通知
                return true;
            }
        });
    }

    /**
     * 请求Server API,获取token
     */
    private void getToken() {
        deviceId = SysInfoUtils.readTelephoneSerialNum(MainActivity.this);//userId用设备号替代
        String name = "monkey";//用户名
        String portraitUri = "http://rongcloud-web.qiniudn.com/docs_demo_rongcloud_logo.png";//头像
        HomeApi.getRongToken(deviceId, name, portraitUri, new ApiCallBack<RongImBean>() {
            //请求token的接口地址是"https://api.cn.ronghub.com/user/getToken.json"
            //除了需要post传userId、name、和portraitUri外
            //还需要addHeader参数App-Key(申请的app key)、
            //                 Nonce(随机数 double r = new Random().nextDouble();)、
            //                 Timestamp(时间戳 long t = System.currentTimeMillis();)、
            //                 Signature(申请的app secret、Nonce和Timestamp的sha1加密值)
            @Override
            public void onSuccess(RongImBean result) {
                super.onSuccess(result);
                if (result != null && result.getToken() != null) {
                    token = result.getToken();
                    Log.e("monkey", "融云token--> " + token);
                    connect(token);
                }
            }
        });
    }

    /**
     * 接收消息
     */
    private void receiveMsg() {
        RongIMClient.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            /**
             * 收到消息的处理。
             * @param message 收到的消息实体。
             * @param i       剩余未拉取消息数目。
             * @return 是否接收
             */
            @Override
            public boolean onReceived(final Message message, int i) {

                if (message != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sendTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date(message.getSentTime()));
                            rongMsg = (TextMessage) message.getContent();
                            Log.e("monkey", "融云接收消息-->"
                                    + "userId:" + message.getSenderUserId()
                                    + " 内容:" + rongMsg.getContent()
                                    + " 发送时间:" + sendTime);
                            //收到消息后写自己的操作逻辑
                        }
                    });
                }
                return true;
            }
        });
    }

    /**
     * 建立与融云服务器的连接
     *
     * @param token token
     */
    private void connect(String token) {
        if (getApplicationInfo().packageName.equals(SysInfoUtils.getCurProcessName(getApplicationContext()))) {
            RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    Log.e("monkey", "融云 Token 错误,在线上环境下主要是因为 Token 已经过期,您需要向 App Server 重新请求一个新的 Token");
                }

                @Override
                public void onSuccess(String userId) {
                    Log.e("monkey", "连接融云成功--> " + userId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.e("monkey", "连接融云失败,错误码--> " + errorCode);
                }
            });
        }
    }

    /**
     * 发送消息
     */
    private void sendMsg(String userId) {
        /**
         * 发送普通消息
         * @param conversationType      会话类型
         * @param targetId              会话ID
         * @param content               消息的内容,一般是MessageContent的子类对象
         * @param pushContent           接收方离线时需要显示的push消息内容
         * @param pushData              接收方离线时需要在push消息中携带的非显示内容
         * @param SendMessageCallback   发送消息的回调
         * @param ResultCallback        消息存库的回调,可用于获取消息实体
         */
        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE, userId, TextMessage.obtain("你好"), null, null, new RongIMClient.SendMessageCallback() {
                    @Override
                    public void onSuccess(Integer integer) {
                        String str = "消息发送成功";
                        Log.e("monkey", str);
                    }

                    @Override
                    public void onError(Integer integer, RongIMClient.ErrorCode errorCode) {
                        String str = "消息发送失败";
                        Log.e("monkey", str);
                    }
                }, null);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是ElementUI集成融云即时通讯版本5.x的详细代码: 1. 首先需要在项目中引入融云WebIM SDK,可以使用npm或者直接引入CDN。 2. 在main.js中全局引入ElementUI和融云WebIM SDK: ``` import Vue from 'vue' import App from './App.vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import RongIMLib from 'rong-imlib-web-sdk' Vue.config.productionTip = false Vue.use(ElementUI) Vue.prototype.RongIMLib = RongIMLib new Vue({ render: h => h(App), }).$mount('#app') ``` 3. 在需要使用即时通讯的组件中,实现登录和聊天功能: ``` <template> <div class="chat-container"> <!-- 聊天列表 --> <div class="chat-list"> <div v-for="(item, index) in chatList" :key="index">{{ item }}</div> </div> <!-- 聊天输入框 --> <div class="chat-input"> <el-input v-model="inputMsg" placeholder="请输入消息"></el-input> <el-button @click="sendMsg">发送</el-button> </div> </div> </template> <script> export default { data() { return { inputMsg: '', // 输入框内容 chatList: [], // 聊天列表 targetId: 'targetId', // 目标用户ID conversationType: RongIMLib.CONVERSATION_TYPE.PRIVATE, // 会话类型 chatRoomId: null // 聊天室ID } }, methods: { // 登录融云 loginRongIM() { // 获取token,此处省略获取过程 let token = 'token' // 连接融云服务器 this.RongIMLib.RongIMClient.init('appKey') this.RongIMLib.RongIMClient.setConnectionStatusListener({ onChanged: (status) => { console.log('RongIM connect status: ' + status) } }) this.RongIMLib.RongIMClient.connect(token, { onSuccess: (userId) => { console.log('RongIM login success: ' + userId) // 设置当前用户信息 let userInfo = { id: userId, name: 'userName', avatar: 'avatarUrl' } this.RongIMLib.RongIMClient.getInstance().setCurrentUserInfo(userInfo) this.RongIMLib.RongIMClient.getInstance().setConversationNotificationStatus({ conversationType: this.conversationType, targetId: this.targetId, isBlocked: false, notificationStatus: RongIMLib.NOTIFY_STK_NOTIFY }) // 接收消息监听 this.RongIMLib.RongIMClient.getInstance().setOnReceiveMessageListener({ onReceived: (message) => { console.log('RongIM receive message: ' + message.content.content) // 将消息添加到聊天列表 this.chatList.push(message.content.content) } }) }, onError: (errorCode) => { console.log('RongIM login error: ' + errorCode) } }) }, // 发送消息 sendMsg() { let content = this.inputMsg if (!content) { return } let msg = new this.RongIMLib.TextMessage({content: content}) let conversationType = this.conversationType let targetId = this.targetId this.RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, { onSuccess: (message) => { console.log('RongIM send message success: ' + message.content.content) // 将消息添加到聊天列表 this.chatList.push(message.content.content) // 清空输入框 this.inputMsg = '' }, onError: (errorCode, message) => { console.log('RongIM send message error: ' + errorCode + ', ' + message) } }) } }, mounted() { // 登录融云 this.loginRongIM() } } </script> ``` 以上是ElementUI集成融云即时通讯版本5.x的详细代码,需要注意的是,此处省略了获取token的过程,需要根据实际情况获取。另外,需要将appKey、targetId、conversationType等参数设置为正确的值,以保证功能正常运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值