We apologize for the inconvenience of this page no longer being maintained. For the latest product information, please visit our current product introduction page. >>

Message Receiving

Update time: 2024/08/20 15:45:46

The SDK provides a set of messaging management features, such as sending and receiving messages, storing messages, uploading and downloading attachments. You are allowed to send text, audio messages, image, video, file, location, and custom messages.

The message structure is IMMessage and different message types are identified by MsgTypeEnum. IMMessage does not support inheritance or extension.

For information about parameters, message sending, message resending, message recalling and audio message, see Message sending.

Receiving messages

After adding message receiving observerMsgServiceObserve#observeReceiveMessage, the third-party app can receive a message when a new message is sent.

  • API prototype
java/**
 * Register or unregister the observer for receiving messages.
 * The messages in the list of messages of a notification may not be received completely or may be sent out, for example, the message sent from other clients is roamed here.
 * Or, after MsgService#saveMessageToLocal(IMMessage, boolean) is invoked, the parameter notify is set to true, i.e. to notify the message.
 * @param observer - Observer. The parameter is the list of received messages. In the list, messages are taken from the same object.
 * @param register true indicates registered, and true indicates unregistered.
 */
public void observeReceiveMessage(Observer<List<IMMessage>> observer, boolean register);
  • Example
javaObserver<List<IMMessage>> incomingMessageObserver =
	new Observer<List<IMMessage>>() {
	    @Override
	    public void onEvent(List<IMMessage> messages) {
		    // Process received new message. To upload conveniently, the SDK ensures that all messages are taken from the same chat object.
        }
    }
NIMClient.getService(MsgServiceObserve.class)
		.observeReceiveMessage(incomingMessageObserver, true);

Receiving notification messages

For some actions in specific scenarios, CommsEase server presets some notification messages. The notification is also a specific message. Developers must parse data in messages to get notification content. The most ordinary notification message is group notification event, for example, if a new member joins a group , then all members of the group will receive the notification message. The notification message cannot be sent from client now.

The notification message is a message in session, of which corresponding data structure is IMMessage and type is MsgTypeEnum.notification. The notification is mainly used to notify group event and chat room event.

The notification message must be parsed. See group Notification Message.

Receiving multimedia messages

The multi-media message includes audio, image, file, and video messages. You should consider resource download after a message is received. For multi-media messages, use CommsEase upload service:

  • If image and video messages are received, the SDK will automatically download thumbnails and cover images when receiving the message by default.
  • If audio messages are received, the SDK will automatically download original audio files when receiving the message by default.
  • If file messages are received, the SDK will not download original files.

If you want to disable the default policy, please choose the download time on your own in the following ways:

  • Close automatic download

Update the initialization parameterSDKOptions - preloadAttach to "false".

  • Active download of attachments:

Prototype

java/**
 * Generally, the attachment will be downloaded automatically when a message is received. If the download fails, the interface can be invoked to download again.
 *
 * @param msg - Message body of attachment
 * @param thumb - Determine to download thumbnail. If it is "true", only thumbnail must be downloaded.
 * The parameter is valid for image and video message only.
 * @return AbortableFuture - Callback tracking The callback feature can be configured to stop downloading.
 */
public AbortableFuture<Void> downloadAttachment(IMMessage msg, boolean thumb);
  • Parameters
Parameter Description
msg Message body of attachment.
thumb Determine that only a thumbnail is downloaded. If "true", only a thumbnail is downloaded. The parameter is valid only for image and video messages.
  • Example
java// Determine download status before download. If the download is repeated, error code 414 will be returned. (Take SnapChatAttachment for an example)
private boolean isOriginImageHasDownloaded(final IMMessage message) {
    if (message.getAttachStatus() == AttachStatusEnum.transferred &&
        !TextUtils.isEmpty(((SnapChatAttachment) message.getAttachment()).getPath())) {
        return true;
    }
    return false;
}
// Because the large size of a downloaded file, the interface will return AbortableFuture and only allow users to cancel download during the download operation.
AbortableFuture future = NIMClient.getService(MsgService.class).downloadAttachment(message, false);
  • attachment parameters

After download, you can get specific attachment content using corresponding MsgAttachment. The base class of multimedia attachments is FileAttachment, which inherits from MsgAttachment. The subclasses mainly include:

