Android SDK Development Guide

Overview

JMessage provides developers with an easy-to-use and reliable IM development framework. Developers can integrate SDKs to quickly implement instant messaging capabilities. The SDK supports Android 2.3 or higher mobile phone systems.

To learn more about JMessage, please refer to the document: Product Introduction of JMessage

Message

The most important function of JMessage is instant messaging.

  • Ensure timely delivery of messages;
  • Single chat, group chat
  • Message type: text, voice, picture, file, location, etc.
  • Save offline messages when users are offline
  • Based on JPush's original large-capacity, stable long-term connection and concurrency capabilities of large-capacity message;

User

  • The developer's user is registered to JMessage based on username / password. SDK can initiate the registration of the user, or the server can initiate registration in batches.
  • When the user logs in to the App, he also logs in to JMessage. After logging in, he can send chat messages to other usernames or receive messages from other usernames or group messages. Whether user A has permission to send a message to user B is controlled by the App logic itself.
  • It is allowed to have users update user attributes such as avatars to JMessage.

Group

Multiple usernames can be added to a group to send group chat messages to the group.

  • Create groups and quit groups;
  • Add group members, remove group members;
  • Public groups added in version 2.4.0

Friend

  • From version 1.4.0, jmessage android sdk begins to provide interfaces for the hosting of user friend relationships and sending and receiving of related friend requests.

Note: Any other features built on friendship (such as chats between friends, etc.) need to be implemented by the developer's application layer.

Chat Room

  • From version 2.4.0, jmessage android sdk begins to provide chat room features, including basic information querying, join chat rooms, exit chat rooms. See details in chat room management.

String Specification

The field attributes and specifications in the JMessage are defined here for verification and normalization.

Parameter Character Description Length limit
app_key A 24-bit string generated by the JPush Web Portal. Letter or number, case insensitive.
username Start with a letter or number. Supports letters, numbers, underscores, English dots, minus signs, and @. Byte(4~128)
password Any Byte(4~128)
group_name Unsupported characters: "\n" "\r" Byte(0~64)
nickname Unsupported characters: "\n" "\r" Byte(0~64)
note_name Unsupported characters: "\n" "\r" Byte(0~64)
other Other String types that are not explicitly specified are treated as such. Support all characters Byte(0~250)

API List

Listed below are the main APIs provided by the JMessage SDK. For complete API and class information, visit: API Java docs

SDK Initialization

Before calling other interfaces of IM, you must first adjust this interface to initialize the SDK. It is recommended to call it in the application class. Message roaming is turned off by default.

JMessageClient.init(Context context)

Parameter Description

  • Context context object in the application

SDK Initialization (Set Message History Roaming)

Since 2.1.0

Initialize SDK and specify whether to enable message history roaming.

After opening the message roaming, when a user logs in between multiple devices, sdk will automatically synchronize the history message of current user to the local device, and send a ConversationRefreshEvent event to notify the upper layer to refresh after the synchronization is completed. See the event handling section for specific event handling methods.
Note: If the application contains multiple processes, the SDK initialization should be placed in the Application

JMessageClient.init(Context context, boolean msgRoaming)

Parameter Description

  • Context context object in the application.
  • boolean msgRoaming Whether to enable message roaming, true - enable, false - turn off.

Registration and Login

Registration

JMessageClient.register(String username, String password, BasicCallback callback);

/**
 * 注册同时指定用户信息中的其他字段
 * @since 2.3.0
 */
JMessageClient.register(String userName, String password, RegisterOptionalUserInfo optionalUserInfo, BasicCallback callback);

Parameter Description

  • String username
  • String password
  • RegisterOptionalUserInfo (optionalUserInfo: additional information of registered user)
  • BasicCallback

Login

JMessageClient.login(String username, String password, BasicCallback callback);

Parameter Description

  • String username
  • String password
  • BasicCallback callback

Logout

JMessageClient.logout();

Record of logging in

Since 2.5.0

Get login history of device when you log in

    /**
     * 用户登陆,并且在回调中获取用户账号所登陆过的设备信息{@link cn.jpush.im.android.api.model.DeviceInfo}<br/>
     * 每个端:移动端(Android 、iOS),PC端,Web端(JS、微信小程序)只保存最近一次设备登陆记录。
     *
     * @param userName 开发者注册的用户名,应该唯一。
     * @param password 用户登录密码,推荐将字符串加密。
     * @param callback 回调接口
     * @since 2.5.0
     */
    public static void login(String userName, String password, RequestCallback<List<DeviceInfo>> callback) {
        login(userName, password, (BasicCallback) callback);
    }

DeviceInfo

Method Type Instruction
getDeviceID() long Get device ID
getPlatformType() PlatformType Get the platform type of device
getOnlineStatus() int Get device status, 0 not online, 1 online
isLogin() boolean Determine if the device is currently logged in. true: login, false: log out
getLastLoginTime() int Get last login time of the device, unit - second
getFlag() int The default is 0, 1 means the device is kicked out by the current login device

Multi-end Simultaneously Online

From the version 2.3.0, SDK supports multi-end simultaneously online. For detailed rules, see the Multi-end Online Description.

User Attribute Maintenance

Get user information

JMessageClient.getUserInfo(String username, GetUserInfoCallback callback);

Parameter Description

  • String username
  • GetUserInfoCallback

Callback

JMessageClient.gotResult(int responseCode, String responseMessage, UserInfo userInfo);
  • UserInfo

Get user information (cross-application)

Get user information. This interface can be used to obtain user information under different appKeys. If appKey is empty, user information under the current appKey is obtained by default.

JMessageClient.getUserInfo(String username, String appKey, GetUserInfoCallback callback);

Parameter Description

  • String username
  • String appKey
  • GetUserInfoCallback

Get the user information of the current login account locally

JMessageClient.getMyInfo();

Parameter Description

  • N/A

Return

  • UserInfo

Update user information

JMessageClient.updateMyInfo(UserInfo.Field updateField, UserInfo info, BasicCallback callback);

Parameter Description

  • UserInfo.Field updateField enumeration type, indicates the user information field that needs to be updated. Include:

    • nickname
    • birthday
    • signature
    • gender
    • region
    • address
    • all
  • UserInfo userInfo The user information (object) to be updated. The SDK will determine which attribute needs to be updated to the server based on the field parameter.

  • BasicCallback

Update user password

JMessageClient.updateUserPassword(String oldPassword, String newPassword, BasicCallback callback);

Parameter Description

  • String oldPassword
  • String newPassword
  • BasicCallback

Update user avatar

JMessageClient.updateUserAvatar(File avatar, BasicCallback callback);

Parameter Description

  • File avatar
  • BasicCallback

Local Session Management

Create a single chat session

Create a single chat session. If a corresponding session already exists on the local, it will not be recreated and the local session object will be returned directly. By specifying appkey, you can send messages to users under other appkeys.

    Conversation.createSingleConversation(String username, String appkey)

Parameter Description

  • String username: The username of the session object.
  • String appkey: appkey of the application to which the user belongs. If it is empty, it defaults to the appkey of the application.

Create a group chat session

Create a group chat session. If a corresponding session object already exists on the local, it will not be recreated and the local session object will be returned directly.

Conversation.createGroupConversation(long groupID)

Parameter Description

  • groupID of the session object group

Get a list of conversations

Get the list of sessions from the local database, by default, it is in descending order according to the time of last message in the session

JMessageClient.getConversationList();

Parameter Description

  • N/A

Return

  • List<Conversation>  list of conversations.

Get a single chat session

Get the single chat session information with the username under the specified appkey. If the appkey is empty, the session for the username user in the appkey is used by default.

JMessageClient.getSingleConversation(String username, String appkey);

Parameter Description

  • String username : the user name of the target user.
  • String appkey: Appkey of the app to which the user belongs

Return

  • Conversation: the single chat session object that is matched based on the parameters.

Get a single group chat session

JMessageClient.getGroupConversation(long groupID);

Parameter Description

  • long groupID Group ID of the target group.

Return

  • Conversation: The group chat session object that is matched based on the parameters.

Delete a single chat session

Delete the single chat session with username under the specified appkey and delete the local chat record. If appkey is empty, the default attempt is to delete the session for the username corresponding to the appkey.

JMessageClient.deleteSingleConversation(String username, String appkey);

Parameter Description

  • String username:The user name of the target user.
  • String appkey:Appkey of the app to which the user belongs

Return

  • Whether boolean deleted successfully

Delete a single group chat session

JMessageClient.deleteGroupConversation(long groupID);

Parameter Description

  • long groupID:The group ID of the target group.

Return

  • Whether boolean deleted successfully

Get the number of unread messages in a single session

conversation.getUnReadMsgCnt();

return

  • Int:number of unread messages for the current session

Reset the number of unread messages for a single session

conversation.resetUnreadCount();

return

  • false. boolean true indicates that the reset was successful and false otherwise.

Set the number of unread messages manually

conversation.setUnReadMessageCnt(int count);

Parameter Description

  • int count - The number of unread messages specified by int count

return

  • boolean true indicates that the setting was successful, otherwise it returns false.

Get the total number of unread messages for all sessions

JMessageClient.getAllUnReadMsgCount();

return

  • int - Total number of unread messages for all current user sessions

Message Management

Create a text message

    /**
     * 创建一条单聊文本消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param username 聊天对象用户名
     * @param appKey   聊天对象所属应用的appKey
     * @param text     文本内容
     * @return 消息对象
     */
    JMessageClient.createSingleTextMessage(String username, String appKey, String text)

    /**
     * 创建一条群聊文本信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupID 群组的groupID
     * @param text    文本内容
     * @return 消息对象
     */
    JMessageClient.createGroupTextMessage(long groupID, String text)

