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.

  1. 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
  1. 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

  1. JMessageClient.register(String username, String password, BasicCallback callback);
  2. /**
  3. * 注册同时指定用户信息中的其他字段
  4. * @since 2.3.0
  5. */
  6. 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

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

Parameter Description

  • String username
  • String password
  • BasicCallback callback

Logout

  1. JMessageClient.logout();

Record of logging in

Since 2.5.0

Get login history of device when you log in

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

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

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

Parameter Description

  • String username
  • GetUserInfoCallback

Callback

  1. 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.

  1. 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

  1. JMessageClient.getMyInfo();

Parameter Description

  • N/A

Return

  • UserInfo

Update user information

  1. 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

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

Parameter Description

  • String oldPassword
  • String newPassword
  • BasicCallback

Update user avatar

  1. 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.

  1. 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.

  1. 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

  1. 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.

  1. 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

  1. 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.

  1. 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

  1. 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

  1. conversation.getUnReadMsgCnt();

return

  • Int:number of unread messages for the current session

Reset the number of unread messages for a single session

  1. conversation.resetUnreadCount();

return

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

Set the number of unread messages manually

  1. 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

  1. JMessageClient.getAllUnReadMsgCount();

return

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

Message Management

Create a text message

  1. /**
  2. * 创建一条单聊文本消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param username 聊天对象用户名
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param text 文本内容
  9. * @return 消息对象
  10. */
  11. JMessageClient.createSingleTextMessage(String username, String appKey, String text)
  12. /**
  13. * 创建一条群聊文本信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  14. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  15. * 接口来创建消息
  16. *
  17. * @param groupID 群组的groupID
  18. * @param text 文本内容
  19. * @return 消息对象
  20. */
  21. JMessageClient.createGroupTextMessage(long groupID, String text)

Create a picture message

  1. /**
  2. * 创建一条单聊图片信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param username 聊天对象的用户名
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param imageFile 图片文件
  9. * @return 消息对象
  10. * @throws FileNotFoundException
  11. */
  12. JMessageClient.createSingleImageMessage(String username, String appKey, File imageFile) throws FileNotFoundException
  13. /**
  14. * 创建一条群聊图片信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  15. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  16. * 接口来创建消息
  17. *
  18. * @param groupID 群组的groupID
  19. * @param imageFile 图片文件
  20. * @return 消息对象
  21. * @throws FileNotFoundException
  22. */
  23. JMessageClient.createGroupImageMessage(long groupID, File imageFile) throws FileNotFoundException

Create a voice message

  1. /**
  2. * 创建一条单聊语音信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param username 聊天对象的用户名
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param voiceFile 语音文件
  9. * @param duration 语音文件时长
  10. * @return 消息对象
  11. * @throws FileNotFoundException
  12. */
  13. JMessageClient.createSingleVoiceMessage(String username, String appKey, File voiceFile, int duration) throws FileNotFoundException
  14. /**
  15. * 创建一条群聊语音信息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  16. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  17. * 接口来创建消息
  18. *
  19. * @param groupID 群组groupID
  20. * @param voiceFile 语音文件
  21. * @param duration 语音文件时长
  22. * @return 消息对象
  23. * @throws FileNotFoundException
  24. */
  25. JMessageClient.createGroupVoiceMessage(long groupID, File voiceFile, int duration) throws FileNotFoundException

Create a location message

  1. /**
  2. * 创建一条单聊地理位置消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param username 聊天对象的用户名
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param latitude 纬度信息
  9. * @param longitude 经度信息
  10. * @param scale 地图缩放比例
  11. * @param address 详细地址信息
  12. * @return 消息对象
  13. */
  14. JMessageClient.createSingleLocationMessage(String username, String appKey, double latitude, double longitude, int scale, String address)
  15. /**
  16. * 创建一条群聊地理位置消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  17. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  18. * 接口来创建消息
  19. *
  20. * @param groupId 群组groupID
  21. * @param latitude 纬度信息
  22. * @param longitude 经度信息
  23. * @param scale 地图缩放比例
  24. * @param address 详细地址信息
  25. * @return 消息对象
  26. */
  27. JMessageClient.createGroupLocationMessage(long groupId, double latitude, double longitude, int scale, String address)

Create a file message

  1. /**
  2. * 创建一条单聊file消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param userName 聊天对象的用户名
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param file 发送的文件
  9. * @param fileName 指定发送的文件名称,如果不填或为空,则默认使用文件原名。
  10. * @return 消息对象
  11. * @throws FileNotFoundException
  12. */
  13. JMessageClient.createSingleFileMessage(String userName, String appKey, File file, String fileName) throws FileNotFoundException, JMFileSizeExceedException
  14. /**
  15. * 创建一条群聊file消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  16. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  17. * 接口来创建消息
  18. *
  19. * @param groupID 群组groupID
  20. * @param file 发送的文件
  21. * @param fileName 指定发送的文件名称,如果不填或为空,则默认使用文件原名。
  22. * @return 消息对象
  23. * @throws FileNotFoundException
  24. */
  25. JMessageClient.createGroupFileMessage(long groupID, File file, String fileName) throws FileNotFoundException, JMFileSizeExceedException

Create a custom message

  1. /**
  2. * 创建一条单聊自定义消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param username 聊天对象username
  7. * @param appKey 聊天对象所属应用的appKey
  8. * @param valuesMap 包含自定义键值对的map.
  9. * @return 消息对象
  10. */
  11. JMessageClient.createSingleCustomMessage(String username, String appKey, Map<? extends String, ? extends String> valuesMap)
  12. /**
  13. * 创建一条群聊自定义消息
  14. *
  15. * @param groupID 群组groupID
  16. * @param valuesMap 包含了自定义键值对的map
  17. * @return 消息对象
  18. */
  19. JMessageClient.createGroupCustomMessage(long groupID,
  20. Map<? extends String, ?> valuesMap)

