Chat API

This is the developer guide for Chat SDK v1. The new Chat SDK v2 for Android is now available and is the recommended version to integrate Chat into your mobile app.

This document covers how to create your own Chat UI using the Chat API. It covers sending and receiving data to and from Zendesk Chat and managing a chat lifecycle. It doesn't cover how to render the data.

Chat API documentation

Download the Chat API documentation from https://zendesk.github.io/mobile_sdk_javadocs. To add the docs to your project, see Attaching Javadocs in Android Studio.

We also have some sample apps on Github which demonstrate how to use the Zendesk mobile SDKs in different ways. These can serve as useful references when integrating with the API providers.

Installation

...
// Note that this is root level repositories container and not the one under 'buildScript'
repositories {
    maven { url 'https://zendesk.jfrog.io/zendesk/repo' }
}
...
dependencies {
    compile group: 'com.zopim.android', name: 'sdk-api', version: '1.4.8'
}
...

Configuration

Configuration is performed in exactly the same way regardless of how you intend to use the SDK. See Configuring and starting a chat.

When using the 'sdk-api' artifact, ZopimChat is not available. Use ZopimChatApi instead.

Starting a chat session

To start a chat session:

import com.zopim.android.sdk.api.ChatApi;
import com.zopim.android.sdk.api.ZopimChatApi;
...

ChatApi chat = ZopimChatApi.start(activity);

This starts the session and returns an instance of the chat API. If default configuration was provided during chat initialization it will apply to this chat as well.

To configure and start a chat session:

import com.zopim.android.sdk.api.ChatApi;
import com.zopim.android.sdk.api.ZopimChatApi;
...

// builds and configures new chat API session
ChatApi chat = new ZopimChatApi.SessionConfig()
    .department("A department")
    .tags("tag1", "tag2")
    .build(activity);

This will configure and start the session and return an instance of the chat API. This chat configuration is specific to this chat session.

Events

Type Description
Connection events Chat connection status has been updated
Timeout events Indicates when a session times out
Chat log events A new chat event. These are the events that ultimately get rendered
Chatting status events The chatting status of a current session, whether or not the visitor is chatting to an agent
Agent events The agent information has changed. Primarily used as an indicator that the agent is joining, leaving or typing.
File sending events Indicates upload progression and status.
Account events Account has gone on or offline.
Connection events

Connection events indicate a chat connection state has changed. A chat must be in the connected state to send messages. Messages are not cached to send when the chat connects. You can configure chat anytime because of this information.

Listening for connection events

Once a session has been initiated, listen for connection status updates and timeout events:

import com.zopim.android.sdk.data.observers.ConnectionObserver;
import com.zopim.android.sdk.model.Connection;
import com.zopim.android.sdk.api.ZopimChatApi;
...

ConnectionObserver connectionObserver = new ConnectionObserver() {

    public void update(Connection connection) {
        // update is received on a non-UI thread
        ...
    }

};

// listen for connection updates
ZopimChatApi.getDataSource().addConnectionObserver(connectionObserver);

// and remember to remove the observer onStop()
ZopimChatApi.getDataSource().deleteConnectionObserver(connectionObserver);
Handling connection events

When you receive an update that the connection status has changed, you receive a Connection object. To obtain the new status use the following code:

import com.zopim.android.sdk.model.Connection;
...

Connection.Status status = connection.getStatus();

Where Connection.Status is:

Type Description
Connection.Status.UNKNOWN Chat connection has not been started
Connection.Status.CONNECTING Chat is currently establishing a connection
Connection.Status.CONNECTED Chat is connected
Connection.Status.CLOSED Chat connection has been closed
Connection.Status.DISCONNECTED Chat connection lost
Connection.Status.NO_CONNECTION Device has no internet connection
Timeout events

It is important to listen for timeout events as well as connection events. When a chat times out, it moves to the uninitialized state and a timeout notification is sent.

Listening for timeout events

To listen for timeout events:

import android.content.BroadcastReceiver;
import com.zopim.android.sdk.api.ChatSession;
...

public class MyActivity extends AppCompatActivity {

    private ChatTimeoutReceiver chatTimeoutReceiver = new ChatTimeoutReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entry_activity);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(chatTimeoutReceiver, new IntentFilter(ChatSession.ACTION_CHAT_SESSION_TIMEOUT));
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(chatTimeoutReceiver);
    }

    public class ChatTimeoutReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            if (intent != null && ChatSession.ACTION_CHAT_SESSION_TIMEOUT.equals(intent.getAction())) {
                ...
            }
        }
    }
}
Handling timeout events

When a chat times out, you won't be able to send messages. You can start a new chat or inform the user the chat has ended but you cannot reconnect to the timed out chat.

Chat log events

Chat log events contain the majority of the information you will present to the user. An effective chat UI must be able to render chat log events and send messages.

Listening for chat log events

To listen for chat log events:

import com.zopim.android.sdk.api.ZopimChatApi;
import com.zopim.android.sdk.data.observers.ChatItemsObserver;
import com.zopim.android.sdk.model.items.RowItem;
import java.util.TreeMap;
...