- Video message attachment VideoAttachment

- Image message attachment ImageAttachment

- Audio message attachment AudioAttachment

FileAttachment is taken for an example to describe attachment parameters:

Return FileAttachment interface Description
String getPath() Get the local file path. If the file is not found, "null" will be returned.
You can get file path of audio message after downloading attachment.
You can get file image or video path after manual download. When the message is received, the SDK only downloads thumbnail files automatically by default.
String getPathForSave() Get the file saving location.
String getThumbPath() Get local path of thumbnail file. If the file is not found, "null" will be returned.
When the message status shows that thumbnail has been downloaded, you can get the thumbnail file path.
String getThumbPathForSave() Get the thumbnail file saving location.
void setPath(String path) Set file path.
long getSize() Get file size, unit: byte.
void setSize(long size) Set file size. Unit: byte.
String getMd5() Get file content MD5.
void setMd5(String md5) Set file content MD5.
String getUrl() Get file download url on server. If the file has not been uploaded, "null" will be returned.
void setUrl(String url) Set file download url on server.
String getExtension() Get file suffix name.
void setExtension(String extension) Set file suffix name.
String getFileName() Get file name.
String getDisplayName() Get file display name. It is different from file name and used for interface display only.
String setDisplayName() Set file display name.

For other types of attachment attributes, see Client API Document.

Listening for the message status

The interface can monitor change of message receiving or sending status "MsgStatusEnum" and attachment receiving or sending status "AttachStatusEnum". When the status is changed to AttachStatusEnum.transferred, it indicates that attachment has been downloaded successfully.

  • API Prototype
java/**
 * Register or unregister the observer for changes in message status.
 * @param observer - Observer. The parameter is changed message body. The updated status may include status and attachStatus.
 * @param register true indicates registered, and true indicates unregistered.
 */
public void observeMsgStatus(Observer<IMMessage> observer, boolean register);
  • Parameters

MsgStatusEnum property

MsgStatusEnum property Description
draft Draft
sending The message is being sent.
success The message is sent successfully.
fail The message is not sent successfully.
read It applies to received audio messages that have not been read by current users.
unread Unread status.

AttachStatusEnum attribute

AttachStatusEnum attribute Description
def The status is disabled by default.
transferring The message is being transferred.
transferred The message has been transferred successfully, with successful attachment download token.
fail The message has not been transferred successfully.
  • Example
java// Listen changes in message status.
NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(statusObserver, register);

private Observer<IMMessage> statusObserver = new Observer<IMMessage>() {
        @Override
        public void onEvent(IMMessage msg) {
            // 1. Determine your message by sessionId.
            // 2. Update status of message in memory.
            // 3. Refresh the interface.
        }
    };

Receiving messages in a chat room

For more information, see the chat room topic.

Filtering messages

The SDK supports message filtering. After message filtering, the SDK will neither store the corresponding message nor throw it to the receiving callback, so the application layer will not receive the corresponding message.

The filtering feature is only valid for online messages, offline messages, and roaming messages. During query, local and cloud history cannot be filtered.

We do not recommend executing time-consuming operation in message filtering feature or method. Otherwise, the thread may be blocked.

We recommend to register filter in onCreate under Application after SDK initialization.

  • API prototype
java/**
 * Register message filter.
 *
 * @param filter - Message filter implemented by upper-level developers. It determines to filter messages (not to store in database). If the value is null, it indicates to log out / cancel the filter for notification messages.
 */
void registerIMMessageFilter(IMMessageFilter filter);
  • Parameters
Return IMMessageFilter interface Description
boolean shouldIgnore(IMMessage message) Determine that message is filtered.
Returned "true" indicates message filtering (then SDK will not store the message and the upper developer will not receive the message).
default "false" indicates message non-filtering(the message is saved to db by default and informed of the upper developer).
  • Example

The SDK filters update notification for group profile picture.

