Skip to main content

创建自定义消息

自定义消息需要继承自 MessageContent,并实现下面的方法。

public class CustomMessage extends MessageContent {
//必须实现默认的构造方法,并指定 contentType。
//contentType 是消息类型的标识符,请保证全局唯一性。
//SDK 内部保留了 "jg:" 开头的所有标识符,您可以指定除此开头外的任意字符串。
public CustomMessage() {
mContentType = "my:custom";
}

//重写父类的 encode 方法,将消息内的所有字段转换成 json。
@Override
public byte[] encode() {
JSONObject jsonObject = new JSONObject();
try {
if (!TextUtils.isEmpty(mValue)) {
jsonObject.put("value", mValue);
}
} catch (JSONException e) {
LoggerUtils.e("CustomMessage JSONException " + e.getMessage());
}
return jsonObject.toString().getBytes(StandardCharsets.UTF_8);
}

//重写父类的 decode 方法,将 json 转换成消息内的有效字段。
@Override
public void decode(byte[] data) {
if (data == null) {
LoggerUtils.e("CustomMessage decode data is null");
return;
}
String jsonStr = new String(data, StandardCharsets.UTF_8);

try {
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject.has("value")) {
mValue = jsonObject.optString("value");
}
} catch (JSONException e) {
LoggerUtils.e("CustomMessage decode JSONException " + e.getMessage());
}
}

//会话列表中显示的消息摘要,非必要实现
@Override
public String conversationDigest() {
if (!TextUtils.isEmpty(mValue)) {
return mValue;
}
return "";
}

public void setValue(String value) {
this.mValue = value;
}

private String mValue;
}

注册自定义消息

调用 SDK 的注册接口,使 SDK 在收发消息的时候,知道如何序列化和反序列化自定义消息。 注册接口调用一次即可。

JIM.getInstance().getMessageManager().registerContentType(CustomMessage.class);

发送自定义消息

构造自定义消息对象,并调用 SDK 的 sendMessage 接口进行发送。

CustomMessage c = new CustomMessage();
c.setValue("I am a custom message");
Conversation conversation = new Conversation(Conversation.ConversationType.PRIVATE, "userid1");
IMessageManager.ISendMessageCallback callback = new IMessageManager.ISendMessageCallback() {
@Override
public void onSuccess(Message message) {
Log.i("TAG", "send message success");
}

@Override
public void onError(Message message, int errorCode) {
Log.i("TAG", "send message error, code is " + errorCode);
}
};
Message message = JIM.getInstance().getMessageManager().sendMessage(c, conversation, callback);
Log.i("TAG", "after send, clientMsgNo is " + message.getClientMsgNo());