CEC Android SDK API

Send Text Message

// send a text message. content for the message text content. toChatUsername for the IM service ID on the Hyphenate Customer Engagement Cloud.
        Message message = Message.createTxtSendMessage(content, toChatUsername);
        ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Send Voice Message

// filePath is the voice file path. length for the recording time (seconds). toChatUsername for the IM service ID.
    Message message = Message.createVoiceSendMessage(filePath, length, toChatUsername);
    ChatClient.getInstance().getChat().sendMessage(message, new Callback(){});

Send Picture Message

// filePath is the image path. false for not sending the original image (any picture more than 100k will be compressed before being sent to the other party). true for sending the original image. toChatUsername for the IM service ID 
        Message message = Message.createImageSendMessage(filePath, false, toChatUsername);
        ChatClient.getInstance().getChat().sendMessage(message, new Callback(){});

Send Location Message

// latitude for latitude of the location, longitude for longitude of the location, locAddress for specific location content, toChatUsername for IM service ID
     Message message = Message.createLocationSendMessage(latitude, longitude, locAddress, toChatUsername);
     ChatClient.getInstance().getChat().sendMessage(message, new Callback(){});

Send File Message

// filePath for the local file path, and toChatUsername for the IM service ID
    Message message = Message.createFileSendMessage(filePath, toChatUsername);
    ChatClient.getInstance().getChat().sendMessage(message, new Callback(){});

Send Transparent Message ====

// used in "chat with agent" scenarios
       Message message = Message.createSendMessage(Message.Type.CMD);
        String action = "action";// specific action
        message.addBody(new EMCmdMessageBody(action));
        message.setTo(toChatUsername);
        ChatClient.getInstance().getChat().sendMessage(message, new Callback(){});

Send Extended Message

An extended message is a message with attributes. Extended messages are used to implement certain functions, such as specifying a team, specifying an agent, passing a customer profile.

Message message = Message.createTxtSendMessage(content, toChatUsername);
        // add your own attributes
        message.setAttribute("attribute1", "value");
        ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Pass Customer Profile

When you need to pass customer attributes (nickname, phone, etc.) to Hyphenate Customer Engagement Cloud, you need to put the attributes in an extended message. Example of an extended text message:

VisitorInfo info = ContentFactory.createVisitorInfo(null);
info.nickName("user nick")
    .name("truly name")
    .qq("10000")
    .companyName("Hyphenate")
    .description("")
    .email("abc@123.com");
Message message = Message.createTxtSendMessage(content, toChatUsername);
message.addContent(info);
ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Send Track Message

VisitorTrack track = ContentFactory.createVisitorTrack(null);
track.title("test_track1")  // display title
                 .price("¥235") // display price
                 .desc("shirt + sweater") // description
                 .imageUrl("http://o8ugkv090.bkt.clouddn.com/em_three.png")// display picture
                 .itemUrl("http://www.baidu.com"); // link that can be clicked
Message message = Message.createTxtSendMessage(content, toChatUsername);
message.addContent(track);
ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Send Order Message

OrderInfo info = ContentFactory.createOrderInfo(null);
   info.title("test_order1")
    .orderTitle("order number: 7890")
    .price("$28")
    .desc("High-waist skirt")
    .imageUrl(IMAGE_URL_1)
    .itemUrl("http://www.baidu.com");
   Message message = Message.createTxtSendMessage(content, toChatUsername);
   message.addContent(info);
   ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Specify Agent

Specify an agent to serve conversations.

The agent account is the agent's login email address.

AgentIdentityInfo info = ContentFactory.createAgentIdentityInfo(null);
   info.agentName(agentName); // Agent account
   Message message = Message.createTxtSendMessage(content, toChatUsername);
   message.addContent(info);
   ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Specify Team

Specify a team to serve conversations.

The name of the team must be exactly the same as the name of the team set on the Hyphenate Customer Engagement Cloud.

QueueIdentityInfo info = ContentFactory.createQueueIdentityInfo(null);
info.queueName(queueName); // Team name
   Message message = Message.createTxtSendMessage(content, toChatUsername);
   message.addContent(info);
   ChatClient.getInstance().getChat().sendMessage(message, new Callback() {});

Receive Messages

Receive messages by registering listeners to the messages.

ChatClient.getInstance().getChat().addMessageListener(new ChatManager.MessageListener() {
            @Override
            public void onMessage(List<Message> list) {
                // receive a regular message
            }

            @Override
            public void onCmdMessage(List<Message> list) {
                 // received a command message. Command messages are not saved in the database. They are used as system notifications, such as comment updates in notes,
                 // and conversations served, transferred, and closed
            }

            @Override
            public void onMessageStatusUpdate() {
            // message status updated. It is used to refresh the list and display the latest status

            }

            @Override
            public void onMessageSent() {
            // Message sent. It is used to refresh the list and display the latest message

            }
        });
        
// remove the listener when you do not need it, such as in the onDestroy () of an activity
ChatClient.getInstance().getChat().removeMessageListener(msgListener);

