融云语音会议室 发送和接收消息实现

文章目录

  • 前言
  • 一、定义消息实体类
  • 二、注册自定义消息
  • 三、自定义消息监听
  • 四、发送消息
  • 五、实现监听
  • 六、结论
  • 七、错误示范

前言

融云语音会议室 和融云聊天室完全是两个概念,融云API是完全不支持融云语音会议室的,所以说有关于语音会议室消息的发送是不能指望融云聊天来实现的,那么看博主是怎么做的吧。

一、定义消息实体类

import android.os.Parcel;
import android.support.annotation.IntDef;

import org.json.JSONException;
import org.json.JSONObject;

import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;

@MessageTag(value = "SealRTC:SetRoomInfo", flag = MessageTag.NONE)
public class RoomInfoMessage extends MessageContent {

    @IntDef({
            JoinMode.AUDIO_VIDEO,
            JoinMode.AUDIO,
            JoinMode.OBSERVER
    })
    public @interface JoinMode {
        int AUDIO_VIDEO = 0;
        int AUDIO = 1;
        int OBSERVER = 2;
    }

    private String userId;
    private String userName;
    private String userMessage;
    private @JoinMode int joinMode;
    private long timeStamp;

    public RoomInfoMessage(String userId, String userName, @JoinMode int joinMode, long timeStamp, String userMessage) {
        this.userId = userId;
        this.userName = userName;
        this.joinMode = joinMode;
        this.timeStamp = timeStamp;
        this.userMessage = userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

    public String getUserMessage() {
        return userMessage;
    }

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

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setJoinMode(@JoinMode int joinMode) {
        this.joinMode = joinMode;
    }

    public void setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    public int getJoinMode() {
        return joinMode;
    }

    public long getTimeStamp() {
        return timeStamp;
    }

    public RoomInfoMessage(byte[] data) {
        try {
            JSONObject jsonObject = new JSONObject(new String(data));
            JSONObject valueJson = jsonObject.getJSONObject("infoValue");
            userId = valueJson.getString("userId");
            userName = valueJson.getString("userName");
            userMessage = valueJson.getString("userMessage");
            joinMode = valueJson.getInt("joinMode");
            timeStamp = valueJson.getLong("joinTime");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] encode() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("infoKey", userId);
            JSONObject valueObject = new JSONObject();
            valueObject.put("userId", userId);
            valueObject.put("userName", userName);
            valueObject.put("joinMode", joinMode);
            valueObject.put("userMessage", userMessage);
            valueObject.put("joinTime", timeStamp);
            jsonObject.put("infoValue", valueObject);
            return jsonObject.toString().getBytes();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(userId);
        dest.writeString(userName);
        dest.writeString(userMessage);
        dest.writeInt(joinMode);
        dest.writeLong(timeStamp);
    }

    public RoomInfoMessage(Parcel parcel) {
        userId = parcel.readString();
        userName = parcel.readString();
        userMessage = parcel.readString();
        joinMode = parcel.readInt();
        timeStamp = parcel.readLong();
    }

    public static final Creator<RoomInfoMessage> CREATOR = new Creator<RoomInfoMessage>() {
        @Override
        public RoomInfoMessage createFromParcel(Parcel source) {
            return new RoomInfoMessage(source);
        }

        @Override
        public RoomInfoMessage[] newArray(int size) {
            return new RoomInfoMessage[size];
        }
    };

}

二、注册自定义消息

这个注册最好放在App的Oncreate中

   RongIMClient.registerMessageType(RoomInfoMessage.class);

三、自定义消息监听

监听设置最好是在joinRoom的onUiSuccess中

  RongRTCEngine.getInstance().joinRoom
import com.hkzr.yidui.model.RoomInfoMessage;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;

public class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {

    public MyReceiveMessageListener(GetUserMsgListener getUserMsgListener) {
        this.getUserMsgListener = getUserMsgListener;
    }

