Skip to main content

Create a Custom Message

A custom message must inherit from MessageContent and implement the methods below.

public class CustomMessage extends MessageContent {
//Implement the default constructor and specify contentType.
//contentType identifies the message type and must be globally unique.
//The SDK reserves all identifiers beginning with "jg:"; use any string that does not begin with this prefix.
public CustomMessage() {
mContentType = "my:custom";
}

//Override the parent class's encode method to convert all message fields to 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);
}

//Override the parent class's decode method to populate valid message fields from 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());
}
}

//message summary displayed in the conversation list; optional
@Override
public String conversationDigest() {
if (!TextUtils.isEmpty(mValue)) {
return mValue;
}
return "";
}

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

private String mValue;
}

Register a Custom Message

Call the SDK registration API so that it knows how to serialize and deserialize the custom message when sending and receiving messages. The registration API needs to be called only once.

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

Send a Custom Message

Create a custom message object and send it by calling the SDK sendMessage API.

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());