Detect Message Type

message.getType() == Message.Type.LOCATION location message
message.getType() == Message.Type.FILE file message
message.getType() == Message.Type.IMAGE picture message
message.getType() == Message.Type.VOICE voice message
message.getType() == Message.Type.CMD command message
message.getType() == Message.Type.TXT text message or extended text message
     // for a text message, you need to check its subtype
     MessageHelper.getEvalRequest(message) != null  satisfaction evaluation message
     MessageHelper.getOrderInfo(message) != null    order message
     MessageHelper.getVisitorTrack(message) != null track message
     MessageHelper.getRobotMenu(message) != null  robot menu message
     MessageHelper.getToCustomServiceInfo(message) != null  chat with agent button message
     

Listen to Message Status

Use message to listen to whether a message is sent successfully or has failed.

message.setMessageStatusCallback(new Callback(){});

Get Conversation Details

Conversation conversation = ChatClient.getInstance().getChat().getConversation(toChatUsername);
// Get all messages for a conversation
List<Message> messages = conversation.getAllMessages();
// During SDK initialization, 20 messages are obtained. Go to the DB to get more messages.
// Get the pagesize message before startMsgId. SDK automatically stores the messages obtained using this method to the conversation. You do not need to add these messages to the conversation again.
List<Message> messages = conversation.loadMoreMsgFromDB(startMsgId, pageSize);

Get the Number of Unread Messages

Conversation conversation = ChatClient.getInstance().getChat().getConversation(toChatUsername);
conversation.getUnreadMsgCount()

Clear the Number of Unread Messages

Conversation conversation = ChatClient.getInstance().getChat().getConversation(toChatUsername);
// Clear the number of unread messages in a specified conversation
conversation.markAllMessagesAsRead();
// Set a message to read
conversation.markMessageAsRead(messageId);
// Clear the number of all unread messages
ChatClient.getInstance().getChat().markAllConversationsAsRead();

Get the Total Number of Messages

Conversation conversation = ChatClient.getInstance().getChat().getConversation(toChatUsername);
// Get the number of messages in this conversation locally
conversation.getAllMsgCount()
// Get the number of messages in this conversation in the memory
conversation.getAllMessages().size()

Get All Conversations

Map<String, Conversation> conversations = ChatClient.getInstance().getChat().getAllConversations();

Delete Conversation and History

// Delete the conversation with a specific user. To keep the conversation history, pass false
ChatClient.getInstance().getChat().deleteConversation(username, true);
// Delete a specific message in a conversation
Conversation conversation = ChatClient.getInstance().getChat().getConversation(toChatUsername);
conversation.removeMessage(deleteMsg.msgId);

Get All Notes

/**
     * Get all notes
     * @param projectId Note Project ID. Obtain the Project ID from "Admin Mode > Note".
     * @param targetUser    IM service ID of the IM account created on Hyphenate Customer Engagement Cloud
     * @param page      page number. It starts from 0
     * @param pageSize  Number of notes on each page
     * @param callback
     */
TicketManager.getInstance().getTickets(projectId, targetUser, page, pageSize, new ValueCallBack(){})

Create Note

/**
     * Create a new note
     *
     * @param postContent
     * @param projectId Note Project ID. Obtain the Project ID from "Admin Mode > Note".
     * @param imUser  IM Service ID of the IM account created on Hyphenate Customer Engagement Cloud
     * @param callback
     */
TicketManager.getInstance().createLeaveMessage(postContent, projectId, imUser, new ValueCallBack(){});

Get All Comments for a Note

/**
     * Get all comments for a note. This API gets the latest 100 comments
     *
     * @param projectId Note Project ID. Obtain the Project ID from "Admin Mode > Note".
     * @param ticketId Note id
     * @param targetUser    IM service ID of the IM account created on Hyphenate Customer Engagement Cloud
     * @param callback
     */
   TicketManager.getInstance().getComments(projectId, ticketId, targetUser, new ValueCallBack(){});
   
   /**
     * Get all comments for a note. This API gets the comments page by page
     *
     * @param projectId Note Project ID. Obtain the Project ID from "Admin Mode > Note".
     * @param ticketId Note id
     * @param targetUser    IM service ID of the IM account created on Hyphenate Customer Engagement Cloud
     * @param callback
     * @param page      page number. It starts from 0
     * @param size  Number of comments on each page
     */
   TicketManager.getInstance().getComments(projectId, ticketId, targetUser, new ValueCallBack(){}, page, size);

Add a Comment to a Note

/**
     * Add a comment to a note
     *
     * @param projectId Note Project ID. Obtain the Project ID from "Admin Mode > Note".
     * @param ticketId Note id
     * @param targetUser    IM service ID of the IM account created on Hyphenate Customer Engagement Cloud
     * @param newCommentBodyJson
     * @param callback
     */
   TicketManager.getInstance().createComment(projectId, ticketId, targetUser, newCommentBodyByJson, new ValueCallBack(){});

Get Working Status