Create a video message

  1. /**
  2. * 创建一条单聊video消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  3. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  4. * 接口来创建消息
  5. *
  6. * @param userName 聊天对象用户名
  7. * @param appKey 聊天对象所属应用appkey
  8. * @param thumbImage 视频缩略图,可不填。
  9. * @param thumbFormat 视频缩略图格式名
  10. * @param videoFile 视频文件对象
  11. * @param videoFileName 视频文件名称,如果不填或为空,则默认使用文件原名
  12. * @param duration 视频时长
  13. * @return 消息对象
  14. * @throws IOException
  15. * @since 2.6.0
  16. */
  17. JMessageClient.createSingleVideoMessage(String userName, String appKey, Bitmap thumbImage, String thumbFormat, File videoFile, String videoFileName, int duration) throws IOException
  18. /**
  19. * 创建一条群聊video消息,此方法是创建message的快捷接口,对于不需要关注会话实例的开发者可以使用此方法
  20. * 快捷的创建一条消息。其他的情况下推荐使用{@link Conversation#createSendMessage(MessageContent)}
  21. * 接口来创建消息
  22. *
  23. * @param groupID 群组groupID
  24. * @param thumbImage 视频缩略图,可不填。
  25. * @param thumbFormat 视频缩略图格式名
  26. * @param videoFile 视频文件对象
  27. * @param videoFileName 视频文件名称,如果不填或为空,则默认使用文件原名
  28. * @param duration 视频时长
  29. * @return 消息对象
  30. * @throws IOException
  31. * @since 2.6.0
  32. */
  33. 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.

  1. 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

  1. 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.

  1. JMessageClient.sendMessage(Message message, MessageSendingOptions options);

Parameter Description

  • Message message - message object
  • MessageSendingOptions - control options when sending messages
Example Code
  1. Message message = mConversation.createSendMessage(new TextContent(“Hello jmessage.”));
  2. message.setOnSendCompleteCallback(new BasicCallback() {
  3. @Override
  4. public void gotResult(int responseCode, String responseDesc) {
  5. if (responseCode == 0) {
  6. //消息发送成功
  7. } else {
  8. //消息发送失败
  9. }
  10. }
  11. });
  12. MessageSendingOptions options = new MessageSendingOptions();
  13. options.setRetainOffline(false);
  14. JMessageClient.sendMessage(message);//使用默认控制参数发送消息
  15. //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

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

Get the message list by condition

  1. /**
  2. * 会话中消息按时间降序排列,从其中的offset位置,获取limit条数的消息.
  3. *
  4. * @param offset 获取消息的起始位置
  5. * @param limit 获取消息的条数
  6. * @return 符合查询条件的消息List, 如果查询失败则返回空的List。
  7. */
  8. conversation.getMessagesFromNewest(int offset, int limit)
  9. /**
  10. * 会话中消息按时间升序排列,从其中的offset位置,获取limit条数的消息.<br/>
  11. *
  12. * @param offset 获取消息的起始位置
  13. * @param limit 获取消息的条数
  14. * @return 符合查询条件的消息List, 如果查询失败则返回空的List。
  15. */
  16. 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:

  1. /**
  2. 类似MessageEvent事件的接收,上层在需要的地方增加OfflineMessageEvent事件的接收
  3. 即可实现离线消息的接收。
  4. **/
  5. public void onEvent(OfflineMessageEvent event) {
  6. //获取事件发生的会话对象
  7. Conversation conversation = event.getConversation();
  8. List<Message> newMessageList = event.getOfflineMessageList();//获取此次离线期间会话收到的新消息列表
  9. System.out.println(String.format(Locale.SIMPLIFIED_CHINESE, "收到%d条来自%s的离线消息。\n", newMessageList.size(), conversation.getTargetId()));
  10. }
  11. /**
  12. 如果在JMessageClient.init时启用了消息漫游功能,则每当一个会话的漫游消息同步完成时
  13. sdk会发送此事件通知上层。
  14. **/
  15. public void onEvent(ConversationRefreshEvent event) {
  16. //获取事件发生的会话对象
  17. Conversation conversation = event.getConversation();
  18. //获取事件发生的原因,对于漫游完成触发的事件,此处的reason应该是
  19. //MSG_ROAMING_COMPLETE
  20. ConversationRefreshEvent.Reason reason = event.getReason();
  21. System.out.println(String.format(Locale.SIMPLIFIED_CHINESE, "收到ConversationRefreshEvent事件,待刷新的会话是%s.\n", conversation.getTargetId()));
  22. System.out.println("事件发生的原因 : " + reason);
  23. }

Retract Message

Retract a message in a conversation

Since 2.2.0
Initiated by the sender

  1. 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

  1. /**
  2. * 转发消息,只有发送成功或收到的消息才可转发
  3. *
  4. * @param message 需要转发的消息对象
  5. * @param conv 目标会话
  6. * @param options 消息转发时的控制选项,仅对此次发送生效, null则使用默认配置
  7. * @param callback 回调函数
  8. * @since 2.3.0
  9. * @deprecated deprecated since jmessage 2.6.0 use {@link JMessageClient#forwardMessage(Message, Conversation, MessageSendingOptions, RequestCallback)} instead.
  10. */
  11. JMessageClient.forwardMessage(Message message, Conversation conv, MessageSendingOptions options, BasicCallback callback);
  12. /**
  13. * 转发消息,注意只有发送成功或收到的消息才可转发,符合转发要求后会创建新的消息发送,
  14. * 创建的消息会在回调中返回(无论发送是否成功),如果不符合转发要求则不会创建新消息 message返回null。<br/>
  15. *
  16. * @param message 需要转发的消息对象
  17. * @param conv 目标会话
  18. * @param options 消息转发时的控制选项,仅对此次发送生效, null则使用默认配置
  19. * @param callback 回调函数
  20. * @since 2.6.0
  21. */
  22. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. message.haveRead()

Interface return

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