    @Override
    public boolean onReceived(Message message, int code) {
        MessageContent content = message.getContent();
        if (content instanceof RoomInfoMessage) {
            RoomInfoMessage roomInfoMessage = (RoomInfoMessage) content;
            String userName = roomInfoMessage.getUserName();
            String userMessage = roomInfoMessage.getUserMessage();
            if (null != getUserMsgListener)
                getUserMsgListener.receivedUserMsg(userName + ":" + userMessage);
        }
        return true;
    }

    public interface GetUserMsgListener {
        void receivedUserMsg(String msg);
    }

    GetUserMsgListener getUserMsgListener;
}

四、发送消息

private void sendMessage(String msg) {
        if (this.mRongRTCRoom != null) {
            String name = this.mUser.getUser().getName();
            RoomInfoMessage roomInfoMessage = new RoomInfoMessage(mUser.getUserId() + "", name, RoomInfoMessage.JoinMode.AUDIO, System.currentTimeMillis(), msg);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put(RongLibConst.KEY_USERID, roomInfoMessage.getUserId());
                jsonObject.put("userName", roomInfoMessage.getUserName());
                jsonObject.put("joinMode", Integer.valueOf(roomInfoMessage.getJoinMode()));
                jsonObject.put("joinTime", Long.valueOf(System.currentTimeMillis()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            this.mRongRTCRoom.setRoomAttributeValue(jsonObject.toString(), roomInfoMessage.getUserId(), roomInfoMessage, new RongRTCResultUICallBack() {

                public void onUiSuccess() {
                    adapter.addData(name + ": " + msg);
                    rc.smoothScrollToPosition(adapter.getData().size() - 1);
                }

                public void onUiFailed(RTCErrorCode errorCode) {
                }
            });
        }
    }

对~就是setRoomAttributeValue这个函数

五、实现监听

	@Override
    public void receivedUserMsg(String msg) {
        adapter.addData(msg);
        rc.smoothScrollToPosition(adapter.getData().size() - 1);
    }

六、结论

语音会议室内的消息发送就是这样,不同于普通聊天室,是没有自己的消息发送和接收的,所以有关于成员管理,踢人,历史消息,全部需要自己的实现。

setRoomAttributeValue意思为设置房间属性,那么利用这个接口我们就可以让所有的用户同步监听消息,同时根据不同的RoomInfoMessage做出不同的动作,比如踢人。

七、错误示范

博主也不是没有走弯路,下面给出一个错误的示范。

  /**
    * 发送消息
    */
   private void sendMessage(String msg) {
       if (mRongRTCRoom == null) return;
       RoomInfoMessage obtain = new RoomInfoMessage(
               mUser.getUserId() + "",
               mUser.getUsername(),
               RoomInfoMessage.JoinMode.AUDIO,
               Calendar.getInstance().getTimeInMillis()
       );
       mRongRTCRoom.sendMessage(m_id, obtain, new IRongCallback.ISendMediaMessageCallback() {
           @Override
           public void onProgress(Message message, int i) {
               LogUtils.i("发送消息:onProgress");
           }

           @Override
           public void onCanceled(Message message) {
               LogUtils.i("发送消息:onCanceled");
           }

           @Override
           public void onAttached(Message message) {
               LogUtils.i("发送消息:onAttached");
           }

           @Override
           public void onSuccess(Message message) {
               LogUtils.i("发送消息:onSuccess");
           }

           @Override
           public void onError(Message message, RongIMClient.ErrorCode errorCode) {
               LogUtils.i("发送消息:onError:" + errorCode.getValue());
           }
       });
   }

    @Override
    public void onReceiveMessage(Message message) {
        MessageContent messageContent = message.getContent();
        if (messageContent instanceof RoomInfoMessage) {
            RoomInfoMessage roomInfoMessage = (RoomInfoMessage) messageContent;
            roomInfoMessage.getUserId();
            adapter.getData().add(roomInfoMessage.getUserName() + " : " /*+ roomInfoMessage.getUserMessage()*/);
        }
    }

放心~ 你永远都进入不了onReceiveMessage监听,而只会是一个超时的errorCode

你可能感兴趣的:(Android)