/**
     * Whether to display the note screen (in most cases, display the conversation screen during work hours and the note screen during non-work hours)
     * Return true for non-work hours, return false for work hours
     */
  TicketManager.getInstance().getWorkStatus(new ValueCallBack(){});

Update the current user's nickname in APNs push. If a user changes his nickname, you need to update the nickname to Hyphenate server.

// This method passes a string as its argument and returns a Boolean value to indicate the success or failure.
ChatClient.getInstance().updateNickToServer(nickname)

Listen to Incoming Calls

Register BroadcastReceiver of the corresponding action to listen to incoming calls. When receiving the broadcasts, you can call up the call Activity in the app.

IntentFilter callFilter = new IntentFilter(ChatClient.getInstance().callManager().getIncomingCallBroadcastAction());
registerReceiver(new CallReceiver(), callFilter);

private class CallReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // caller username
        String from = intent.getStringExtra("from");
        // call type
        String type = intent.getStringExtra("type");
                // Jump to the call page
    }
}

Answer a Call

/**
     * Answer a call
     */
ChatClient.getInstance().callManager().acceptCall(new Callback(){});

Decline a Call

/**
* Decline a call
* 
*/
ChatClient.getInstance().callManager().endCall();

Hang Up a Call

/**
* Hang up a call
*/
ChatClient.getInstance().callManager().endCall();

Pause and Resume Voice or Video Data Transfer

  • Pause voice data transfer:

ChatClient.getInstance().callManager().pauseVoice();

  • Restore voice data transfer:

ChatClient.getInstance().callManager().resumeVoice();

  • Pause video (image) data transfer:

ChatClient.getInstance().callManager().pauseVideo();

  • Restore video (image) data transfer:

ChatClient.getInstance().callManager().resumeVoice();

Switch Camera

During a video call, if there is a front camera, the front camera is used by default. To switch to another camera, call this API.

ChatClient.getInstance().callManager().switchCamera();

Set the Local and Opposite Surface View

// set your own video image
  ChatClient.getInstance().callManager().setLocalView(localSurfaceView);
  // set the other person's video image
  ChatClient.getInstance().callManager().setRemoteView(streamId, remoteSurfaceView);

Subscribe to the other person's video stream

To see the other person's video and voice, you need to subscribe to the stream. When you do not need the other person's video, you need to unsubscribe the stream.

// subscribe to the other person's video stream
  ChatClient.getInstance().callManager().subscribe(mediastream, itemSurfaceview, null);
  // Unsubscribe from the other person's video stream
  ChatClient.getInstance().callManager().unSubscribe(mediastream, null);

Listen To Video Stream Callback

// monitor video stream changes. usually called in the onCreate method
  ChatClient.getInstance().callManager().addDelegate(this);
  // cancel the monitor of video stream changes. usually called in the onDestroy method
  ChatClient.getInstance().callManager().removeDelegate(this);
  
      public interface CallManagerDelegate {
        // when a video stream is received
        void onAddStream(MediaStream stream);
        // When a video stream is cancelled
        void onRemoveStream(MediaStream stream);
        // When a video stream is updated
        void onUpdateStream(MediaStream stream);
        // When a video chat is hung up
        void onCallEnd(int reason, String description);
    }

Display the Number of Queuing Customers

When initializing, you need to call option.showVisitorWaitCount (), and then add WaitListener.

Note: You need to enable the “queuing customers” function, a value-added service, on Hyphenate Customer Engagement Cloud. To activate it, please provide the tenant ID and contact Hyphenate.

ChatClient.getInstance().chatManager().addVisitorWaitListener(new ChatManager.VisitorWaitListener() {
            @Override
            public void waitCount(final int num) {
                if (getActivity() == null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (num > 0){
                            tvTipWaitCount.setVisibility(View.VISIBLE);
                            tvTipWaitCount.setText(getString(R.string.current_wait_count, num));
                        }else{
                            tvTipWaitCount.setVisibility(View.GONE);
                        }
                    }
                });
            }
        });

Display Agent's Input Status

When initializing, you need to call options.showAgentInputState (), and then add AgentInputListener.

Note: You need to enable the “display agent's input status” function, a value-added service, on Hyphenate Customer Engagement Cloud. To activate it, please provide the tenant ID and contact Hyphenate.

ChatManager.AgentInputListener agentInputListener = new ChatManager.AgentInputListener() {
        @Override
        public void onInputState(final String input) {
            if (getActivity() == null){
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (input != null) {
                        titleBar.setTitle(input);
                    } else {
                        if (!TextUtils.isEmpty(titleName)) {
                            titleBar.setTitle(titleName);
                        } else {
                            titleBar.setTitle(toChatUsername);
                        }
                    }
                }
            });

        }
    }
    // add listener in the onCreate method
    ChatClient.getInstance().chatManager().addAgentInputListener(agentInputListener);
    // remove listener in the onDestroy method    
    ChatClient.getInstance().chatManager().removeAgentInputListener(agentInputListener);