Message Receipt Status Change Event

  1. 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:

  1. //消息发送方:
  2. //===========发送带已读回执的消息:
  3. final Message message = mConversation.createSendMessage(new TextContent(“这是一条需要对方发送已读回执的消息.”));
  4. message.setOnSendCompleteCallback(new BasicCallback() {
  5. @Override
  6. public void gotResult(int responseCode, String responseDesc) {
  7. if (responseCode == 0) {
  8. //消息发送成功
  9. message.getUnreceiptCnt();//带回执的消息发送成功后,可以查看当前尚未发送已读回执的人数
  10. message.getReceiptDetails(...);//获取当前已读回执详情,具体包括已读和未读用户的UserInfo列表。callback中代码略
  11. } else {
  12. //消息发送失败
  13. }
  14. }
  15. });
  16. MessageSendingOptions options = new MessageSendingOptions();
  17. options.setNeedReadReceipt(true);//针对这条消息打开已读回执功能
  18. JMessageClient.sendMessage(message,options);//使用自定义的控制参数发送消息
  19. //===========
  20. //===========消息发送方监听回执状态变化:
  21. public void onEventMainThread(MessageReceiptStatusChangeEvent event) {
  22. Conversation conv = event.getConversation();
  23. tv_refreshEvent.append(String.format(Locale.SIMPLIFIED_CHINESE, "\n收到MessageReceiptStatusChangeEvent事件,会话对象是%s\n", conv.getTargetId()));
  24. for (MessageReceiptStatusChangeEvent.MessageReceiptMeta meta : event.getMessageReceiptMetas()) {
  25. tv_refreshEvent.append(String.format(Locale.SIMPLIFIED_CHINESE,
  26. "回执数有更新的消息serverMsgID:%d\n当前未发送已读回执的人数:%d", meta.getServerMsgId(), meta.getUnReceiptCnt()));
  27. }
  28. }
  29. //===========
  30. //消息接收方
  31. //===========将消息标记为已读
  32. if(!message.haveRead()){ //当消息的haveRead状态为false时,调用setHaveRead,将消息标记为已读
  33. msg.setHaveRead(new BasicCallback() {
  34. @Override
  35. public void gotResult(int responseCode, String responseMessage) {
  36. Toast.makeText(MessageReceiptActivity.this, "成功将消息标记为已读. responseCode = " + responseCode + " responseMessage =" + responseMessage, Toast.LENGTH_SHORT).show();
  37. }
  38. });
  39. }
  40. //===========

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

  1. /**
  2. * 发送消息透传给个人。
  3. * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
  4. * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
  5. * sdk不会将此类透传消息内容本地化。
  6. *
  7. * @param username 目标的用户名
  8. * @param appKey 目标的appKey, 如果传入null或空字符串,则默认用本应用的appKey
  9. * @param msg 发送的消息内容
  10. * @param callback 回调函数
  11. * @since 2.3.0
  12. */
  13. JMessageClient.sendSingleTransCommand(String username, appkey, String cmd, BasicCallback callback)
  14. /**
  15. * 发送消息透传给群。
  16. * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
  17. * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
  18. * sdk不会将此类透传消息内容本地化。
  19. *
  20. * @param gid 群组的gid
  21. * @param msg 发送的消息内容
  22. * @param callback 回调函数
  23. * @since 2.3.0
  24. */
  25. JMessageClient.sendGroupTransCommand(long gid, String msg, BasicCallback callback)
  26. /**
  27. * 发送透传消息给当前用户在其他平台已登录的设备。
  28. * 消息不会进入到后台的离线存储中去,仅当对方用户当前在线时,透传消息才会成功送达。
  29. * 透传命令送达时,接收方会收到一个{@link CommandNotificationEvent}事件通知。
  30. * sdk不会将此类透传消息内容本地化。
  31. *
  32. * @param platformType 平台类型,其中{@link PlatformType#all}表示发送给当前多端在线的其他所有设备(不包括本设备)。
  33. * @param msg 发送的消息内容
  34. * @param callback 回调函数
  35. * @since 2.5.0
  36. */
  37. JMessageClient.sendCrossDeviceTransCommand(PlatformType platformType, String msg, BasicCallback callback)

Event Handling

Register event receiving class

  1. JMessageClient.registerEventReceiver(Object receiver);
  2. 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

  1. 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
  1. public void onEvent(EventEntity event){
  2. //do your own business
  3. }

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
  1. public void onEventMainThread(EventEntity event){
  2. //do your own business
  3. }

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

  1. class MessageEventReceiver extends Activity{
  2. @Override
  3. protected void onCreate() {
  4. super.onCreate(savedInstanceState);
  5. //这里只是为了展示注册事件接受者接口的用法,实际上开发者可以在任意类中注册事件接收者
  6. //,而不仅仅在Activity中。 下同
  7. JMessageClient.registerEventReceiver(this);
  8. }
  9. @Override
  10. protected void onDestroy() {
  11. JMessageClient.unRegisterEventReceiver(this);
  12. super.onDestroy();
  13. }
  14. public void onEvent(MessageEvent event){
  15. Message msg = event.getMessage();
  16. switch (msg.getContentType()){
  17. case text:
  18. //处理文字消息
  19. TextContent textContent = (TextContent) msg.getContent();
  20. textContent.getText();
  21. break;
  22. case image:
  23. //处理图片消息
  24. ImageContent imageContent = (ImageContent) msg.getContent();
  25. imageContent.getLocalPath();//图片本地地址
  26. imageContent.getLocalThumbnailPath();//图片对应缩略图的本地地址
  27. break;
  28. case voice:
  29. //处理语音消息
  30. VoiceContent voiceContent = (VoiceContent) msg.getContent();
  31. voiceContent.getLocalPath();//语音文件本地地址
  32. voiceContent.getDuration();//语音文件时长
  33. break;
  34. case custom:
  35. //处理自定义消息
  36. CustomContent customContent = (CustomContent) msg.getContent();
  37. customContent.getNumberValue("custom_num"); //获取自定义的值
  38. customContent.getBooleanValue("custom_boolean");
  39. customContent.getStringValue("custom_string");
  40. break;
  41. case eventNotification:
  42. //处理事件提醒消息
  43. EventNotificationContent eventNotificationContent = (EventNotificationContent)msg.getContent();
  44. switch (eventNotificationContent.getEventNotificationType()){
  45. case group_member_added:
  46. //群成员加群事件
  47. break;
  48. case group_member_removed:
  49. //群成员被踢事件
  50. break;
  51. case group_member_exit:
  52. //群成员退群事件
  53. break;
  54. case group_info_updated://since 2.2.1
  55. //群信息变更事件
  56. break;
  57. }
  58. break;
  59. }
  60. }
  61. }