Create a picture message

    /**
     * 创建一条单聊图片信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param username  聊天对象的用户名
     * @param appKey    聊天对象所属应用的appKey
     * @param imageFile 图片文件
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createSingleImageMessage(String username, String appKey, File imageFile) throws FileNotFoundException

    /**
     * 创建一条群聊图片信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupID   群组的groupID
     * @param imageFile 图片文件
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createGroupImageMessage(long groupID, File imageFile) throws FileNotFoundException

Create a voice message

    /**
     * 创建一条单聊语音信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param username  聊天对象的用户名
     * @param appKey    聊天对象所属应用的appKey
     * @param voiceFile 语音文件
     * @param duration  语音文件时长
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createSingleVoiceMessage(String username, String appKey, File voiceFile, int duration) throws FileNotFoundException

    /**
     * 创建一条群聊语音信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupID   群组groupID
     * @param voiceFile 语音文件
     * @param duration  语音文件时长
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createGroupVoiceMessage(long groupID, File voiceFile, int duration) throws FileNotFoundException

Create a location message

    /**
     * 创建一条单聊地理位置消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param username  聊天对象的用户名
     * @param appKey    聊天对象所属应用的appKey
     * @param latitude  纬度信息
     * @param longitude 经度信息
     * @param scale     地图缩放比例
     * @param address   详细地址信息
     * @return 消息对象
     */
    JMessageClient.createSingleLocationMessage(String username, String appKey, double latitude, double longitude, int scale, String address)

    /**
     * 创建一条群聊地理位置消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupId   群组groupID
     * @param latitude  纬度信息
     * @param longitude 经度信息
     * @param scale     地图缩放比例
     * @param address   详细地址信息
     * @return 消息对象
     */
    JMessageClient.createGroupLocationMessage(long groupId, double latitude, double longitude, int scale, String address)

Create a file message

    /**
     * 创建一条单聊file消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param userName 聊天对象的用户名
     * @param appKey   聊天对象所属应用的appKey
     * @param file     发送的文件
     * @param fileName 指定发送的文件名称,如果不填或为空,则默认使用文件原名。
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createSingleFileMessage(String userName, String appKey, File file, String fileName) throws FileNotFoundException, JMFileSizeExceedException

    /**
     * 创建一条群聊file消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupID  群组groupID
     * @param file     发送的文件
     * @param fileName 指定发送的文件名称,如果不填或为空,则默认使用文件原名。
     * @return 消息对象
     * @throws FileNotFoundException
     */
    JMessageClient.createGroupFileMessage(long groupID, File file, String fileName) throws FileNotFoundException, JMFileSizeExceedException

Create a custom message

 /**
     * 创建一条单聊自定义消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param username  聊天对象username
     * @param appKey    聊天对象所属应用的appKey
     * @param valuesMap 包含自定义键值对的map.
     * @return 消息对象
     */
JMessageClient.createSingleCustomMessage(String username, String appKey, Map<? extends String, ? extends String> valuesMap)

 /**
  * 创建一条群聊自定义消息
  *
  * @param groupID   群组groupID
  * @param valuesMap 包含了自定义键值对的map
  * @return  消息对象
  */
JMessageClient.createGroupCustomMessage(long groupID,
  Map<? extends String, ?> valuesMap)

Create a video message

    /**
     * 创建一条单聊video消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param userName      聊天对象用户名
     * @param appKey        聊天对象所属应用appkey
     * @param thumbImage    视频缩略图,可不填。
     * @param thumbFormat   视频缩略图格式名
     * @param videoFile     视频文件对象
     * @param videoFileName 视频文件名称,如果不填或为空,则默认使用文件原名
     * @param duration      视频时长
     * @return 消息对象
     * @throws IOException
     * @since 2.6.0
     */
    JMessageClient.createSingleVideoMessage(String userName, String appKey, Bitmap thumbImage, String thumbFormat, File videoFile, String videoFileName, int duration) throws IOException

    /**
     * 创建一条群聊video消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
     * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
     * 接口来创建消息
     *
     * @param groupID       群组groupID
     * @param thumbImage    视频缩略图,可不填。
     * @param thumbFormat   视频缩略图格式名
     * @param videoFile     视频文件对象
     * @param videoFileName 视频文件名称,如果不填或为空,则默认使用文件原名
     * @param duration      视频时长
     * @return 消息对象
     * @throws IOException
     * @since 2.6.0
     */
    JMessageClient.createGroupVideoMessage(long groupID, Bitmap thumbImage, String thumbFormat, File videoFile, String videoFileName, int duration) throws IOException

Monitor message sending result

After the message is sent, the interface will be called back to inform the upper layer.

message.setOnSendCompleteCallback(BasicCallback sendCompleteCallback)

Parameter Description

  • BasicCallback sendCompleteCallback callback interface

Send message

Send a message through the server to the sending object and save it to the local session. Send by default configuration parameters

JMessageClient.sendMessage(Message message);

Parameter Description

  • Message message - message object

Message sending with control parameters

Since 2.2.0
For the message sending operation, some optional parameter configurations are supported. See MessageSendingOptions for specific parameters.

JMessageClient.sendMessage(Message message, MessageSendingOptions options);

Parameter Description

  • Message message - message object
  • MessageSendingOptions - control options when sending messages
Example Code
Message message = mConversation.createSendMessage(new TextContent(“Hello jmessage.”));
message.setOnSendCompleteCallback(new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseDesc) {
        if (responseCode == 0) {
            //消息发送成功
        } else {
            //消息发送失败
        }
    }
});
MessageSendingOptions options = new MessageSendingOptions();
options.setRetainOffline(false);

JMessageClient.sendMessage(message);//使用默认控制参数发送消息
//JMessageClient.sendMessage(message,options);//使用自定义的控制参数发送消息

Acquire local message record

Any message belongs to a certain session, so to obtain the local message record, you first need to obtain the conversation object conversation, and then obtain the message record in the session.

Get all messages in the session

    /**
     * 获取会话中所有消息,消息按照时间升序排列.<br/>
     *
     * @return 包含会话中所有消息的List
     */
    conversation.getAllMessage();

Get the message list by condition

    /**
     * 会话中消息按时间降序排列,从其中的offset位置,获取limit条数的消息.
     *
     * @param offset 获取消息的起始位置
     * @param limit  获取消息的条数
     * @return 符合查询条件的消息List, 如果查询失败则返回空的List。
     */
    conversation.getMessagesFromNewest(int offset, int limit)

    /**
     * 会话中消息按时间升序排列,从其中的offset位置,获取limit条数的消息.<br/>
     *
     * @param offset 获取消息的起始位置
     * @param limit  获取消息的条数
     * @return 符合查询条件的消息List, 如果查询失败则返回空的List。
     */
    conversation.getMessagesFromOldest(int offset, int limit);

Receive message

When sdk receives a message, it throws a MessageEvent or OfflineMessageEvent. Developers can get specific Message object through this event, and then perform UI refresh or other related logic. See the specific event processing method in Event Handling section

Changes of Received Message from Version 2.1.0

2.1.0版本开始,sdk将消息下发分为在线下发和离线下发两种类型。 先明确两个概念:Starting from the 2.1.0 release, sdk divides the message delivery into online delivery and offline delivery. First clear two concepts:

  • Online messages: During the im user's online period, all received messages are called online messages.
  • Offline messages: Messages generated during the im user's offline period (including logout or network disconnection) are temporarily stored on the Jiguang Server. When the user goes online again, sdk will pull this part of the message, which is called offline news.

With the distinction between these two concepts, sdk also handles these two messages differently:

Version Online message Offline message
Before 2.1.0 Throws a MessageEvent after every message received Like online news, how many offline messages there are, how many MessageEvent will be thrown
After 2.1.0 Throws a MessageEvent after every message received In session units, sdk throws an OfflineMessageEventif there is an offline message. Even if there are multiple offline messages in the same session, sdk will only throw an OfflineMessageEvent,This Event contains all the information related to offline messages. This will greatly reduce the pressure on the upper level to handle incidents.

Summary

After sdk is upgraded to version 2.1.0 (or later), the upper layer needs to make the following changes to the processing of message receiving:

  • In addition to the MessageEvent, a new event type, OfflineMessageEvent, was added to receive offline message events.
  • For developers who need message roaming, he needs add the reception of the ConversationRefreshEvent event. After the roaming message in the session is completed, sdk will trigger this event to notify the upper layer to refresh session.

Example Code:

    /**
      类似MessageEvent事件的接收,上层在需要的地方增加OfflineMessageEvent事件的接收
      即可实现离线消息的接收。
    **/
    public void onEvent(OfflineMessageEvent event) {
        //获取事件发生的会话对象
        Conversation conversation = event.getConversation();
        List<Message> newMessageList = event.getOfflineMessageList();//获取此次离线期间会话收到的新消息列表
        System.out.println(String.format(Locale.SIMPLIFIED_CHINESE, "收到%d条来自%s的离线消息。\n", newMessageList.size(), conversation.getTargetId()));
    }


    /**
      如果在JMessageClient.init时启用了消息漫游功能,则每当一个会话的漫游消息同步完成时
      sdk会发送此事件通知上层。
    **/
    public void onEvent(ConversationRefreshEvent event) {
        //获取事件发生的会话对象
        Conversation conversation = event.getConversation();
        //获取事件发生的原因,对于漫游完成触发的事件,此处的reason应该是
        //MSG_ROAMING_COMPLETE
        ConversationRefreshEvent.Reason reason = event.getReason();
        System.out.println(String.format(Locale.SIMPLIFIED_CHINESE, "收到ConversationRefreshEvent事件,待刷新的会话是%s.\n", conversation.getTargetId()));
        System.out.println("事件发生的原因 : " + reason);
    }

Retract Message

Retract a message in a conversation

Since 2.2.0
Initiated by the sender

conversation.retractMessage(Message message, BasicCallback callback)

Parameter Description

  • Message message - Message entity of message that needs to be withdrawn
  • BasicCallback callback - callback interface

Event notification to withdrawn party

Since 2.2.0
After the message sender initiates the withdrawal, the withdrawn party receives an event notification MessageRetractEvent. See the Event Handling section for how to handle specific events.

Note: Regardless of recalled party or withdrawn party, the message content is replaced with the PromtContent type after the message is withdrawn, and the content of the message becomes invisible.

Forward Message

Forward a message in a conversation

    /**
     * 转发消息,只有发送成功或收到的消息才可转发
     *
     * @param message  需要转发的消息对象
     * @param conv     目标会话
     * @param options  消息转发时的控制选项,仅对此次发送生效, null则使用默认配置
     * @param callback 回调函数
     * @since 2.3.0
     * @deprecated deprecated since jmessage 2.6.0 use {@link JMessageClient#forwardMessage(Message, Conversation, MessageSendingOptions, RequestCallback)} instead.
     */
    JMessageClient.forwardMessage(Message message, Conversation conv, MessageSendingOptions options, BasicCallback callback);

    /**
     * 转发消息,注意只有发送成功或收到的消息才可转发,符合转发要求后会创建新的消息发送,
     * 创建的消息会在回调中返回(无论发送是否成功),如果不符合转发要求则不会创建新消息 message返回null。<br/>
     *
     * @param message  需要转发的消息对象
     * @param conv     目标会话
     * @param options  消息转发时的控制选项,仅对此次发送生效, null则使用默认配置
     * @param callback 回调函数
     * @since 2.6.0
     */
    JMessageClient.forwardMessage(Message message, Conversation conv, MessageSendingOptions options, final RequestCallback<Message> callback);

