- Android
- iOS
- JavaScript
- Flutter
- ReactNative
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());
Create a Custom Message
A custom message must inherit from MessageContent and implement the methods below.
@interface CustomMessage : JMessageContent
@property (nonatomic, copy) NSString *value;
@end
@implementation CustomMessage
//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.
+ (NSString *)contentType {
return @"my:custom";
}
//Override the parent class's encode method to convert all message fields to NSData.
- (NSData *)encode {
NSDictionary * dic = @{@"value":self.value?:@""};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
return data;
}
//Override the parent class's decode method to populate valid message fields from NSData
- (void)decode:(NSData *)data {
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.value = json["value"]?:@"";
}
//message summary displayed in the conversation list; optional
- (NSString *)conversationDigest {
return self.content?:@"";
}
@end
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.shared.messageManager registerContentType:[CustomMessage class]];
Send a Custom Message
Create a custom message object and send it by calling the SDK sendMessage API.
JConversation *conversation = [[JConversation alloc] initWithConversationType:JConversationTypePrivate conversationId:@"userid2"];
CustomMessage *c = [[CustomMessage alloc] init];
c.value = @"This is a custom message";
JMessage *m = [JIM.shared.messageManager sendMessage:c
inConversation:conversation
success:^(long long clientMsgNo) {
NSLog(@"sendMessage success");
} error:^(JErrorCode errorCode, long long clientMsgNo) {
NSLog(@"sendMessage error");
}];
NSLog(@"after send, m.clientMsgNo is %lld", m.clientMsgNo);
Custom messages support the same send parameters as Send a Message. Before sending, register the custom message to tell the SDK whether it should be counted and stored. Registration is required only once and can be performed after SDK initialization.
Parameters
| Name | Type | Required | Default | Description | Version |
|---|---|---|---|---|---|
| message | Object | Yes | Message object | 1.0.0 | |
| message.conversationType | Number | Yes | Conversation type | 1.0.0 | |
| message.conversationId | String | Yes | Conversation ID. For PRIVATE conversations, it is the recipient userId; for GROUP conversations, it is the group ID. | 1.0.0 | |
| message.name | String | Yes | Message name. Use it to send different message types as needed; see [MessageType] for enum details.(../../../enum/web#message) | 1.0.0 | |
| message.content | Object | Yes | Message content used to construct the message.name message | 1.0.0 | |
| message.mentionInfo | Object | No | None | Applies when conversationType is GROUP. Setting mentionInfo marks this message as a mention message. | 1.0.0 |
| mentionInfo.mentionType | Number | No | None | Mention type. See Mention Message Enums for details. | 1.0.0 |
| mentionInfo.targetIds | Array | No | None | List of specified members. The SDK prioritizes mentionType when determining the mention type. | 1.0.0 |
Success Callback
| Name | Type | Description | Version |
|---|---|---|---|
| message | Object | After sending succeeds, returns a message object with messageId and sentTime. See Message for the message structure. | 1.0.0 |
Failure Callback
| Name | Type | Description | Version |
|---|---|---|---|
| result | Object | When sending fails, returns an object containing tid and error. Check error.msg directly or see [status codes].(../../../status_code/web) | 1.0.0 |
Code Example
let { ConversationType } = JIM;
/** Step 1: Register the custom message once globally ***********/
let MSG_NAME = {
TEST_MSG_NAME: 'test:msgname'
};
let msgs = [
// isCount: whether the conversation unread count increases by 1 when the recipient receives the message
// isStorage: whether to store the message in message history
{ name: MSG_NAME.TEST_MSG_NAME, isCount: true, isStorage: true },
];
jim.registerMessage(msgs)
/** Step 2: Send the custom message ***********/
let msg = {
conversationType: ConversationType.GROUP,
conversationId: 'groupid1',
name: MSG_NAME.TEST_MSG_NAME,
content: {
// Define the text property according to the cross-platform contract
text: 'Hello JIM'
}
};
jim.sendMessage(msg).then((message) => {
console.log(message);
}, (error) => {
let { error, tid } = result;
// Use tid to update the failed-message state. On Web, failed messages are stored only in SDK memory and are unavailable after a refresh
console.log(tid, error);
});
Create a Custom Message
A custom message must inherit from MessageContent and implement the methods below.
import JuggleIM from 'juggleim-rnsdk';
class CustomMessage implements CustomMessageContent {
contentType = 'my:custom';
value: string = '';
//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.
//Override the parent class's encode method to convert all message fields to JSON.
encode(): string {
const map = { "value": this.value };
return JSON.stringify(map);
}
//Override the parent class's decode method to populate valid message fields from JSON.
decode(jsonStr: string): void {
const map = JSON.parse(jsonStr);
this.value = map['value'] || '';
}
}
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.
JuggleIM.registerCustomMessageType('my:custom', CustomMessage);
Send a Custom Message
Create a custom message object and send it by calling the SDK sendMessage API.
const customMessage = new CustomMessage();
customMessage.value = 'This is value';
const conversation = {
type: 1,
id: 'userId1'
};
const callback = (message: any, errorCode: number) => {
if (errorCode === 0) {
console.log('sendMessage success, messageId is ' + message.messageId);
} else {
console.log('sendMessage error, errorCode is ' + errorCode.toString());
}
};
JuggleIM.sendMessage({
conversation: conversation,
content: customMessage
}, callback);
Create a Custom Message
A custom message must inherit from MessageContent and implement the methods below.
class CustomMessage extends MessageContent {
String value = '';
CustomMessage();
//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.
String getContentType() {
return "my:custom";
}
//Override the parent class's encode method to convert all message fields to JSON.
String encode() {
Map map = {"value": value};
return json.encode(map);
}
//Override the parent class's decode method to populate valid message fields from JSON.
void decode(String string) {
Map map = json.decode(string);
value = map['value'] ?? '';
}
}
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.
JuggleIm.instance.registerMessageType(() => CustomMessage());
Send a Custom Message
Create a custom message object and send it by calling the SDK sendMessage API.
CustomMessage c = CustomMessage();
c.value = 'This is value';
Conversation conversation = Conversation(ConversationType.private, 'groupId1');
DataCallback<Message> callback = (m, errorCode) {
if (errorCode == 0) {
print("sendMessage success, messageId is " + m.messageId);
} else {
print('sendMessage error, errorCode is ' + errorCode.toString() + ', clientMsgNo is ' + m.clientMsgNo!.toString());
}
};
Message message = await JuggleIm.instance.sendMessage(c, conversation, callback);