Receive notification bar click event

  1. class NotificationClickEvent extends Activity{
  2. @Override
  3. protected void onCreate() {
  4. super.onCreate(savedInstanceState);
  5. JMessageClient.registerEventReceiver(this);
  6. }
  7. @Override
  8. protected void onDestroy() {
  9. JMessageClient.unRegisterEventReceiver(this);
  10. super.onDestroy();
  11. }
  12. public void onEvent(NotificationClickEvent event){
  13. Intent notificationIntent = new Intent(mContext, ChatActivity.class);
  14. mContext.startActivity(notificationIntent);//自定义跳转到指定页面
  15. }
  16. }

User login status change event

  1. class UserLogoutEventReceiver extends Activity{
  2. @Override
  3. protected void onCreate() {
  4. super.onCreate(savedInstanceState);
  5. JMessageClient.registerEventReceiver(this);
  6. }
  7. @Override
  8. protected void onDestroy() {
  9. JMessageClient.unRegisterEventReceiver(this);
  10. super.onDestroy();``
  11. }
  12. public void onEvent(LoginStateChangeEvent event){
  13. LoginStateChangeEvent.Reason reason = event.getReason();//获取变更的原因
  14. UserInfo myInfo = event.getMyInfo();//获取当前被登出账号的信息
  15. switch (reason) {
  16. case user_password_change:
  17. //用户密码在服务器端被修改
  18. break;
  19. case user_logout:
  20. //用户换设备登录
  21. break;
  22. case user_deleted:
  23. //用户被删除
  24. break;
  25. }
  26. }
  27. }

Group Information Maintenance

Create a group

  1. JMessageClient.createGroup(String groupName, String groupDesc, CreateGroupCallback callback);
  2. @since 2.3.0
  3. 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

  1. 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

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

Get a list of groups

  1. JMessageClient.getGroupIDList(GetGroupListCallback callback)

Callback

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

Get group information

  1. JMessageClient.getGroupInfo(long groupId, GetGroupInfoCallback callback)

Parameter Description

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

Callback

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

Update group name

  1. groupInfo.updateName(String groupName, BasicCallback callback);

Parameter Description

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

Update group description

  1. 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

  1. 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

  1. 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

  1. 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

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

Quit group

  1. JMessageClient.exitGroup(long groupId, BasicCallback callback);

Parameter Description

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

Get a list of group members

  1. JMessageClient.getGroupMembers(long groupID,
  2. GetGroupMembersCallback callback)

Parameter Description

  • long groupId - group ID
  • GetGroupMembersCallback callback

Callback

  1. 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

  1. 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

  1. groupinfo.isGroupBlocked();

return

  • int 1 - blocked, 0 - unblocked

Get the current group block list of users

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. //消息发送方
  2. Conversation conv = Conversation.createGroupConversation(gid);
  3. GroupInfo groupInfo = (GroupInfo) conv.getTargetInfo();
  4. List<UserInfo> atList = new ArrayList<UserInfo>();
  5. atList.add(groupInfo.getGroupMemberInfo("user1", appkey));//获取到被@的群成员的userinfo,并填充到atList中去。
  6. atList.add(groupInfo.getGroupMemberInfo("user2", appkey));
  7. //创建一条带有atList的消息。
  8. Message msg = conv.createSendMessage(new TextContent("a message with atList!"), atList, null);
  9. JMessageClient.sendMessage(msg);//发送消息
  10. //消息接收方
  11. public void onEvent(MessageEvent event){
  12. Message msg = event.getMessage();//收到消息事件,从消息事件中拿到消息对象
  13. msg.isAtMe(); //判断这条消息是否@了我
  14. //获取消息中包含的完整的atList
  15. msg.getAtUserList(new GetUserInfoListCallback() {
  16. @Override
  17. public void gotResult(int responseCode, String responseMessage, List<UserInfo> userInfoList) {
  18. if(responseCode == 0){
  19. //获取atList成功
  20. }else{
  21. //获取atList失败
  22. }
  23. }
  24. });
  25. }

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

  1. /**
  2. * 创建公开群组, 群组创建成功后,创建者会默认包含在群成员中。
  3. * 公开群组与私有群组的区别是公开群组只有群主和管理员邀请入群才能直接入群,群内其他人员邀请他人入群需要经过群主或管理员审批,
  4. * 管理员相关见{@link GroupInfo#addGroupKeeper(List, BasicCallback)}, 同时公开群组支持申请入群操作{@link JMessageClient#applyJoinGroup(long, String, BasicCallback)},
  5. * 申请入群时也需要群主或管理员审批, 需要审批入群时群主和管理员会收到{@link cn.jpush.im.android.api.event.GroupApprovalEvent}事件
  6. * 通过{@link GroupInfo#getGroupType()}得到群组类型
  7. *
  8. * @param groupName 群组名称
  9. * @param groupDesc 群组描述
  10. * @param callback 回调接口
  11. * @since 2.4.0
  12. */
  13. JMessageClient.createPublicGroup(String groupName, String groupDesc,
  14. CreateGroupCallback callback);
  15. /**
  16. * 创建公开群组,群组创建成功后,创建者会默认包含在群成员中。
  17. * 公开群组定义参考{@link JMessageClient#createPublicGroup(String, String, CreateGroupCallback)}
  18. * 使用此接口创建群组时可以指定群头像,并且可以指定头像文件在后台存储时的扩展名,如果填空或者不填,则后台存储文件时将没有扩展名。
  19. *
  20. * @param groupName 群组名称
  21. * @param groupDesc 群组描述
  22. * @param groupAvatarFile 群组头像文件
  23. * @param format 头像文件扩展名,注意名称中不要包括"."
  24. * @param callback 回调接口
  25. * @since 2.4.0
  26. */
  27. JMessageClient.createPublicGroup(final String groupName, final String groupDesc, final File groupAvatarFile, String format,
  28. final CreateGroupCallback callback);