Message Read Receipt

Read receipt setting

The message sender can set whether to require the receiver to send a read receipt for a single message when sending the message. The default behavior is false Since 2.3.0

messageSendingOptions.setNeedReadReceipt(boolean needReadReceipt)

Parameter Description

  • boolean needReadReceipt - Whether the receiver needs to send a read receipt. true - yes, false - no.

Get the number of people who have not sent a read receipt yet

When a message that requires the recipient to send a read receipt is successfully issued, the message sender can view the number of people who have not yet sent the read receipt. Since 2.3.0

  message.getUnreceiptCnt()

Interface return

  • int - The number of people who have not yet sent read receipts.
Returns 0 when all recipients have read or this message does not require a read receipt

Get current read receipt details

After a message that requires the receiver to send a read receipt is successfully issued, the message sender can view the details of the current read receipt . The details include the UserInfo list of the user who has currently sent the read receipt and has not sent the read receipt.

Since 2.3.0

  message.getReceiptDetails(GetReceiptDetailsCallback callback)

Parameter Description

  • GetReceiptDetailsCallback callback - result callback

The message receiver marks the message as read

For message receivers, a message can be marked as read. After successful marking, the read status of this message is recorded locally.

When this message is a message that requires read receipt, sdk will also send a notification event MessageReceiptStatusChangeEvent to the message sender to inform that the number of receivers who has sent read receipt has changed.

Note that this read state will only be saved locally, and the read state will be reset to false after the local data is cleared or the user changes the device to log in.

Since 2.3.0

  message.setHaveRead(BasicCallback callback)

Parameter Description

  • BasicCallback callback - result callback

Get whether the message is read

For the message receiver, this interface can be used to obtain whether the message is read. By default, all read status of received messages is false. The read status of the message becomes true after successfully invoking the message.setHaveRead(BasicCallback callback) interface Note that this read state will only be saved locally, and the read state will be reset to false after the local data is cleared or the user changes the device to log in.

Since 2.3.0

  message.haveRead()

Interface return

  • boolean: Read state of boolean messages. true - read, false - unread

Message Receipt Status Change Event

MessageReceiptStatusChangeEvent

For a message sent by a message sender that requires the receiver to send a read receipt, after the receiver successfully sends a read receipt via the message.setHaveRead(BasicCallback callback) interface, sdk throws the event notification message sender. Through this event, the sender can know the unreported number of which message in which session has changed. The specific processing method see the event handling section

Receipt-related example code:

//消息发送方:
//===========发送带已读回执的消息:
final Message message = mConversation.createSendMessage(new TextContent(“这是一条需要对方发送已读回执的消息.”));
message.setOnSendCompleteCallback(new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseDesc) {
        if (responseCode == 0) {
            //消息发送成功
            message.getUnreceiptCnt();//带回执的消息发送成功后,可以查看当前尚未发送已读回执的人数
            message.getReceiptDetails(...);//获取当前已读回执详情,具体包括已读和未读用户的UserInfo列表。callback中代码略
        } else {
            //消息发送失败
        }
    }
});
MessageSendingOptions options = new MessageSendingOptions();
options.setNeedReadReceipt(true);//针对这条消息打开已读回执功能
JMessageClient.sendMessage(message,options);//使用自定义的控制参数发送消息
//===========

//===========消息发送方监听回执状态变化:
public void onEventMainThread(MessageReceiptStatusChangeEvent event) {
        Conversation conv = event.getConversation();
        tv_refreshEvent.append(String.format(Locale.SIMPLIFIED_CHINESE, "\n收到MessageReceiptStatusChangeEvent事件,会话对象是%s\n", conv.getTargetId()));
        for (MessageReceiptStatusChangeEvent.MessageReceiptMeta meta : event.getMessageReceiptMetas()) {
            tv_refreshEvent.append(String.format(Locale.SIMPLIFIED_CHINESE,
                    "回执数有更新的消息serverMsgID:%d\n当前未发送已读回执的人数:%d", meta.getServerMsgId(), meta.getUnReceiptCnt()));
        }
}
//===========


//消息接收方
//===========将消息标记为已读
if(!message.haveRead()){ //当消息的haveRead状态为false时,调用setHaveRead,将消息标记为已读
    msg.setHaveRead(new BasicCallback() {
        @Override
        public void gotResult(int responseCode, String responseMessage) {
            Toast.makeText(MessageReceiptActivity.this, "成功将消息标记为已读. responseCode = " + responseCode + " responseMessage =" + responseMessage, Toast.LENGTH_SHORT).show();
        }
    });
}
//===========

Command Transparent Transmission

Since 2.3.0
Commands sent through the transparent transmission will not be saved offline, but will be pushed when the other user is online. After sdk receives the command, it will not be saved locally, and the notification bar will not be sent.

The overall response is fast.
Developers can use transparent transmission to extend auxiliary functions in some online scenarios, such as implementing input status prompts.

Send command transparent transmission

    /**
     * 发送消息透传给个人。
     * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
     * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
     * sdk不会将此类透传消息内容本地化。
     *
     * @param username 目标的用户名
     * @param appKey   目标的appKey, 如果传入null或空字符串,则默认用本应用的appKey
     * @param msg      发送的消息内容
     * @param callback 回调函数
     * @since 2.3.0
     */
    JMessageClient.sendSingleTransCommand(String username, appkey, String cmd,  BasicCallback callback)

    /**
     * 发送消息透传给群。
     * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
     * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
     * sdk不会将此类透传消息内容本地化。
     *
     * @param gid      群组的gid
     * @param msg      发送的消息内容
     * @param callback 回调函数
     * @since 2.3.0
     */
    JMessageClient.sendGroupTransCommand(long gid, String msg, BasicCallback callback)

    /**
     * 发送透传消息给当前用户在其他平台已登录的设备。
     * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
     * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
     * sdk不会将此类透传消息内容本地化。
     *
     * @param platformType 平台类型,其中{@link PlatformType#all}表示发送给当前多端在线的其他所有设备(不包括本设备)。
     * @param msg          发送的消息内容
     * @param callback     回调函数
     * @since 2.5.0
     */
    JMessageClient.sendCrossDeviceTransCommand(PlatformType platformType, String msg, BasicCallback callback)

Event Handling

Register event receiving class

JMessageClient.registerEventReceiver(Object receiver);
JMessageClient.registerEventReceiver(Object receiver, int priority);

Parameter Description

  • Object receiver - Object of message receiving class
  • int priority - defines the priority of the event received. The default value is 0. The higher the priority, the earlier the event is received. (The priority is only valid for the receiver in the same thread mode)

Untie the event receiving class

JMessageClient.unRegisterEventReceiver(Object receiver);

Parameter Description

  • Object receiver – object of message receiver. After the object is unbound, it will no longer receive any events.

Event reception

After registering the event receiving class, the following method needs to be implemented in the message receiving class to receive the corresponding message. Sdk will distinguish different thread modes according to the method name of the implementation method. The commonly used thread modes are onEvent (default thread mode) and onEventMainThread (main thread mode).

Different types of events can be received by defining different types of parameters. The specific event type is defined in the section "Event Types"

Default thread (child thread) mode
public void onEvent(EventEntity event){
  //do your own business
}

The method body will be called in the default thread (child thread) and can be used to handle time-consuming operations.

Parameter Definition

  • EventEntity event - the event object. (Define that different types of parameters can receive different types of events. For specific usage, refer to "Example Code.")
Main thread mode
public void onEventMainThread(EventEntity event){
  //do your own business
}

The method body will be called in the main thread and can be used to refresh the UI.

Parameter definition

  • EventEntity event – the event object.

Event type

MessageEvent

Method Type Instruction
getMessage() Message Get message object


OfflineMessageEvent Since 2.1.0

Method Type Instruction
getConversation() Conversation Get the session object that received the offline message
getNewMessageList() List Get the list of offline messages received, including a list of offline messages that the session received offline this time. It may also contain messages sent by itself.
getOfflineMsgCnt() int Get the total number of offline messages for this session in the event.


ConversationRefreshEvent

Method Type Instruction
getConversation() Conversation Get the session object that needs to be refreshed
getReason() Reason Get the cause of the event


MyInfoUpdatedEvent

Method Type Instruction
getMyInfo() UserInfo Get my userinfo after updating


NotificationClickEvent

Method Type Instruction
getMessage() Message Get the message object corresponding to the clicked notification


UserLogoutEvent (Obsolete, use LoginStateChangeEvent instead)

Method Type Instruction
getMyInfo() UserInfo Get the information of the currently logged out account


UserDeletedEvent (Obsolete, use LoginStateChangeEvent instead)

Method Type Instruction
getMyInfo() UserInfo Get the information of current deleted account


LoginStateChangeEvent

Method Type Instruction
getMyInfo() UserInfo Get information of the current account whose login status has changed
getReason() Reason Get the reason for changing the login status.

MessageRetractEvent Since 2.2.0

Method Type Instruction
getConversation() Conversation Get the session object to which the recalled message belongs
getRetractedMessage() Message Gets the recalled message object. (Note! The MessageContent object of the Message retrieved at this time has changed from the original message content before revocation to the prompt text of PromptContent type)

MessageReceiptStatusChangeEvent  Since 2.3.0

Method Type Instruction
getConversation() Conversation Get the session object to which the message with unreceipt number changed belongs
getMessageReceiptMetas() List<MessageReceiptMeta> Get the MessageReceiptMeta of the message whose non-receipt number has changed. Include the serverMsg Id of the message, the current number of unreceipt, and the update number of unreceipt number

CommandNotificationEvent

Since 2.3.0


Method Type Instruction
getSenderUserInfo() UserInfo Get UserInfo of message sender by command transparent transmission
getType() Type Get the type of sending object by command transparent transmission, single chat is Type.single, group chat is Type.group
getTargetInfo() Objcet Get the Info of sending object by command transparent transmission. If the object is a single chat user, it is UserInfo. If the object is a group, it is GroupInfo. It will be enforced to transform when using.
getMsg() String Get the actual content of the command transparent transmission.