java// It is registered when the app is opened to ensure that the filter can be called back to filter roaming and offline messages. Notes: The time-consuming operation must be avoided to implement the filter.
NIMClient.getService(MsgService.class).registerIMMessageFilter(new IMMessageFilter() {
        @Override
        public boolean shouldIgnore(IMMessage message) {
            if (UserPreferences.getMsgIgnore() && message.getAttachment() != null) {
                if (message.getAttachment() instanceof UpdateTeamAttachment) {
                    UpdateTeamAttachment attachment = (UpdateTeamAttachment) message.getAttachment();
                    for (Map.Entry<TeamFieldEnum, Object> field : attachment.getUpdatedFields().entrySet()) {
                        if (field.getKey() == TeamFieldEnum.ICON) {
                            return true; // Filter
                        }
                    }
                }
            }
            return false; // Not to filter.
        }
    });

Read receipt

When the sender wants to know whether the recipient has read the message already sent, the feature of read receipts is enabled.

Read receipt for messages in one-to-one chats

Send read receipts: The interface of sending read receipts is called in the session interface and the last message of the current session is fed, which indicates that all messages have been read.

  • API prototype
java/**
* Send read receipt of a message.
* @param sessionId - Chat object ID (account of the chat object).
* @param message - Read message (generally, it is the final message that is received currently.)
*/
NIMClient.getService(MsgService.class).sendMessageReceipt(sessionId, message);
  • Example
java// The account is an example. Please register.
String account = "testAccount";
// message - Final read message in a session.
NIMClient.getService(MsgService.class).sendMessageReceipt(account, message);

Monitor read receipt:

  • API prototype
java/**
 * Register or unregister the observer for read receipt.
 * @param observer - Observer. The parameter is the set of read receipts.
 * @param register true indicates registered, and true indicates unregistered.
 */
public void observeMessageReceipt(Observer<List<MessageReceipt>> observer, boolean register);
  • Parameters
Return Method Description
String getSessionId() Chat object ID. It is user account for one-to-one chat and group ID for group chat.
long getTime() If the time of final read message in the session is earlier than the time, it is considered to have been read.
  • Example
java// Register or unregister the observer
NIMClient.getService(MsgServiceObserve.class).observeMessageReceipt(messageReceiptObserver, register);
private Observer<List<MessageReceipt>> messageReceiptObserver = new Observer<List<MessageReceipt>>() {
        @Override
        public void onEvent(List<MessageReceipt> messageReceipts) {
            receiveReceipt();
        }
};

In addition, you can determine whether the message has been read using isRemoteRead() in IMMessage.

Read receipt for messages in group chats

You must contact our commercial consultant to apply for enabling the read receipt for group message feature. Also, you should limit the number of group members to 100 when enabling this feature.

  • Enable read receipt for messages in group chats.

When SDK is initialized, you must set SDKOptions - enableTeamMsgAck parameter to "true" to enable the read receipt for group message feature.

  • Require other group members to send read receipts when they receive this message.

When sending group messages, you can mark that read receipt is required for the message using IMMessage - setMsgAck() method. When receiving group messages, you can get whether read receipt is required for the message using IMMessage - needMsgAck attribute.

Example

java// Create a message to be sent.
IMMessage message = MessageBuilder.createTextMessage(sessionId, SessionTypeEnum.Team, "content");
// Mark the need of read receipt feedback for the message.
message.setMsgAck();
// Send a message.
NIMClient.getService(MsgService.class).sendMessage(message, false);
  • The message recipient sends a group message read receipt.

Prototype

java/**
 * (Team message recipient) Mark a team message as "read".
 *
 * @param message - Team messages.
 * @return InvocationFuture - Configurable callback feature. It can monitor the sending result.
 */
InvocationFuture<Void> sendTeamMessageReceipt(IMMessage message);

Example

javaNIMSDK.getTeamService().sendTeamMessageReceipt(message)

In addition, you can determine whether read receipt for group message has been sent using IMMessage - hasSendAck().

  • The message sender monitors read receipt for group messages.

Prototype

java/**
 * Register or unregister the observer for read receipt of a group message (when group members send a message requiring read receipt, if some members read the message, the observer will be called back).
 *
 * @param observer - Observer. The parameter is the information set of read receipts.
 * @param register true indicates registered, and true indicates unregistered
 */
public void observeTeamMessageReceipt(Observer<List<TeamMessageReceipt>> observer, boolean register);

Parameter Description

TeamMessageReceipt interface

Return Method Description
String getMsgId() Get message ID.
int getAckCount() Get read count.
int getUnAckCount() Get unread count.

Example