Apply to join the group

Since 2.4.0

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

Group members approval events/span>

Since 2.4.0

  1. 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

  1. 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]

  1. /**
  2. * 入群审批同意,操作成功后,群内所有成员包括被审批人自己都会收到一个包含群成员变化的EventNotification类型的消息
  3. *
  4. * @param username 同意入群者的username
  5. * @param appKey 同意入群者的appKey,若传入空则默认使用本应用的appKey
  6. * @param callback
  7. */
  8. groupApprovalEvent.acceptGroupApproval(String username, String appKey, final BasicCallback callback);
  9. /**
  10. * 入群审批拒绝,操作成功后,该次审批请求的发起方(Type为{@link Type#apply_join_group}时是申请人 Type为{@link Type#invited_into_group}时是邀请人)
  11. * 会收到一个审批拒绝通知事件{@link GroupApprovalRefuseEvent}
  12. *
  13. * @param username 拒绝入群者的username
  14. * @param appKey 拒绝入群者的appKey, 若传入空则默认使用本应用的appKey
  15. * @param reason 拒绝理由,可填null
  16. * @param callback
  17. */
  18. groupApprovalEvent.refuseGroupApproval(String username, String appKey, String reason, BasicCallback callback);

Group members approval rejected events

Since 2.4.0

  1. 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

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

Public group related example code

  1. //创建公开群组
  2. JMessageClient.createPublicGroup(name, desc, callback);
  3. JMessageClient.createPublicGroup(name, desc, avatarFile, format, callback);//包含群头像
  4. //申请入群
  5. JMessageClient.applyJoinGroup(Long.parseLong(mEt_groupID.getText().toString()), reason, new BasicCallback() {
  6. @Override
  7. public void gotResult(int responseCode, String responseMessage) {
  8. mProgressDialog.dismiss();
  9. if (responseCode == 0) {
  10. Toast.makeText(ApplyJoinGroupActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
  11. } else {
  12. Log.d(TAG, "apply failed. code :" + responseCode + " msg : " + responseMessage);
  13. Toast.makeText(ApplyJoinGroupActivity.this, "申请失败", Toast.LENGTH_SHORT).show();
  14. }
  15. }
  16. });
  17. //入群审批
  18. event.acceptGroupApproval(username, appKey, new BasicCallback() {
  19. @Override
  20. public void gotResult(int responseCode, String responseMessage) {
  21. if (0 == responseCode) {
  22. Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
  23. } else {
  24. Log.i(TAG, "acceptApplyJoinGroup failed,"+ " code = " + responseCode + ";msg = " + responseMessage);
  25. Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
  26. }
  27. }
  28. }); //入群审批同意
  29. event.refuseGroupApproval(username, appKey, reason, new BasicCallback() {
  30. @Override
  31. public void gotResult(int responseCode, String responseMessage) {
  32. if (0 == responseCode) {
  33. Toast.makeText(getApplicationContext(), "拒绝成功", Toast.LENGTH_SHORT).show();
  34. } else {
  35. Log.i(TAG, "refuseApplyJoinGroup failed,"+ " code = " + responseCode + ";msg = " + responseMessage);
  36. Toast.makeText(getApplicationContext(), "拒绝失败", Toast.LENGTH_SHORT).show();
  37. }
  38. }
  39. }); //入群审批拒绝
  40. //获取指定应用下所有公开群组
  41. JMessageClient.getPublicGroupListByApp(appkey, start, count, new RequestCallback<List<GroupBasicInfo>>() {
  42. @Override
  43. public void gotResult(int responseCode, String responseMessage, List<GroupBasicInfo> groupBasicInfos) {
  44. if (responseCode == 0) {
  45. String result = "";
  46. for (GroupBasicInfo groupBasicInfo : groupBasicInfos) {
  47. result += "GroupID: " + groupBasicInfo.getGroupID() + ", GroupType: " + groupBasicInfo.getGroupType() +
  48. ", GroupName: " + groupBasicInfo.getGroupName() + ", GroupDescription: " + groupBasicInfo.getGroupDescription() +
  49. ", GroupAvatarMediaID: " + groupBasicInfo.getAvatar() + ", GroupMaxMemberCount: " + groupBasicInfo.getMaxMemberCount()+ "\n\n";
  50. }
  51. tvDisplay.setText(result);
  52. tvDisplay.post(new Runnable() {
  53. @Override
  54. public void run() {
  55. scrollView.fullScroll(ScrollView.FOCUS_DOWN);
  56. }
  57. });
  58. } else {
  59. tvDisplay.setText("获取失败!\nresponseCode:" + responseCode + "\nresponseMsg" + responseMessage);
  60. }
  61. }
  62. });

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

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

Get a list of banned

Since 2.4.0

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

Determine whether the user is banned

Since 2.4.0

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

Relevant example code of group members banned

  1. //设置群成员禁言状态
  2. JMessageClient.getGroupInfo(mGroupID, new GetGroupInfoCallback() {
  3. @Override
  4. public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo) {
  5. if (0 == responseCode) {
  6. groupInfo.setGroupMemSilence(mNames, mAppKey, keepSilence, new BasicCallback() {
  7. @Override
  8. public void gotResult(int i, String s) {
  9. mProgressDialog.dismiss();
  10. if (0 == i) {
  11. Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言成功" : "取消禁言成功", Toast.LENGTH_SHORT).show();
  12. } else {
  13. Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言失败" : "取消禁言失败", Toast.LENGTH_SHORT).show();
  14. Log.i(TAG, "GroupInfo.setGroupMemSilence " + ", responseCode = " + i + " ; Desc = " + s);
  15. }
  16. }
  17. });
  18. } else {
  19. mProgressDialog.dismiss();
  20. Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言失败" : "取消禁言失败", Toast.LENGTH_SHORT).show();
  21. Log.i(TAG, "getGroupInfo failed " + ", responseCode = " + responseCode + " :Desc = " + responseMessage);
  22. }
  23. }
  24. });
  25. //获取群成员禁言列表
  26. JMessageClient.getGroupInfo(mGetId, new GetGroupInfoCallback() {
  27. @Override
  28. public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo) {
  29. mProgressDialog.dismiss();
  30. if (responseCode == 0) {
  31. List<UserInfo> silenceMembers = groupInfo.getGroupSilenceMembers();
  32. StringBuilder sb = new StringBuilder();
  33. for (UserInfo info : silenceMembers) {
  34. sb.append(info.getUserName());
  35. sb.append("\n");
  36. }
  37. mTv_showGroupInfo.append("群成员禁言信息列表(这里获取name,需要其他信息请自行获取):\n" + sb.toString());
  38. Toast.makeText(getApplicationContext(), "获取成功", Toast.LENGTH_SHORT).show();
  39. } else {
  40. Log.i("GetGroupInfoActivity", "groupInfo.getGroupMembers" + ", responseCode = " + responseCode + " ; Desc = " + responseMessage);
  41. Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
  42. }
  43. }
  44. });
  45. //判断用户是否被禁言
  46. JMessageClient.getGroupInfo(mGetId, new GetGroupInfoCallback() {
  47. @Override
  48. public void gotResult(int i, String s, GroupInfo groupInfo) {
  49. if (i == 0) {
  50. mProgressDialog.dismiss();
  51. Toast.makeText(getApplicationContext(), groupInfo.isKeepSilence(name, appKey) ? "已被禁言" : "没有被禁言或者用户不存在或不在指定群", Toast.LENGTH_SHORT).show();
  52. } else {
  53. mProgressDialog.dismiss();
  54. Log.i("GetGroupInfoActivity", "groupInfo.getGroupMemberSilenceStatus" + ", responseCode = " + i + " ; Desc = " + s);
  55. Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
  56. }
  57. }
  58. });

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

  1. /**
  2. * 添加群管理员
  3. *
  4. * @param userInfos 群成员UserInfo列表
  5. * @param callback 回调
  6. * @since 2.5.0
  7. */
  8. groupInfo.addGroupKeeper(List<UserInfo> userInfos, BasicCallback callback);