GroupApprovalEvent Since 2.4.0

Method Type Instruction
getType() Type Get the group member approval notification event type. It is Type.apply_join_group when actively applying, and Type.invited_into_groupwhen invited to join.
getFromUserInfo() UserInfo Get the initiator UserInfo of group member approval event. It is the applicant UserInfo when actively applying and inviter UserInfo when invited to join the group.
getApprovalUserInfoList() List<UserInfo> Get the user UserInfo that needs approval
getReason() String Get the reason for the occurrence of the incident, and the reason for applying is the application reason (may be null). When the one is invited to join the group, it is null.
acceptGroupApproval() void To approve the application, needs to specify username,appKey
refuseGroupApproval() void To reject the application, needs to specify username,appKey,reason (can be null)

GroupApprovalRefuseEvent Since 2.4.0

Method Type Instruction
getFromUserInfo() UserInfo Get the event initiator userInfo, which is the owner information in this event
getToUserInfoList() List<UserInfo> Get the user information list of event object, which is the UserInfo list of the user who is rejected into the group
getReason() String Get the reason for the incident, the reason why the owner rejects the approval
getGid() long Return the actual group Gid

ChatRoomMessageEvent Since 2.4.0

Method Type Instruction
getMessages() List<Message> Get a list of messages contained in chat room message events

GroupApprovedNotificationEvent Since 2.5.0

Method Type Instruction
getApprovalEventID() long Get the corresponding incoming approval event ID
getApprovalResult() boolean Get results of group approval
getGroupID() long Get the group ID corresponding to the group approval event
getOperator() UserInfo Get operator user information for this group approval
getApprovedUserInfoList() List<UserInfo> Obtain user information that has been approved. The approval of these users has been approved.

Example Code

Receive message events

class MessageEventReceiver extends Activity{

  @Override
  protected void onCreate() {
    super.onCreate(savedInstanceState);
    //这里只是为了展示注册事件接受者接口的用法,实际上开发者可以在任意类中注册事件接收者
    //,而不仅仅在Activity中。 下同
    JMessageClient.registerEventReceiver(this);
  }

  @Override
  protected void onDestroy() {
    JMessageClient.unRegisterEventReceiver(this);
    super.onDestroy();
  }

  public void onEvent(MessageEvent event){
    Message msg = event.getMessage();

    switch (msg.getContentType()){
        case text:
            //处理文字消息
            TextContent textContent = (TextContent) msg.getContent();
            textContent.getText();
            break;
        case image:
            //处理图片消息
            ImageContent imageContent = (ImageContent) msg.getContent();
            imageContent.getLocalPath();//图片本地地址
            imageContent.getLocalThumbnailPath();//图片对应缩略图的本地地址
            break;
        case voice:
            //处理语音消息
            VoiceContent voiceContent = (VoiceContent) msg.getContent();
            voiceContent.getLocalPath();//语音文件本地地址
            voiceContent.getDuration();//语音文件时长
            break;
        case custom:
            //处理自定义消息
            CustomContent customContent = (CustomContent) msg.getContent();
            customContent.getNumberValue("custom_num"); //获取自定义的值
            customContent.getBooleanValue("custom_boolean");
            customContent.getStringValue("custom_string");
            break;
        case eventNotification:
        //处理事件提醒消息
        EventNotificationContent eventNotificationContent = (EventNotificationContent)msg.getContent();
        switch (eventNotificationContent.getEventNotificationType()){
            case group_member_added:
            //群成员加群事件
            break;
            case group_member_removed:
            //群成员被踢事件
            break;
            case group_member_exit:
            //群成员退群事件
            break;
            case group_info_updated://since 2.2.1
            //群信息变更事件
            break;
        }
        break;
    }
  }
 }

Receive notification bar click event

class NotificationClickEvent extends Activity{
    @Override
    protected void onCreate() {
        super.onCreate(savedInstanceState);
        JMessageClient.registerEventReceiver(this);
    }
    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        super.onDestroy();
    }
    public void onEvent(NotificationClickEvent event){
        Intent notificationIntent = new Intent(mContext, ChatActivity.class);
        mContext.startActivity(notificationIntent);//自定义跳转到指定页面
    }

}

User login status change event

class UserLogoutEventReceiver extends Activity{
    @Override
    protected void onCreate() {
        super.onCreate(savedInstanceState);
        JMessageClient.registerEventReceiver(this);
    }
    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        super.onDestroy();``
    }
    public void onEvent(LoginStateChangeEvent event){
        LoginStateChangeEvent.Reason reason = event.getReason();//获取变更的原因
        UserInfo myInfo = event.getMyInfo();//获取当前被登出账号的信息
        switch (reason) {
            case user_password_change:
                //用户密码在服务器端被修改
                break;
            case user_logout:
                //用户换设备登录
                break;
            case user_deleted:
                //用户被删除
                break;
        }
     }

}

Group Information Maintenance

Create a group

JMessageClient.createGroup(String groupName, String groupDesc, CreateGroupCallback callback);

@since 2.3.0
JMessageClient.createGroup(String groupName, String groupDesc, File groupAvatarFile, String format, CreateGroupCallback callback);

Parameter Description

  • String groupName - group name
  • String groupDesc - group description
  • File groupAvatarFile - group avatar file
  • String format – extension of avatar file, do not include "."
  • CreateGroupCallback callback - result callback

Callback

  public abstract void gotResult(int responseCode, String responseMsg, long groupId);
  • long groupId - newly created group ID (when respnseCode = 0).

Dissolve groups

Since 2.5.0

    /**
     * 解散指定的群组,只有群的群主有权限解散。
     * 群组解散后会以message的形式通知到群内所有成员,类型为{@link cn.jpush.im.android.api.content.EventNotificationContent.EventNotificationType#group_dissolved}
     *
     * @param groupID 群组id
     * @param callback 回调
     * @since 2.5.0
     */
    JMessageClient.adminDissolveGroup(long groupID, BasicCallback callback);

Get a list of groups

JMessageClient.getGroupIDList(GetGroupListCallback callback)

Callback

public abstract void gotResult(int responseCode, String responseMessage,
            List<Long> groupIDList)
  • List groupIDList - list of groupIDs of the groups to which the user is joined currently

Get group information

JMessageClient.getGroupInfo(long groupId, GetGroupInfoCallback callback)

Parameter Description

  • long groupId - group ID
  • GetGroupInfoCallback callback - result callback

Callback

  public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo)
  • GroupInfo groupInfo - the group information object returned

Update group name

groupInfo.updateName(String groupName, BasicCallback callback);

Parameter Description

  • String groupName - new name
  • BasicCallback callback - result callback

Update group description

groupInfo.updateDescription(String groupDesc, BasicCallback callback);

Parameter Description

  • String groupName - new group details description
  • BasicCallback callback - result callback

Update group description

Since 2.3.0

groupInfo.updateAvatar(File avatar, String format, BasicCallback callback);

Parameter Description

  • File avatar - group avatar file
  • String format - file extension, note that the name does not contain "."
  • BasicCallback callback - result callback

Add group members

JMessageClient.addGroupMembers(long groupID, String appKey, List<String> userNameList, BasicCallback callback)

Parameter Description

  • long groupId - the group ID of the group to be added. Returns when creating a group.
  • String appkey - the appkey to which the added group member belongs. If empty, the default is appkey of the application.
  • List usernameList - a list of group members, using the member username.
  • BasicCallback callback - result callback

Remove group members

JMessageClient.removeGroupMembers(long groupId, String appKey, List<String> usernameList, BasicCallback callback);

Parameter Description

  • long groupId - group ID of the member to delete.
  • String appkey - the appkey to which the removed group member belongs. If empty, it defaults to appkey of this application.
  • List usernameList - the list of members to delete.
  • BasicCallback callback - result callback

Transfer owners

Since 2.5.0

    /**
     * 移交群主,将群主移交給指定群内成员,移交群主后原群主成为普通群成员.<br/>
     * 移交群主成功后群内所有成员会收到群主变更事件,SDK收到事件会以类型为{@link cn.jpush.im.android.api.content.EventNotificationContent.EventNotificationType#group_owner_changed}
     * 的消息事件方式上报
     *
     * @param username 待移交者用户名
     * @param appKey 待移交者appKey, 若传入空则默认使用本应用appKey
     * @since 2.5.0
     */
    groupInfo.changeGroupAdmin(String username, String appKey, BasicCallback callback);

Quit group

JMessageClient.exitGroup(long groupId, BasicCallback callback);

Parameter Description

  • long groupId - Group ID to exit.
  • BasicCallback callback - result callback.

Get a list of group members

JMessageClient.getGroupMembers(long groupID,
      GetGroupMembersCallback callback)

Parameter Description

  • long groupId - group ID
  • GetGroupMembersCallback callback

Callback

  public void gotResult(int responseCode, String responseMessage, List<String> members);
  • List members - member lists (username)

Block Group Message

After the group is set to be blocked, the group's messages will not be received. However, the change of the group members can still be received normally.

Since 2.1.0

Set up a group message block

groupinfo.setBlockGroupMessage(int blocked, BasicCallback callback)

Parameter Description

  • int blocked: whether to block group messages. 1 - blocked, 0 - unblocked
  • BasicCallback callback - result callback.

Determine whether the group is blocked

groupinfo.isGroupBlocked();

return

  • int 1 - blocked, 0 - unblocked

Get the current group block list of users

JMessageClient.getBlockedGroupsList(GetGroupInfoListCallback callback)

Parameter Description

  • GetGroupInfoListCallback callback - result callback.

Groups @ Features

The sender of the message can send a message with @list.
After receiving the message with @list, if the @list contains itself, or is @all members, there will be corresponding prompts in the notification bar prompt popup by default in sdk, such as "xxx in the group@ you".

Create @group member message

Since 2.1.0

conversation.createSendMessage(MessageContent content, List<UserInfo> atList, String customFromName)

Parameter Description

  • MessageContent - object of message content
  • List atList -userInfo list of @user
  • String customFromName - custom fromName

Return

  • Message - message object

Create @All group members message

Since 2.2.0

conversation.createSendMessageAtAllMember(MessageContent content, String customFromName)

Parameter Description

  • MessageContent content – object of message content
  • String customFromName - custom fromName

Return

  • Message - message object containing @all member information

Determine whether the message is @ yourself

Since 2.1.0

message.isAtMe()