java// Register a listener.
NIMClient.getService(MsgServiceObserve.class).observeTeamMessageReceipt(teamMessageReceiptObserver, register);
// Implement a listener.
private Observer<List<TeamMessageReceipt>> teamMessageReceiptObserver = new Observer<List<TeamMessageReceipt>>() {
    @Override
    public void onEvent(List<TeamMessageReceipt> teamMessageReceipts) {
     ...
    }
};
  • Refresh read and unread count of group messages at a time.

Prototype

java/**
 * (Team message sender) Refresh read and unread count of team messages at a time, without asynchronous callback.
 * If there is any change in read and unread count, it will be notified using {@link com.netease.nimlib.sdk.msg.MsgServiceObserve#observeTeamMessageReceipt(Observer, boolean)} at a time. If there is not any change, no notification will be sent.
 *
 * @param messages - Set of Team profile requested for refresh.
 */
void refreshTeamMessageReceipt(List<IMMessage> messages);

Refreshes in batches is executed when a message is loaded. For repeated refreshes, the SDK will not send network request. The SDK will notify any change in read and unread count only using observer interface. API is asynchronous non-callback interface.

Example

java// messages - Received in-bulk messages.
NIMSDK.getTeamService().refreshTeamMessageReceipt(messages);
  • Query read and unread account list for a team message.

Prototype

java/**
 * (Team messages sender) Query read and unread account list for a team message.
 *
 * @param message - Message to be queried.
 * @return - List of read and unread accounts of the message.
 */
InvocationFuture<TeamMsgAckInfo> fetchTeamMessageReceiptDetail(IMMessage message);

Example

java// message - Message to be queried.
NIMSDK.getTeamService().fetchTeamMessageReceiptDetail(message).setCallback(new RequestCallback<TeamMsgAckInfo>() {
    @Override
    public void onSuccess(TeamMsgAckInfo param) {
        // Successful acquisition.
    }

    @Override
    public void onFailed(int code) {
		// Capture failed.
    }

    @Override
    public void onException(Throwable exception) {
		// Exception.
    }
});
  • Query read and unread account list for a group message from database.

Notes: The list acquired from database may be old.

Prototype

java/**
 * Query the list of read and unread accounts for a group message from the local database.
 * Notes!!! : The data acquired here is generally older than the list information before offline status.
 *
 * @param message - Message to be queried.
 * @return - List of read and unread accounts of the message.
 */
TeamMsgAckInfo queryTeamMessageReceiptDetailBlock(IMMessage message);

Example

java// message - Message to be queried.
NIMSDK.getTeamService().queryTeamMessageReceiptDetailBlock(message);
  • Query read and unread account count for a group message.

You can get read account count for group message using getTeamMsgAckCount() method under IMMessage interface, and get unread account count for group message using getTeamMsgUnAckCount() method.

Broadcast messaging

IM SDK supports broadcasting messages to all users, which are initiated by the server interface, and a broadcast message is sent to all the users in the application. The client cannot send any message. The SDK receives the broadcast and sends a notification to the upper layer. The message cannot be stored at the client.

  • API prototype
java/**
 * Register or unregister the observer for all-member broadcast message.
 * @param observer - Observer. The parameter is the all-member broadcast message.
 * @param register true indicates registered, and true indicates unregistered.
 */
public void observeBroadcastMessage(Observer<BroadcastMessage> observer, boolean register);
  • BroadcastMessage schema
Parameter Description
id Broadcast ID.
fromAccount Account of broadcast sender.
time Timestamp of broadcast message.
content Content of broadcast message.
  • Example
java/**
 * Register CommsEase full-service broadcast recipient.
 *
 * @param register
 */
private void registerNimBroadcastMessage(boolean register) {
    NIMClient.getService(MsgServiceObserve.class).observeBroadcastMessage(new Observer<BroadcastMessage>() {
        @Override
        public void onEvent(BroadcastMessage broadcastMessage) {
            // Processing
        }
    }, register);
}
Was this page helpful?
Yes
No
  • Receiving messages
  • Receiving notification messages
  • Receiving multimedia messages
  • Listening for the message status
  • Receiving messages in a chat room
  • Filtering messages
  • Read receipt
  • Read receipt for messages in one-to-one chats
  • Read receipt for messages in group chats
  • Broadcast messaging