Cancel the administrator

Since 2.5.0

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

Get the list of administrators

Since 2.5.0

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

Example Code

  1. //添加管理员
  2. groupInfo.addGroupKeeper(userInfos, new BasicCallback() {
  3. @Override
  4. public void gotResult(int responseCode, String responseMessage) {
  5. if (responseCode == 0) {
  6. Toast.makeText(getApplicationContext(), "添加管理员成功", Toast.LENGTH_SHORT).show();
  7. } else {
  8. Toast.makeText(getApplicationContext(), "添加管理员失败", Toast.LENGTH_SHORT).show();
  9. mTvGroupKeeper.setText("responseCode:" + responseCode + "\nresponseMessage:" + responseMessage);
  10. }
  11. }
  12. });
  13. //取消管理员
  14. groupInfo.removeGroupKeeper(userInfos, new BasicCallback() {
  15. @Override
  16. public void gotResult(int responseCode, String responseMessage) {
  17. if (responseCode == 0) {
  18. Toast.makeText(getApplicationContext(), "取消管理员成功", Toast.LENGTH_SHORT).show();
  19. } else {
  20. Toast.makeText(getApplicationContext(), "取消管理员失败", Toast.LENGTH_SHORT).show();
  21. mTvGroupKeeper.setText("responseCode:" + responseCode + "\nresponseMessage:" + responseMessage);
  22. }
  23. }
  24. });
  25. //获取管理员列表
  26. List<UserInfo> userInfos = groupInfo.getGroupKeepers();
  27. String result = "这里只展示username:";
  28. for (UserInfo userInfo : userInfos) {
  29. if (userInfo != null) {
  30. result += "\n" + userInfo.getUserName();
  31. }
  32. }
  33. 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

  1. 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

  1. 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

  1. JMessageClient.getBlacklist(GetBlacklistCallback callback)

Parameter Description

  • GetBlacklistCallback - get callback interface of blacklist

Callback

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

Notification Bar Management

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

Parameter Description

Get display type of notification bar

Since 2.2.0

  1. 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

  1. 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.

  1. 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 .

  1. 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.

  1. 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.

  1. 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

  1. ContactManager.sendInvitationRequest("test_user", "test_appkey", "hello", new BasicCallback() {
  2. @Override
  3. public void gotResult(int responseCode, String responseMessage) {
  4. if (0 == responseCode) {
  5. //好友请求请求发送成功
  6. } else {
  7. //好友请求发送失败
  8. }
  9. }
  10. });

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.

  1. 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

  1. ContactManager.acceptInvitation("test_user", "test_appkey", new BasicCallback() {
  2. @Override
  3. public void gotResult(int responseCode, String responseMessage) {
  4. if (0 == responseCode) {
  5. //接收好友请求成功
  6. } else {
  7. //接收好友请求失败
  8. }
  9. }
  10. });

Reject friend request

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

  1. 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:

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

Get buddy list

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

  1. ContactManager.getFriendList(final GetUserInfoListCallback callback)

Parameter Definition

  • GetUserInfoListCallback callback - result callback.

Example Code

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

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

  1. userinfo.removeFromFriendList(BasicCallback callback)

Parameter Definition

  • BasicCallback callback - result callback