Return

  • boolean true - atList contains yourself, false - atList does not contain yourself

Determine whether the message is @all members

Since 2.1.0

message.isAtAll()

return

  • boolean true - is @all members, false - not @all members

Get the list of group members @ in the message Since 2.1.0

message.getAtUserList(GetUserInfoListCallback callback)

Parameter Description

  • GetUserInfoListCallback callback - Gets the callback interface of the user list. Note that this interface will return null when this message is a @all members message.

Example Code

    //消息发送方
    Conversation conv = Conversation.createGroupConversation(gid);
    GroupInfo groupInfo = (GroupInfo) conv.getTargetInfo();
    List<UserInfo> atList = new ArrayList<UserInfo>();
    atList.add(groupInfo.getGroupMemberInfo("user1", appkey));//获取到被@的群成员的userinfo,并填充到atList中去。
    atList.add(groupInfo.getGroupMemberInfo("user2", appkey));

    //创建一条带有atList的消息。
    Message msg = conv.createSendMessage(new TextContent("a message with atList!"), atList, null);
    JMessageClient.sendMessage(msg);//发送消息



    //消息接收方
    public void onEvent(MessageEvent event){
        Message msg = event.getMessage();//收到消息事件,从消息事件中拿到消息对象
        msg.isAtMe(); //判断这条消息是否@了我

        //获取消息中包含的完整的atList
        msg.getAtUserList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, List<UserInfo> userInfoList) {
                if(responseCode == 0){
                    //获取atList成功
                }else{
                    //获取atList失败
                }
            }
      });
    }

Public

Since 2.4.0
Version 2.4.0 added a new public group type. The only difference between the public group and the private group (original group) is that only the owner or the administrator can invite someone to join the group directly.

When other people in the group need to invite others to join the group, he must get the approval by the owner or administrator. Public group supports the application for joining.

Create a public group

Since 2.4.0

    /**
     * 创建公开群组, 群组创建成功后,创建者会默认包含在群成员中。
     * 公开群组与私有群组的区别是公开群组只有群主和管理员邀请入群才能直接入群,群内其他人员邀请他人入群需要经过群主或管理员审批,
     * 管理员相关见{@link GroupInfo#addGroupKeeper(List, BasicCallback)}, 同时公开群组支持申请入群操作{@link JMessageClient#applyJoinGroup(long, String, BasicCallback)},
     * 申请入群时也需要群主或管理员审批, 需要审批入群时群主和管理员会收到{@link cn.jpush.im.android.api.event.GroupApprovalEvent}事件
     * 通过{@link GroupInfo#getGroupType()}得到群组类型
     *
     * @param groupName 群组名称
     * @param groupDesc 群组描述
     * @param callback  回调接口
     * @since 2.4.0
     */
    JMessageClient.createPublicGroup(String groupName, String groupDesc,
                                             CreateGroupCallback callback);

    /**
     * 创建公开群组,群组创建成功后,创建者会默认包含在群成员中。
     * 公开群组定义参考{@link JMessageClient#createPublicGroup(String, String, CreateGroupCallback)}
     * 使用此接口创建群组时可以指定群头像,并且可以指定头像文件在后台存储时的扩展名,如果填空或者不填,则后台存储文件时将没有扩展名。
     *
     * @param groupName       群组名称
     * @param groupDesc       群组描述
     * @param groupAvatarFile 群组头像文件
     * @param format          头像文件扩展名,注意名称中不要包括"."
     * @param callback        回调接口
     * @since 2.4.0
     */
    JMessageClient.createPublicGroup(final String groupName, final String groupDesc, final File groupAvatarFile, String format,
                                             final CreateGroupCallback callback);

Apply to join the group

Since 2.4.0

    /**
     * 申请加入群组,只有公开群组(公开群组定义参考{@link JMessageClient#createPublicGroup(String, String, CreateGroupCallback)}),
     * 才能发送入群申请
     *
     * @param groupID  申请加入群组的gid
     * @param reason   申请理由,可为null
     * @param callback
     * @since 2.4.0
     */
    JMessageClient.applyJoinGroup(long groupID, String reason, BasicCallback callback);

Group members approval events/span>

Since 2.4.0

GroupApprovalEvent

Group members approval events. When receiving the group member approval notice, sdk will raise this event to inform the upper layer. The specific processing method see the event handling section

Approved event notification

Since 2.5.0

GroupApprovedNotificationEvent

The group member approval event has been approved to notify the event. When a group administrator or group owner approves the group member approval event, sdk will raise this event notification to the upper layer.

Only the group owner and group administrator of the group will be notified of the approval event. The specific processing method will be found in event handling section

Join group approval

Since 2.4.0
Approved by the received group member approval event. The approval can not be operated by more than one person, and when one person approves or rejects, the other manager or group owner will receive the [approved event notification]

    /**
     * 入群审批同意,操作成功后,群内所有成员包括被审批人自己都会收到一个包含群成员变化的EventNotification类型的消息
     *
     * @param username 同意入群者的username
     * @param appKey 同意入群者的appKey,若传入空则默认使用本应用的appKey
     * @param callback
     */
    groupApprovalEvent.acceptGroupApproval(String username, String appKey, final BasicCallback callback);

    /**
     * 入群审批拒绝,操作成功后,该次审批请求的发起方(Type为{@link Type#apply_join_group}时是申请人 Type为{@link Type#invited_into_group}时是邀请人)
     * 会收到一个审批拒绝通知事件{@link GroupApprovalRefuseEvent}
     *
     * @param username 拒绝入群者的username
     * @param appKey 拒绝入群者的appKey, 若传入空则默认使用本应用的appKey
     * @param reason 拒绝理由,可填null
     * @param callback
     */
    groupApprovalEvent.refuseGroupApproval(String username, String appKey, String reason, BasicCallback callback);

Group members approval rejected events

Since 2.4.0

GroupApprovalRefuseEvent

Group members approval rejected events. When receiving the group member approval rejection notification, sdk will raise this event notification to the upper layer. The specific processing method is shown in the event handling section.

Get all public groups under the specified app

Since 2.4.1

    /**
     * 获取指定应用appKey所属下公开群组基本信息, 如果appKey为空则默认使用本应用appKey.
     * 公开群组定义见{@link JMessageClient#createPublicGroup(String, String, CreateGroupCallback)},
     * 群基本信息定义见{@link GroupBasicInfo}
     *
     * @param appKey   指定应用的appKey
     * @param start    起始位置
     * @param count    获取个数
     * @param callback 接口回调
     * @since 2.4.1
     */
    JMessageClient.getPublicGroupListByApp(String appKey, int start, int count, RequestCallback<List<GroupBasicInfo>> callback);

Public group related example code

//创建公开群组
JMessageClient.createPublicGroup(name, desc, callback);
JMessageClient.createPublicGroup(name, desc, avatarFile, format, callback);//包含群头像

//申请入群
JMessageClient.applyJoinGroup(Long.parseLong(mEt_groupID.getText().toString()), reason, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        mProgressDialog.dismiss();
        if (responseCode == 0) {
            Toast.makeText(ApplyJoinGroupActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
        } else {
            Log.d(TAG, "apply failed. code :" + responseCode + " msg : " + responseMessage);
            Toast.makeText(ApplyJoinGroupActivity.this, "申请失败", Toast.LENGTH_SHORT).show();
        }
    }
});

//入群审批
event.acceptGroupApproval(username, appKey, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        if (0 == responseCode) {
            Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Log.i(TAG, "acceptApplyJoinGroup failed,"+ " code = " + responseCode + ";msg = " + responseMessage);
            Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
        }
    }
}); //入群审批同意

event.refuseGroupApproval(username, appKey, reason, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        if (0 == responseCode) {
            Toast.makeText(getApplicationContext(), "拒绝成功", Toast.LENGTH_SHORT).show();
        } else {
            Log.i(TAG, "refuseApplyJoinGroup failed,"+ " code = " + responseCode + ";msg = " + responseMessage);
            Toast.makeText(getApplicationContext(), "拒绝失败", Toast.LENGTH_SHORT).show();
        }
    }
}); //入群审批拒绝

//获取指定应用下所有公开群组
JMessageClient.getPublicGroupListByApp(appkey, start, count, new RequestCallback<List<GroupBasicInfo>>() {
    @Override
    public void gotResult(int responseCode, String responseMessage, List<GroupBasicInfo> groupBasicInfos) {
        if (responseCode == 0) {
            String result = "";
            for (GroupBasicInfo groupBasicInfo : groupBasicInfos) {
                result += "GroupID: " + groupBasicInfo.getGroupID() + ", GroupType: " + groupBasicInfo.getGroupType() +
                        ", GroupName: " + groupBasicInfo.getGroupName() + ", GroupDescription: " + groupBasicInfo.getGroupDescription() +
                        ", GroupAvatarMediaID: " + groupBasicInfo.getAvatar() + ", GroupMaxMemberCount: " + groupBasicInfo.getMaxMemberCount()+ "\n\n";
            }
            tvDisplay.setText(result);
            tvDisplay.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
        } else {
            tvDisplay.setText("获取失败!\nresponseCode:" + responseCode + "\nresponseMsg" + responseMessage);
        }
    }
});

Group Members Banned

Since 2.4.0
The 2.4.0 version added a group member banned status setting. After the banning, the user can normally receive the message but cannot send a message to the banned group. After the ban is lifted, the message can be normally sent.

Group member banned state setting

Since 2.4.0

    /**
     * 群成员禁言状态设置,禁言后用户可正常接收消息,但无法向被禁言的群组中发送消息
     * 解禁后可正常发送消息,禁言状态设置成功后群内所有成员将会收到群禁言通知事件
     * sdk收到群禁言通知事件后会以类型为{@link cn.jpush.im.android.api.enums.ContentType#eventNotification}
     * 的消息事件方式上报
     *
     * @param username 待设置群成员的username
     * @param appKey 待设置群成员的appKey,传入空则默认使用本应用appKey
     * @param keepSilence //true 设置禁言, false 取消禁言
     * @param callback
     * @since 2.4.0
     */
    groupInfo.setGroupMemSilence(String username, String appKey, boolean keepSilence, BasicCallback callback);

Get a list of banned

Since 2.4.0

    /**
     * 获取群成员禁言列表,返回群内被禁言的成员信息列表
     *
     * @return List<UserInfo>
     * @since 2.4.0
     */
    groupInfo.getGroupSilenceMembers();