ChatItemsObserver chatItemsObserver = new ChatItemsObserver(context) {
    @Override
    protected void updateChatItems(final TreeMap<String, RowItem> chatItems) {
        ...
    }
};

// listen for chat log events
ZopimChatApi.getDataSource().addChatLogObserver(chatItemsObserver);

// and remember to remove the observer onStop()
ZopimChatApi.getDataSource().deleteChatLogObserver(chatItemsObserver);
Handling chat log events

There are a number of different types of row items:

Type Description
AgentMessage Chat message sent by agent
VisitorMessage Chat message sent by visitor
VisitorAttachment Attachments uploaded by visitor
AgentAttachment Attachments sent by agent
AgentTyping Agent is typing
AgentOptions A list of options sent by agent
ChatEvent Automated chat messages and triggers
ChatMemberEvent Member joined or left the chat
ChatRating Chat ratings sent by agent

Each chat item contains all the information that you're likely to display in the chat UI.

Due to the way events are created, there is no need to update your UI with outgoing messages. You can simply handle a stream of incoming events and render them appropriately based on their type.

When you send a message or upload a file, an event is created immediately. It is then sent to Zendesk Chat. When Zendesk Chat receives the event, it is updated and isUnverified() is set to false.

Events are uniquely identified by event id. Subsequent events with the same event id are updates to the initial event. An example would be a ChatLog. Multiple events are received to indicate changes in upload status.

Chatting status events

Chatting status events are posted whenever the chatting state of a current session changes. This happens when a visitor sends their initial message, it changes from UNKOWN or NOT_CHATTING to a CHATTING state. This will allow you to check if a chat is in progress or not

Listening for chatting status Events
ZopimChatApi.getDataSource().addChattingStatusObserver(new ChattingStatusObserver() {
            @Override
            protected void update(ChattingStatus isChatting) {
                ...
            }
        });
Agent events

Agent events are posted whenever the agent information changes. Typically this is when an agent joins or leaves the chat, or when an agent starts or stops typing.

Listening for agent events

To listen for agent events:

import com.zopim.android.sdk.data.observers.AgentsObserver;
import com.zopim.android.sdk.model.Agent;
import java.util.Map;
import com.zopim.android.sdk.api.ZopimChatApi;
...

AgentsObserver agentsObserver = new AgentsObserver() {
    @Override
    public void update(final Map<String, Agent> map) {
        ...
    }
};

// listen for agent events
ZopimChatApi.getDataSource().addAgentsObserver(agentsObserver);

// and remember to remove the observer onStop()
ZopimChatApi.getDataSource().deleteAgentsObserver(agentsObserver);
Handling agent events

An agent event notification tells you that agent info has been updated.

Agent model:

Property Description
Boolean isTyping(); true if the agent is typing
String getDisplayName(); Display name of the agent
String getAvatarUri(); Agent avatar uri resource
File sending events

File sending events are used to indicate the status and progress of file uploads.

Registering for file sending events
import com.zopim.android.sdk.data.observers.FileSendingObserver;
import com.zopim.android.sdk.model.FileSending;
import com.zopim.android.sdk.api.ZopimChatApi;
...

FileSendingObserver fileSendingObserver = new FileSendingObserver(){
    @Override
    public void update(final FileSending fileSending) {
        ...
    }
};

// listen for agent events
ZopimChatApi.getDataSource().addFileSendingObserver(fileSendingObserver);

// and remember to remove the observer onStop()
ZopimChatApi.getDataSource().deleteFileSendingObserver(fileSendingObserver);
Handling upload events

File uploads generate regular chat log events that contain upload status information. Handling upload events is only needed if you want to display upload progress.

Account events

Account events indicate when your Zendesk Chat account goes online or offline such as when there are no agents online.

Registering for account events
import com.zopim.android.sdk.data.observers.AccountObserver;
import com.zopim.android.sdk.model.Account;
import com.zopim.android.sdk.api.ZopimChatApi;
...

AccountObserver accountObserver = new AccountObserver() {
    @Override
    public void update(final Account account) {

    }
};

// listen for account events
ZopimChatApi.getDataSource().addAccountObserver(accountObserver);

// and remember to remove the observer onStop()
ZopimChatApi.getDataSource().deleteAccountObserver(accountObserver);
Handling account events

To get the status of your Zendesk Chat account:

import com.zopim.android.sdk.model.Account;
...

Account.Status status = account.getStatus();

Where Account.Status is

Type Description
Account.Status.OFFLINE Account is offline
Account.Status.ONLINE Account is online
Account.Status.UNKNOWN Account status is unknown

Sending a message

To send a chat message:

import com.zopim.android.sdk.api.ChatApi;
...

chat.send("A message");

The Chat API can send a chat message once a connection has been established. Any failed attempts are cached to be resent when the connection is restored.

Ending a chat

To end a chat, closing all connections and discarding all session data:

import com.zopim.android.sdk.api.ChatApi;
...

chat.endChat();

Note that this does not immediately cause a session to end, but instead notifies the server that it should take steps to end the session. Attempts to start a new chat immediately after calling endChat will result in the previous chat resuming.

Adding a note to a chat

To add a note to a chat:

import com.zopim.android.sdk.api.ChatApi;
...

chat.setNote("Your note goes here");