Example Code

  1. userinfo.removeFromFriendList(new BasicCallback() {
  2. @Override
  3. public void gotResult(int responseCode, String responseMessage) {
  4. if (0 == responseCode) {
  5. //移出好友列表成功
  6. } else {
  7. //移出好友列表失败
  8. }
  9. }
  10. });

Update user note name/note text

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

  1. userinfo.updateNoteName(String noteName, BasicCallback callback)
  2. userinfo.updateNoteText(String noteText, BasicCallback callback)

Parameter Definition

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

Example Code

  1. userinfo.updateNoteName("new_note_name", new BasicCallback() {
  2. @Override
  3. public void gotResult(int responseCode, String responseMessage) {
  4. if (0 == responseCode) {
  5. //更新备注名成功
  6. } else {
  7. //更新备注名失败
  8. }
  9. }
  10. });

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.
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:

  1. class ContactNotifyEventReceiver extends Activity{
  2. @Override
  3. protected void onCreate() {
  4. super.onCreate(savedInstanceState);
  5. JMessageClient.registerEventReceiver(this);
  6. }
  7. @Override
  8. protected void onDestroy() {
  9. JMessageClient.unRegisterEventReceiver(this);
  10. super.onDestroy();
  11. }
  12. public void onEvent(ContactNotifyEvent event) {
  13. String reason = event.getReason();
  14. String fromUsername = event.getFromUsername();
  15. String appkey = event.getfromUserAppKey();
  16. switch (event.getType()) {
  17. case invite_received://收到好友邀请
  18. //...
  19. break;
  20. case invite_accepted://对方接收了你的好友邀请
  21. //...
  22. break;
  23. case invite_declined://对方拒绝了你的好友邀请
  24. //...
  25. break;
  26. case contact_deleted://对方将你从好友中删除
  27. //...
  28. break;
  29. default:
  30. break;
  31. }
  32. }
  33. }

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

  1. /**
  2. * 获取当前应用appkey所属下聊天室信息。
  3. *
  4. * @param start 起始位置
  5. * @param count 获取个数
  6. * @param callback 接口回调
  7. * @since 2.4.0
  8. */
  9. 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

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

Query chat room information of a specified roomID

Since 2.4.0

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

Enter the chat room

Since 2.4.0

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

Leave the chat room

Since 2.4.0

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

Get chat session information

Since 2.4.0

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

Get the user’s chat room conversation list locally

Since 2.4.0

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

Delete chat room conversation

Since 2.4.0

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

Create a chat room session

Since 2.4.0

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

Chat room message events

Since 2.4.0

  1. 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

  1. // 获取当前应用appkey所属下聊天室信息
  2. ChatRoomManager.getChatRoomListByApp(start, count, new RequestCallback<List<ChatRoomInfo>>() {
  3. @Override
  4. public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
  5. String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
  6. postTextToDisplay("getChatRoomListByApp", responseCode, responseMessage, result);
  7. }
  8. });
  9. // 获取当前用户所加入的所有聊天室的信息
  10. ChatRoomManager.getChatRoomListByUser(new RequestCallback<List<ChatRoomInfo>>() {
  11. @Override
  12. public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
  13. String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
  14. postTextToDisplay("getChatRoomListByUser", responseCode, responseMessage, result);
  15. }
  16. });
  17. // 查询指定roomID的聊天室信息
  18. ChatRoomManager.getChatRoomInfos(Collections.singleton(roomID), new RequestCallback<List<ChatRoomInfo>>() {
  19. @Override
  20. public void gotResult(int responseCode, String responseMessage, List<ChatRoomInfo> chatRoomInfos) {
  21. String result = null != chatRoomInfos ? chatRoomInfos.toString() : null;
  22. postTextToDisplay("getChatRoomInfos", responseCode, responseMessage, result);
  23. }
  24. });
  25. // 进入聊天室
  26. ChatRoomManager.enterChatRoom(roomID, new RequestCallback<Conversation>() {
  27. @Override
  28. public void gotResult(int responseCode, String responseMessage, Conversation conversation) {
  29. String result = null != conversation ? conversation.toString() : null;
  30. postTextToDisplay("enterChatRoom", responseCode, responseMessage, result);
  31. }
  32. });
  33. // 离开聊天室
  34. ChatRoomManager.leaveChatRoom(roomID, new BasicCallback() {
  35. @Override
  36. public void gotResult(int responseCode, String responseMessage) {
  37. postTextToDisplay("leaveChatRoom", responseCode, responseMessage, null);
  38. }
  39. });
  40. // 发送聊天室消息
  41. Conversation conv = JMessageClient.getChatRoomConversation(roomID);
  42. if (null == conv) {
  43. conv = Conversation.createChatRoomConversation(roomID);
  44. }
  45. String text = etInputText.getText().toString();
  46. final Message msg = conv.createSendTextMessage(text);//实际聊天室可以支持所有类型的消息发送,demo为了简便,仅仅实现了文本类型的消息发送
  47. msg.setOnSendCompleteCallback(new BasicCallback() {
  48. @Override
  49. public void gotResult(int responseCode, String responseMessage) {
  50. if (0 == responseCode) {
  51. postMessageToDisplay("MessageSent", responseCode, responseMessage, msg);
  52. } else {
  53. postTextToDisplay("MessageSent", responseCode, responseMessage, "消息发送失败");
  54. }
  55. }
  56. });
  57. JMessageClient.sendMessage(msg);
  58. // 接收聊天室消息
  59. public void onEventMainThread(ChatRoomMessageEvent event) {
  60. Log.d("tag", "ChatRoomMessageEvent received .");
  61. List<Message> msgs = event.getMessages();
  62. for (Message msg : msgs) {
  63. //这个页面仅仅展示聊天室会话的消息
  64. postMessageToDisplay("MessageReceived", event.getResponseCode(), event.getResponseDesc(), msg);
  65. }
  66. }

Do-Not-Disturb Related

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

  1. 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.

  1. 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

  1. 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.