Determine whether the user is banned

Since 2.4.0

    /**
     * 判断用户在该群内是否被禁言,若被禁言返回true,否则返回false
     *
     * @param username 待判断用户的用户名
     * @param appKey 待判断用户的appKey,若传入空则默认使用本应用appKey
     * @return boolean
     * @since 2.4.0
     */
    groupInfo.isKeepSilence(String username, String appKey);

Relevant example code of group members banned

//设置群成员禁言状态
JMessageClient.getGroupInfo(mGroupID, new GetGroupInfoCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo) {
        if (0 == responseCode) {
            groupInfo.setGroupMemSilence(mNames, mAppKey, keepSilence, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    mProgressDialog.dismiss();
                    if (0 == i) {
                        Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言成功" : "取消禁言成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言失败" : "取消禁言失败", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "GroupInfo.setGroupMemSilence " + ", responseCode = " + i + " ; Desc = " + s);
                    }
                }
            });
        } else {
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言失败" : "取消禁言失败", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "getGroupInfo failed " + ", responseCode = " + responseCode + " :Desc = " + responseMessage);
        }
    }
});

//获取群成员禁言列表
JMessageClient.getGroupInfo(mGetId, new GetGroupInfoCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo) {
        mProgressDialog.dismiss();
        if (responseCode == 0) {
            List<UserInfo> silenceMembers = groupInfo.getGroupSilenceMembers();
            StringBuilder sb = new StringBuilder();
            for (UserInfo info : silenceMembers) {
                sb.append(info.getUserName());
                sb.append("\n");
            }
            mTv_showGroupInfo.append("群成员禁言信息列表(这里获取name,需要其他信息请自行获取):\n" + sb.toString());
            Toast.makeText(getApplicationContext(), "获取成功", Toast.LENGTH_SHORT).show();
        } else {
            Log.i("GetGroupInfoActivity", "groupInfo.getGroupMembers" + ", responseCode = " + responseCode + " ; Desc = " + responseMessage);
            Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
        }
    }
});

//判断用户是否被禁言
JMessageClient.getGroupInfo(mGetId, new GetGroupInfoCallback() {
    @Override
    public void gotResult(int i, String s, GroupInfo groupInfo) {
        if (i == 0) {
            mProgressDialog.dismiss();
            Toast.makeText(getApplicationContext(), groupInfo.isKeepSilence(name, appKey) ? "已被禁言" : "没有被禁言或者用户不存在或不在指定群", Toast.LENGTH_SHORT).show();
        } else {
            mProgressDialog.dismiss();
            Log.i("GetGroupInfoActivity", "groupInfo.getGroupMemberSilenceStatus" + ", responseCode = " + i + " ; Desc = " + s);
            Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
        }
    }
});

Group Administrator

Since 2.5.0
Version 2.5.0 added group administrators. Administrators can remove or block common group members, as well as directly add group members and approve application for joining the group in the public group. The owner has the right to add, cancel, remove or ban administrators

Add the administrator

Since 2.5.0

    /**
     * 添加群管理员
     *
     * @param userInfos 群成员UserInfo列表
     * @param callback 回调
     * @since 2.5.0
     */
    groupInfo.addGroupKeeper(List<UserInfo> userInfos, BasicCallback callback);

Cancel the administrator

Since 2.5.0

    /**
     * 取消群管理员,管理员角色描述详见官方文档<a href="https://docs.jiguang.cn/jmessage/client/im_sdk_android/">群组管理员<a/>
     *
     * @param userInfos 群成员UserInfo列表
     * @param callback 回调
     * @since 2.5.0
     */
    groupInfo.removeGroupKeeper(List<UserInfo> userInfos, BasicCallback callback);

Get the list of administrators

Since 2.5.0

    /**
     * 获取群管理员列表, 返回群内管理员的成员信息列表,管理员角色描述详见官方文档<a href="https://docs.jiguang.cn/jmessage/client/im_sdk_android/">群组管理员<a/>
     *
     * @return 管理员的成员信息列表
     * @since 2.5.0
     */
    groupInfo.getGroupKeepers();

Example Code

//添加管理员
groupInfo.addGroupKeeper(userInfos, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        if (responseCode == 0) {
            Toast.makeText(getApplicationContext(), "添加管理员成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "添加管理员失败", Toast.LENGTH_SHORT).show();
            mTvGroupKeeper.setText("responseCode:" + responseCode + "\nresponseMessage:" + responseMessage);
        }
    }
});

//取消管理员
groupInfo.removeGroupKeeper(userInfos, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        if (responseCode == 0) {
            Toast.makeText(getApplicationContext(), "取消管理员成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "取消管理员失败", Toast.LENGTH_SHORT).show();
            mTvGroupKeeper.setText("responseCode:" + responseCode + "\nresponseMessage:" + responseMessage);
        }
    }
});

//获取管理员列表
List<UserInfo> userInfos = groupInfo.getGroupKeepers();
String result = "这里只展示username:";
for (UserInfo userInfo : userInfos) {
    if (userInfo != null) {
        result += "\n" + userInfo.getUserName();
    }
}
mTvGroupKeeper.setText(result);

Blacklist Management

You can add the other user to the "blacklist" list. After joining, we can still send a message to each other. However, it will return the specified error code when the other party sends a message to me, and the message will fail.

Add users to the blacklist

JMessageClient.addUsersToBlacklist(List<String> usernames, BasicCallback callback)

Parameter Description

  • List usernames - usernames list of users added to the blacklist
  • BasicCallback callback - callback interface

Remove users from the blacklist

JMessageClient.delUsersFromBlacklist(List<String> usernames, BasicCallback callback)

Parameter Description

  • List usernames - Username list of users that have been removed from the blacklist
  • BasicCallback callback - callback interface

Get a list of users who have been blacklisted by the current user

JMessageClient.getBlacklist(GetBlacklistCallback callback)

Parameter Description

  • GetBlacklistCallback - get callback interface of blacklist

Callback

  public abstract void gotResult(int responseCode,
    String responseMessage, List<UserInfo> userInfos);
  • List - UserInfos of users who are blacklisted

Notification Bar Management

Set display type of notification
JMessageClient.setNotificationFlag(int flag);

Parameter Description

Get display type of notification bar

Since 2.2.0

JMessageClient.getNotificationFlag();

return

  • int - display type of the currently set notification bar.

Enter a single chat session

Enter a single chat session. The default entry is the user's session under the appKey. The UI needs to call this function when entering the single chat session page, and then the SDK will decide whether to send a notification based on the username passed in

JMessageClient.enterSingleConversation(String username)

Parameter Definition

  • String username – username of single chat chat

Enter a single chat session (cross-application)

Call when entering the chat session interface and set the currently chatting object. And sdk is used to determine if the notification needs to be displayed. If appKey is empty, the application's appKey is filled by default. The UI needs to call this function when entering the single chat session page, and the SDK will decide whether to send a notification based on the username passed in.

JMessageClient.enterSingleConversation(String username,String appKey)

Parameter Definition

  • String username - username of single chat object
  • String appKey - appKey belongs to the chat object

Enter a group chat session

Enter group chat session. The UI needs to call this function when entering the group chat session page, and then the SDK will decide whether to send a notification based on the groupID passed in .

JMessageClient.enterGroupConversation(long groupID)

Parameter Definition

  • long groupID - Group ID of group chat

Exit the session.

Exit the session. The UI needs to call this function when exiting the session page.

JMessageClient.exitConversation();

Monitor the notification bar click event

The user can customize the jump by clicking the notification event NotificationClickEvent in the notification bar. If there is no recipient in the event, the SDK will default to the main interface of the program when the notification bar is clicked.

Event receiving method is shown in event handling section

Buddy List Management

The jmessage sdk buddy module only implements the hosting of the user's buddy relationship and the sending and receiving of related buddy requests. In addition to any of the features built on top of friends (such as being limited to chats between friends, etc.), developers need to implement in their own application layer.

Send request for adding friends

Send friend adding request. In the absence of a response from the other party, it is fine to send the request repeatedly. After the request is sent, the other party will receive a ContactNotifyEvent event of friend request.

public static void sendInvitationRequest(final String targetUsername,String appKey, final String reason, final BasicCallback callback)

Parameter Definition

  • String targetUsername – username of invitee
  • String appKey - the appKey of the invitee user. If it is empty, the user will be searched by default under this appKey.
  • String reason - reason for application
  • BasicCallback callback - result callback

Example Code

ContactManager.sendInvitationRequest("test_user", "test_appkey", "hello", new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //好友请求请求发送成功
                } else {
                    //好友请求发送失败
                }
            }
        });

Accept friend requests

Accept the friend request. After that, the other party will appear in their own friend list and the two parties establish a friend relationship. The other party will receive a ContactNotifyEvent event of friend request accepted.

ContactManager.acceptInvitation(final String targetUsername, String appKey, final BasicCallback callback)

Parameter Definition

  • String targetUsername - username of the inviting party
  • String appKey - the appKey of the inviting user. If it is empty, the user will be searched by default under the appKey.
  • BasicCallback callback - result callback

Example Code

ContactManager.acceptInvitation("test_user", "test_appkey", new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //接收好友请求成功
                } else {
                    //接收好友请求失败
                }
            }
        });

Reject friend request

Reject the friend request. After the request is sent, the other party will receive a ContactNotifyEvent event of friend request rejected.

ContactManager.declineInvitation(final String targetUsername, String appKey, String reason, final BasicCallback callback)

Parameter Definition

  • String targetUsername – username of inviting party
  • String appKey - the appKey of the inviting user. If it is empty, the user will be searched by default under this appKey.
  • String reason - reason to reject
  • BasicCallback callback - result callback

Example Code:

ContactManager.declineInvitation("test_user", "test_appkey", "sorry~", new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //拒绝好友请求成功
                } else {
                    //拒绝好友请求失败
                }
            }
        });

Get buddy list

Get the buddy list of currently logged-in user and return the result asynchronously.

ContactManager.getFriendList(final GetUserInfoListCallback callback)

Parameter Definition

  • GetUserInfoListCallback callback - result callback.

Example Code

ContactManager.getFriendList(new GetUserInfoListCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, List<UserInfo> userInfoList) {
                if (0 == responseCode) {
                    //获取好友列表成功
                } else {
                    //获取好友列表失败
                }
            }
        });

Delete friend

Remove the user from your buddy list. After the removal is successful, the other party will receive a ContactNotifyEvent event to notifying the buddy removed