Summary of cross-application related interface

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

  1. createSingleConversation(String userName, String appKey)
JMessageClient

Get user information across applications

  1. getUserInfo(String username,String appKey,GetUserInfoCallback callback)

Add group members across applications

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

Kick out group members across applications

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

Add users into the blacklist across applications

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

Remove users from blacklist across applications

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

Get group member information

  1. getGroupMemberInfo(String username, String appKey)

Specific implementation of cross-application

Get user information across applications

Obtain cross-application user information by specifying appKey.

  1. 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

  1. JMessageClient.getUserInfo("username", "appKey", new GetUserInfoCallback() {
  2. @Override
  3. public void gotResult(int responseCode, String responseMessage, UserInfo info) {
  4. // 获取到跨应用的用户信息
  5. ...
  6. }
  7. });
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.

  1. 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

  1. //创建跨应用会话
  2. Conversation con = Conversation.createSingleConversation("username", "appKey");
  3. MessageContent content = new TextContent("hello");
  4. //创建一条消息
  5. Message message = con.createSendMessage(content);
  6. //发送消息
  7. 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

  1. 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

  1. 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

  1. //此接口是实例对象上的接口
  2. 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

  1. //添加跨应用用户到群组
  2. JMessageClient.addGroupMembers(testGid, "appKey", userNameList, new BasicCallback() {
  3. @Override
  4. public void gotResult(int responseCode, String responseMessage) {
  5. //添加跨应用群成员成功之后,创建会话,发送消息。
  6. if(0 == responseCode){
  7. Conversation conversation = Conversation.createGroupConversation(testGid);
  8. Message msg = conversation.createSendTextMessage("hello");
  9. JMessageClient.sendMessage(msg);
  10. }
  11. }
  12. });
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

  1. 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

  1. 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

  1. //跨应用添加用户至黑名单
  2. JMessageClient.addUsersToBlacklist(usernames, "appKey",new BasicCallback() {
  3. @Override
  4. public void gotResult(int responseCode, String responseMessage) {
  5. if (0 == responseCode){
  6. //成功跨应用添加用户至黑名单
  7. ...
  8. }
  9. }
  10. });
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.

  1. 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

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

Class Definition

Conversation and messages

  1. cn.jpush.im.android.api.model.Conversation
  2. public File getAvatar();
  3. public String getDisplayName();
  4. public Message getLatestMessage();
  5. public List<Message> getAllMessage();
  6. public List<Message> getNewMessagesFromNewest(int offset, int limit);
  7. public Message createSendMessage(MessageContent content);
  8. public Message createSendTextMessage(String text);
  9. public Message createSendImageMessage(File imageFile)
  10. throws FileNotFoundException
  11. public Message createSendVoiceMessage(File voiceFile, int duration)
  12. throws FileNotFoundException
  13. public Message createSendCustomMessage(Map<? extends String, ?> valuesMap)
  14. public boolean resetUnreadCount();
  1. cn.jpush.im.android.api.model.Message
  2. public String getFromID()
  3. public MessageContent getContent()
  4. public ContentType getContentType()
  5. public MessageStatus getStatus()
  6. public String getTargetID()
  7. public long getCreateTime()
  8. public void setOnContentUploadProgressCallback(ProgressUpdateCallback callback)
  9. public void setOnContentDownloadProgressCallback(ProgressUpdateCallback callback)
  10. public void setOnSendCompleteCallback(BasicCallback sendCompleteCallback)

Example

  1. Conversation conv = JMessageClient.getSingleConversation("tom");
  2. if (null == conv) {
  3. conv = Conversation.createSingleConversation("tom");
  4. }
  5. TextContent text = new TextContent("Hi, JMessage!");
  6. Message message = conv.createSendMessage(text);
  7. JMessageClient.sendMessage(message);
Chat content

Parent class of chat content

  1. cn.jpush.im.api.content.MessageContent

Chat content types supported currently

  1. cn.jpush.im.api.content.TextContent
  2. cn.jpush.im.api.content.VoiceContent
  3. cn.jpush.im.api.content.ImageContent
  4. cn.jpush.im.api.content.LocationContent
  5. cn.jpush.im.api.content.FileContent
  6. cn.jpush.im.api.content.CustomContent

Example

  1. // 参数:文本内容
  2. TextContent text = new TextContent("Hi, JMessage");
  3. // 参数:语音文件对象,语音文件时长
  4. VoiceContent voice = new VoiceContent(new File("/sdcard/voice.amr"), 21);
  5. // 参数:图片文件对象
  6. ImageContent image = new ImageContent(new File("/sdcard/image.png"));
  7. // 参数:任意文件对象
  8. FileContent fileContent = new FileContent(new File("/sdcard/file.xxx"));
  9. // 参数:经度,纬度,缩放比例,地址详情
  10. LocationContent locationContent = new LocationContent(111.1,222.2,500,"xx省xx市xx区xx街xx号");

Callback definition

BasicCallback
  1. public abstract class BasicCallback {
  2. private boolean isRunInUIThread = true;
  3. /**
  4. * Default is running in UI thread.
  5. */
  6. public BasicCallback() {
  7. }
  8. /**
  9. * 默认callback会在主线程中回调,如果需要在子线程回调,则在构造方法的参数中传入false
  10. * @param isRunInUIThread 是否在主线程中执行回调,默认为true。
  11. */
  12. public BasicCallback(boolean isRunInUIThread) {
  13. this.isRunInUIThread = isRunInUIThread;
  14. }
  15. public boolean isRunInUIThread() {
  16. return this.isRunInUIThread;
  17. }
  18. /**
  19. * 异步调用返回结果。
  20. *
  21. * @param responseCode 0 表示正常。大于 0 表示异常,responseMessage 会有进一步的异常信息。
  22. * @param responseMessage 一般异常时会有进一步的信息提示。
  23. */
  24. public abstract void gotResult(int responseCode, String responseMessage);
  25. }

Error Code Definition

Reference Document: List of IM Android SDK Error Codes