userinfo.removeFromFriendList(BasicCallback callback)

Parameter Definition

  • BasicCallback callback - result callback

Example Code

userinfo.removeFromFriendList(new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //移出好友列表成功
                } else {
                    //移出好友列表失败
                }
            }
        });

Update user note name/note text

Update user note name and note text only if they exist in your friends list

userinfo.updateNoteName(String noteName, BasicCallback callback)

userinfo.updateNoteText(String noteText, BasicCallback callback)

Parameter Definition

  • String noteName - new note name
  • String noteText - new note text
  • BasicCallback callback - result callback

Example Code

userinfo.updateNoteName("new_note_name", new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage) {
                if (0 == responseCode) {
                    //更新备注名成功
                } else {
                    //更新备注名失败
                }
            }
        });

ContactNotifyEvent

Add ContactNotifyEvent, specific event handling method is shown in event handling section

Method Type Instruction
getType() ContactNotifyEvent.Type Get the specific types of contact notification events. For details, see definition of [Type](./im_android_api_docs/cn/jpush/im/android/api/event/ContactNotifyEvent.html).
getReason() String Get the reason for the occurrence of the event. This field is filled in by the other party when it initiates the request. If the other party does not fill it, it will return the default string.
getFromUsername() String Get the sender's username
getFromUserAppKey() String Get the appKey of the app to which the event sender belongs

Example Code:

class ContactNotifyEventReceiver extends Activity{

  @Override
  protected void onCreate() {
    super.onCreate(savedInstanceState);
    JMessageClient.registerEventReceiver(this);
  }

  @Override
  protected void onDestroy() {
    JMessageClient.unRegisterEventReceiver(this);
    super.onDestroy();
  }

  public void onEvent(ContactNotifyEvent event) {
        String reason = event.getReason();
        String fromUsername = event.getFromUsername();
        String appkey = event.getfromUserAppKey();

        switch (event.getType()) {
            case invite_received://收到好友邀请
                //...
                break;
            case invite_accepted://对方接收了你的好友邀请
                //...
                break;
            case invite_declined://对方拒绝了你的好友邀请
                //...
                break;
            case contact_deleted://对方将你从好友中删除
                //...
                break;
            default:
                break;
        }
    }

}

Chatroom Management

Since 2.4.0
The biggest difference between chat rooms and groups is that the messages in the chat rooms have no push notifications or be saved offline, and there is no concept of permanent members. Just enter the chat room, you can receive messages and start chatting. However, once you exit the chat room, any messages, notifications, and reminders will not be received any longer.

Note: The latest 50 messages will be obtained automatically after entering the chat room. The client does not support the creation of chat rooms currently.

Chat Room Information

Since 2.4.0
Add chat room information ChatRoomInfo

Method Type Instruction
getRoomID() `long` Get chat room id
getName() `String` Get chat room name
getAppKey() `String` Get the AppKey of the chat room
getOwnerInfo() `UserInfo` Get UserInfo of chat room owner
getMaxMemberCount() `int` Get the maximum number of members allowed in a chat room
getDescription() `String` Get chat room description
getTotalMemberCount() `int` Get the current number of members in the chat room
getCreateTime() `int` Get creation time of chat room, unit – second

Get the current chat room information under appkey

Since 2.4.0

    /**
     * 获取当前应用appkey所属下聊天室信息。
     *
     * @param start    起始位置
     * @param count    获取个数
     * @param callback 接口回调
     * @since 2.4.0
     */
    ChatRoomManager.getChatRoomListByApp(int start, int count, RequestCallback<List<ChatRoomInfo>> callback);

Get information of all chat rooms that the current user joins

Since 2.4.0

    /**
     * 获取当前用户所加入的所有聊天室的信息。
     *
     * @param callback 接口回调
     * @since 2.4.0
     */
    ChatRoomManager.getChatRoomListByUser(RequestCallback<List<ChatRoomInfo>> callback);

Query chat room information of a specified roomID

Since 2.4.0

    /**
     * 查询指定roomID的聊天室信息。
     *
     * @param roomIDs  待查询的roomID集合
     * @param callback 接口回调
     * @since 2.4.0
     */
    ChatRoomManager.getChatRoomInfos(Set<Long> roomIDs, final RequestCallback<List<ChatRoomInfo>> callback);

Enter the chat room

Since 2.4.0

    /**
     * 进入聊天室.
     * 用户只有成功调用此接口之后,才能收到聊天室消息,以及在此聊天室中发言。
     * 成功进入聊天室之后,会将聊天室中最近若干条聊天记录同步到本地并以{@link cn.jpush.im.android.api.event.ChatRoomMessageEvent}事件的形式通知到上层。
     *
     * @param roomID   聊天室的roomID
     * @param callback 接口回调
     * @since 2.4.0
     */
    ChatRoomManager.enterChatRoom(long roomID, final RequestCallback<Conversation> callback);

Leave the chat room

Since 2.4.0

    /**
     * 离开聊天室.
     * 成功调用此接口之后,用户将能不在此聊天室收发消息。
     *
     * @param roomID   聊天室的roomID
     * @param callback 接口回调
     * @since 2.4.0
     */
    ChatRoomManager.leaveChatRoom(long roomID, final BasicCallback callback);

Get chat session information

Since 2.4.0

    /**
     * 获取聊天室会话信息
     *
     * @param roomID 群组的groupID
     * @return 返回会话信息,若不存在和指定对象的会话则返回null
     * @since 2.4.0
     */
    JMessageClient.getChatRoomConversation(long roomID);

Get the user's chat room conversation list locally

Since 2.4.0

    /**
     * 从本地数据库中获取包含所有的聊天室会话的列表
     *
     * @return 返回当前用户的聊天室会话列表,没有则返回空的列表
     * @since 2.4.0
     */
    JMessageClient.getChatRoomConversationList();

Delete chat room conversation

Since 2.4.0

    /**
     * 删除聊天室会话,同时删除掉本地相关缓存文件
     *
     * @param roomID 聊天室roomID
     * @return 删除成功返回true, 否则返回false
     * @since 2.4.0
     */
    JMessageClient.deleteChatRoomConversation(long roomID);

Create a chat room session

Since 2.4.0

    /**
     * 创建聊天室会话,如果本地已存在对应会话,则不会重新创建,直接返回本地会话对象。
     *
     * @param roomID 聊天室的roomID
     * @return 会话对象
     * @since 2.4.0
     */
    Conversation.createChatRoomConversation(long roomID);

Chat room message events

Since 2.4.0

ChatRoomMessageEvent

After the user enters the chat room and receives the chat room message, sdk will automatically throw this event notification to the upper layer. The specific processing method is shown in the event handling section.

Chat room related example code

// 获取当前应用appkey所属下聊天室信息
ChatRoomManager.getChatRoomListByApp(start, count, new RequestCallback<List<ChatRoomInfo>>() {
    @Override
    public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
        String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
        postTextToDisplay("getChatRoomListByApp", responseCode, responseMessage, result);
    }
});

// 获取当前用户所加入的所有聊天室的信息
ChatRoomManager.getChatRoomListByUser(new RequestCallback<List<ChatRoomInfo>>() {
    @Override
    public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
        String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
        postTextToDisplay("getChatRoomListByUser", responseCode, responseMessage, result);
    }
});

// 查询指定roomID的聊天室信息
ChatRoomManager.getChatRoomInfos(Collections.singleton(roomID), new RequestCallback<List<ChatRoomInfo>>() {
    @Override
    public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
        String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
        postTextToDisplay("getChatRoomInfos", responseCode, responseMessage, result);
    }
});

// 进入聊天室
ChatRoomManager.enterChatRoom(roomID, new RequestCallback<Conversation>() {
    @Override
    public void gotResult(int responseCode, String responseMessage, Conversation conversation) {
        String result = null != conversation ? conversation.toString() : null;
        postTextToDisplay("enterChatRoom", responseCode, responseMessage, result);
    }
});

// 离开聊天室
ChatRoomManager.leaveChatRoom(roomID, new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        postTextToDisplay("leaveChatRoom", responseCode, responseMessage, null);
    }
});

// 发送聊天室消息
Conversation conv = JMessageClient.getChatRoomConversation(roomID);
if (null == conv) {
    conv = Conversation.createChatRoomConversation(roomID);
}
String text = etInputText.getText().toString();
final Message msg = conv.createSendTextMessage(text);//实际聊天室可以支持所有类型的消息发送,demo为了简便,仅仅实现了文本类型的消息发送
msg.setOnSendCompleteCallback(new BasicCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage) {
        if (0 == responseCode) {
            postMessageToDisplay("MessageSent", responseCode, responseMessage, msg);
        } else {
            postTextToDisplay("MessageSent", responseCode, responseMessage, "消息发送失败");
        }
    }
});
JMessageClient.sendMessage(msg);

// 接收聊天室消息
public void onEventMainThread(ChatRoomMessageEvent event) {
    Log.d("tag", "ChatRoomMessageEvent received .");
    List<Message> msgs = event.getMessages();
    for (Message msg : msgs) {
        //这个页面仅仅展示聊天室会话的消息
        postMessageToDisplay("MessageReceived", event.getResponseCode(), event.getResponseDesc(), msg);
    }
}

Users/groups can be added to the Do-Not-Disturb (DND) list. When receiving DND messages from users/groups, sdk does not pop up the default notification prompt, but message events are delivered as usual.

Get Do-Not-Disturb list

JMessageClient.getNoDisturblist(GetNoDisurbListCallback callback)

Parameter Definition

  • GetNoDisurbListCallback callback - callback interface.

Set up normal Do-Not-Disturb

See UserInfo and GroupInfo related interfaces in api doc

Set Global Do-Not-Disturb

After setting global Do-Not-Disturb, all messages received will have no notification bar notification and the effect is similar
setNotificationMode(JMessageClient.NOTI_MODE_NO_NOTIFICATION),but this setting also takes effect after the user changes the device.

JMessageClient.setNoDisturbGlobal(int noDisturbGlobal, BasicCallback callback)

Parameter Definition

  • int noDisturbGlobal - int noDisturbGlobal Global Do-Not-Disturb Flag, 1 means setting, other means to cancel setting.
  • BasicCallback callback - callback interface

Get Global Do-Not-Disturb Identifier

JMessageClient.getNoDisturbGlobal(IntegerCallback callback)

Parameter Definition

  • IntegerCallback callback - callback interface.

Cross-application Communication

Instruction: Cross-application communication means that different applications under the same developer account can communicate with each other to meet the developer's need for application communication under different appKeys.
The JMessage Android SDK implements the single-chat and cross-application in the v1.2.0 version. The v1.3.0 version implements the cross-application of group chat and other functions. The specific correspondence relationship is shown in the following table.

Since Function Realized Instructions
v1.2.0 1.Get cross-app user information
2.Cross-app single chat
1.Obtain user information across applications
2.Send the user a single chat message across applications
v1.3.0 1.Cross-app group chat
2.Cross-app blacklist settings
3.Cross-app DND Settings
1.Allow users from different applications to join in the group to make cross-application group chat possible
2.Allow users to be added to the blacklist across applications to block messages from users under different applications
3. Add and remove Do-Not-Disturb across applications

: The key to achieving cross-application group chat is to include cross-application group members in the group, and the process of creating conversations and sending messages is the same as the implementation of common group chat.

The main difference between cross-application interfaces and non-cross-application interfaces is that appkey is added as a parameter in cross-application interfaces. For detailed interface description, please go to JMessage Android API Java docs

Conversation

Create a cross-application single chat session

createSingleConversation(String userName, String appKey)
JMessageClient

Get user information across applications

getUserInfo(String username,String appKey,GetUserInfoCallback callback)  

Add group members across applications

addGroupMembers(long groupID,String appKey,List<String> userNameList,BasicCallback callback)       

Kick out group members across applications

removeGroupMembers(long groupID,String appKey,List<String> userNameList,BasicCallback callback)

Add users into the blacklist across applications

addUsersToBlacklist(List<String> usernames,String appKey,BasicCallback callback)  

Remove users from blacklist across applications

delUsersFromBlacklist(List<String> usernames,String appKey,BasicCallback callback)  
GroupInfo

Get group member information

getGroupMemberInfo(String username, String appKey)  

Specific implementation of cross-application

Get user information across applications

Obtain cross-application user information by specifying appKey.

JMessageClient.getUserInfo(java.lang.String username,java.lang.String appKey,GetUserInfoCallback callback)

Parameter Definition

  • username - username registered by the developer
  • appKey - the specified appKey. If it is empty then the user can be found under this appKey
  • callback - callback interface for getting user information

Example Code

JMessageClient.getUserInfo("username", "appKey", new GetUserInfoCallback() {
     @Override
     public void gotResult(int responseCode, String responseMessage, UserInfo info) {
         // 获取到跨应用的用户信息
         ...
    }
});
Inter-application single chat

Specify the appKey to which the other user belongs when a single chat session is created, a single chat session with the cross-application user can be established.

Conversation.createSingleConversation(String targetUsername, String appKey)

Parameter Definition

  • targetUsername – username of the user
  • appKey - the specified appKey. If it is empty, then the default is appKey of this application.

After creating a cross-application session, just create a message to send. The following is an example of creating a single chat text message

Example Code

//创建跨应用会话
Conversation con = Conversation.createSingleConversation("username", "appKey");
MessageContent content = new TextContent("hello");
//创建一条消息 
Message message = con.createSendMessage(content);
//发送消息 
JMessageClient.sendMessage(message);
Cross-application group chat

The key to achieving cross-application group chat is to include cross-application group members in the group, and the process of creating conversations and sending messages is the same as the common group chat implementation.

Listed below are the interfaces related to group members of cross-application operating.

1.Add group members across applications

JMessageClient.addGroupMembers(long groupID,String appKey,List<String> userNameList,BasicCallback callback);

Parameter

  • groupID - groupID of the group
  • appKey - The appKey to which the user belongs in the usernameList. If it is empty, the user is found under the appKey.
  • userNameList - the set of member usernames added to the group
  • callback - callback interface

2.Kick out group members across applications

JMessageClient.removeGroupMembers(long groupID,String appKey,List<String> userNameList,BasicCallback callback);

Parameter

  • groupID - groupID of the group
  • appKey - the appKey to which the user belongs in usernameList. If appKey is empty, the user is found under the appKey.
  • userNameList - username set of group members who are kicked out
  • callback - callback interface

3.Get group member information

//此接口是实例对象上的接口
groupInfo.getGroupMemberInfo(String username, String appKey)

Parameter

  • username - username of specified group member
  • appKey - the appKey to which the group member belongs

The following is an example of adding a cross-app group member to an existing group and then creating a session to send a message:

Example Code

//添加跨应用用户到群组
JMessageClient.addGroupMembers(testGid, "appKey", userNameList, new BasicCallback() {
     @Override
     public void gotResult(int responseCode, String responseMessage) {
         //添加跨应用群成员成功之后,创建会话,发送消息。 
         if(0 == responseCode){
             Conversation conversation = Conversation.createGroupConversation(testGid);
             Message msg = conversation.createSendTextMessage("hello");
             JMessageClient.sendMessage(msg);
         }
     }
});
Add a blacklist across applications

You can add cross-application users to the blacklist by specifying the appKey when operating the blacklist through the following interfaces.

1.Add user into the blacklist

JMessageClient.addUsersToBlacklist(List<String> usernames,String appKey,BasicCallback callback);

Parameter

  • usernames - usernames added to the blacklist
  • appKey - the appKey to which the user belongs in usernameList. If appKey is empty, the user is found under appKey.
  • callback - callback interface

2.Remove the user from the blacklist

JMessageClient.delUsersFromBlacklist(List<String> usernames,String appKey,BasicCallback callback)

Parameter

  • usernames - set of usernames removed from the blacklist
  • appKey - the appKey to which the user belongs in usernameList. If appKey is empty, the user is found under appKey.
  • callback - callback interface

Example Code

//跨应用添加用户至黑名单
JMessageClient.addUsersToBlacklist(usernames, "appKey",new BasicCallback() {
     @Override
     public void gotResult(int responseCode, String responseMessage) {
         if (0 == responseCode){
             //成功跨应用添加用户至黑名单
             ... 
         } 
     }
}); 
Inter-application do-not-disturb implementation

The original interface does not need to change. The do-not-disturb related interface is an instance interface on the userinfo object. That is, as long as the acquired user is a cross-application user, a cross-application can be realized by directly calling the do-not-disturb interface of the userinfo object.

userinfo.setNoDisturb(int noDisturb,BasicCallback callback)

Parameter

  • noDisturb - 1 - Do-Not-Disturb, Other – Non Do-Not-Disturb (set the parameter to 1 when setting Do-Not-Disturb, and set to 0 if Do-Not-Disturb is cancelled)
  • Callback - callback interface

Example Code

//跨应用获取用户信息
JMessageClient.getUserInfo("username", "appKey", new GetUserInfoCallback() {
    @Override
    public void gotResult(int responseCode, String responseMessage, UserInfo info) {
        //跨应用获取用户信息成功,设置用户的免打扰属性 
        if(0 == responseCode){
            info.setNoDisturb(1,null);
        }
    }
});

Class Definition

Conversation and messages

cn.jpush.im.android.api.model.Conversation

public File getAvatar();
public String getDisplayName();
public Message getLatestMessage();
public List<Message> getAllMessage();
public List<Message> getNewMessagesFromNewest(int offset, int limit);

public Message createSendMessage(MessageContent content);
public Message createSendTextMessage(String text);
public Message createSendImageMessage(File imageFile)
    throws FileNotFoundException
public Message createSendVoiceMessage(File voiceFile, int duration)
    throws FileNotFoundException
public Message createSendCustomMessage(Map<? extends String, ?> valuesMap)
public boolean resetUnreadCount();

cn.jpush.im.android.api.model.Message

public String getFromID()
public MessageContent getContent()
public ContentType getContentType()
public MessageStatus getStatus()
public String getTargetID()
public long getCreateTime()

public void setOnContentUploadProgressCallback(ProgressUpdateCallback callback)
public void setOnContentDownloadProgressCallback(ProgressUpdateCallback callback)
public void setOnSendCompleteCallback(BasicCallback sendCompleteCallback)

Example

Conversation conv = JMessageClient.getSingleConversation("tom");
if (null == conv) {
  conv = Conversation.createSingleConversation("tom");
}
TextContent text = new TextContent("Hi, JMessage!");
Message message = conv.createSendMessage(text);

JMessageClient.sendMessage(message);
Chat content

Parent class of chat content

cn.jpush.im.api.content.MessageContent

Chat content types supported currently

cn.jpush.im.api.content.TextContent
cn.jpush.im.api.content.VoiceContent
cn.jpush.im.api.content.ImageContent
cn.jpush.im.api.content.LocationContent
cn.jpush.im.api.content.FileContent
cn.jpush.im.api.content.CustomContent

Example

// 参数:文本内容
TextContent text = new TextContent("Hi, JMessage");

// 参数:语音文件对象,语音文件时长
VoiceContent voice = new VoiceContent(new File("/sdcard/voice.amr"), 21);

// 参数:图片文件对象
ImageContent image = new ImageContent(new File("/sdcard/image.png"));

// 参数:任意文件对象
FileContent fileContent = new FileContent(new File("/sdcard/file.xxx"));

// 参数:经度,纬度,缩放比例,地址详情
LocationContent locationContent = new LocationContent(111.1,222.2,500,"xx省xx市xx区xx街xx号");

Callback definition

BasicCallback
public abstract class BasicCallback {

    private boolean isRunInUIThread = true;

    /**
     * Default is running in UI thread.
     */
    public BasicCallback() {
    }

    /**
     * 默认callback会在主线程中回调,如果需要在子线程回调,则在构造方法的参数中传入false
     * @param isRunInUIThread 是否在主线程中执行回调,默认为true。
     */
    public BasicCallback(boolean isRunInUIThread) {
        this.isRunInUIThread = isRunInUIThread;
    }

    public boolean isRunInUIThread() {
        return this.isRunInUIThread;
    }

    /**
     * 异步调用返回结果。
     *
     * @param responseCode 0 表示正常。大于 0 表示异常,responseMessage 会有进一步的异常信息。
     * @param responseMessage 一般异常时会有进一步的信息提示。
     */
    public abstract void gotResult(int responseCode, String responseMessage);

}

Error Code Definition

Reference Document: List of IM Android SDK Error Codes


Copyright 2011-2020, jiguang.cn, All Rights Reserved.
粤ICP备12056275号-13 深圳市和讯华谷信息技术有限公司

Documentation built with MkDocs.