Skip to content

Integration into Android Mobile Applications

This article provides detailed instructions on how to integrate Rox.Chat Mobile SDK into your Android application.

Step 1: Install Rox.Chat Mobile SDK Library

  1. Open the build.gradle file of the application (module). Specify the repository address and add the following code:

    repositories {
        mavenCentral()
    }
    
    dependencies {
        ...
        implementation 'com.roxchat.sdk:roxclientsdkandroid:3.+'
    }
    

    In order for the changes to be applied, you need to synchronize the project. For example, in Android Studio you can click Sync Now or select File → Sync Progect with Gradle Files from the menu. Wait for the synchronization to complete.

    If synchronization is successful, the library will be added to the project automatically during compilation. If the compilation fails, make sure you have specified the correct repository and dependency and synchronize the project again.

  2. Edit the AndroidManifest.xml file. You need to add the following items to your manifest: in the root of manifest you need to add the permission:

    <uses -permission android:name="android.permission.INTERNET">
    

    The following dependencies should be added to store chat history on your device:

    <uses -permission android:name="android.permission.READ_EXTERNAL_STORAGE">
    <uses -permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
    

    if it is necessary to prevent the device from going to sleep in order to always receive messages from chat, the following line is added:

    <uses -permission android:name="android.permission.WAKE_LOCK">
    

Step 2. Working with Rox.Chat Mobile SDK

Work with Session

After implementing the dependency in the application, you need to create a session. A session in Rox.Chat Mobile SDK is a separate entity from VisitSession, which is implemented on Rox.Chat Server.

A session is a session during which an application interacts with a service. In the current version of SDK it receives any information from Rox.Chat Server only within a session. Before its creation SDK will not receive any information from the server. The session is started by executing the resume() method, and terminated by executing the destroy() method, or by crashing the application.

But in order to start performing actions on a session, you must first create a session object.

  1. Creating a session. The session object is created by the newSessionBuilder method of the Rox class, which returns an object of the SessionBuilder builder class (both classes and their methods are described in the Rox.java file). After setting all the necessary parameters on the created SessionBuilder object, the build() method is called, which returns a RoxSession object. Example usage (for Android):

    RoxSession roxChatSession = Rox.newSessionBuilder()
        .setAccountName(ACCOUNT_NAME)
        .setLocation(LOCATION_NAME)
        .build()
    

    The ACCOUNT_NAME field must correspond to the account name if the chat is hosted in a cloud configuration (on Rox.Chat servers - see Rox service network configurations). If the chat is hosted on the customer's servers, the full URL must be specified instead (example: https://chat.company.ru).

    The LOCATION_NAME field contains the name of the placement. If you specify a non-existent value in it, the invocation will be in the default placement.

    Calling the build() method completes the setting of the initial parameters and creates the session in suspended form.

    A description of all the parameters that can be set when creating a session, as well as errors that may occur during the process, can be found in reference. Only two of them are mandatory - account name and placement.

    If only account name and placement are set, the session will be created in an unauthorized area, nevertheless it will be a personal chat.

  2. Session methods. Below are the basic methods that need to be saved when working with a session object.

    Method Description Next method
    resume After the session object is created, the resume() method must be called to start the session. As a result of the server response, the session's network activity is started as a result of which the MessageListener, ChatStateListener, CurrentOperatorChangeListener and LocationSettingsChangeListener methods may be called. This method is also used to resume a session after calling the pause() method. pause()
    destroy()
    destroyWithClearVisitorData()
    pause() A method that is used to suspend the network activity of a session (for example, when the user is not in an active application window). If the session is already in a suspended state, the method will not perform any action. resume()
    destroy()
    destroyWithClearVisitorData()
    destroy() A method that is used to deactivate the session and class instance. No session related methods can be used after calling this method.
    destroyWithClearVisitorData() A method that is used to deactivate the session and class instance with the user information removed. No session related methods can be used after calling this method.

    Examples of usage:

    public class MainActivity extends AppCompatActivity {
      private RoxSession session;
      private static final String ACCOUNT_NAME = "account";
      private static final String LOCATION_NAME = "mobile";
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          roxChatSession = Rox.newSessionBuilder()
              .setAccountName(ACCOUNT_NAME)
              .setLocation(LOCATION_NAME)
              .build()
      }
      protected void onStart() {
          super.onStart();
          session.resume();
      }
      protected void onResume() {
          super.onResume();
          session.resume();
      }
      protected void onPause() {
          super.onPause();
          session.pause();
      }
      protected void onDestroy() {
          session.destroy();
          super.onDestroy();
      }
    }
    

Installing Interfaces and Protocols

All of the following interfaces and protocols must be installed for an SDK-based application to function. To use the interface methods, it is necessary that the session is not in suspended or deactivated state.

  1. MessageStream is required for direct interaction with Rox.Chat service (for example, to send or receive messages). It is set by calling the getStream() method of the RoxSession instance. Usage examples:

    • Send a message

      session.getStream().sendMessage(message);
      
    • Delete message

      session.getStream().deleteMessage(message, callback);
      
    • Track changes to the current chat operator

      session.getStream().setCurrentOperatorChangeListener(
              new MessageStream.CurrentOperatorChangeListener() {
              @Override
              public void onOperatorChanged(@Nullable Operator oldOperator,
                                      @Nullable Operator newOperator) {
      //your code
             }
         });
      
    • Track session status changes

      session.getStream().setVisitSessionStateListener(
              new MessageStream.VisitSessionStateListener() {
              @Override
              public void onStateChange(@NonNull MessageStream.VisitSessionState previousState,
                                      @NonNull MessageStream.VisitSessionState newState) {
      //your code
              }
          });
      
    • Track changes in the current chat state

      session.getStream().setChatStateListener(
              new MessageStream.ChatStateListener() {
              @Override
              public void onStateChange(@NonNull MessageStream.ChatState oldState,
                                      @NonNull MessageStream.ChatState newState) {
      //your code
              }
          });
      

    The list of all methods, as well as more detailed information about them can be found in the method description MessageStream.

  2. MessageListener is required to receive changes to the message stream. Its methods are called automatically when performing actions on messages in the chat room: when adding a message, deleting a message, deleting all messages, and modifying a message, respectively. In a user application, you need a class that implements the methods of this interface: messageAdded(Message, Message), messageRemoved(Message), allMessagesRemoved(), messageChanged(Message, Message).

    Example Usage:

    public class MainActivity extends AppCompatActivity {
        private RoxSession session;
        private ListController listController;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            roxChatSession = Rox.newSessionBuilder()
                .setAccountName(ACCOUNT_NAME)
                .setLocation(LOCATION_NAME)
                .build()
            initChatView(rootView);
        }
        private void initChatView(View rootView) {
            RecyclerView recyclerView = rootView.findViewById(R.id.chat_recycler_view);
            listController = ListController.install(this, recyclerView);
        }
        private static class ListController implements MessageListener {
            private static final int MESSAGES_PER_REQUEST = 25;
            private final RecyclerView recyclerView;
            private final MessagesAdapter adapter;
            static ListController install(RoxChatFragment roxChatChatFragment,
                                          RecyclerView recyclerView) {
                return new ListController(roxChatChatFragment, recyclerView);
            }
            private ListController(final RoxChatFragment roxChatChatFragment,
                                   final RecyclerView recyclerView) {
                this.recyclerView = recyclerView;
                this.adapter = new MessagesAdapter(roxChatChatFragment);
                this.recyclerView.setAdapter(this.adapter);
            }
            @Override
            public void messageAdded(@Nullable Message before, @NonNull Message message) {
                int index = (before == null) ? 0 : adapter.indexOf(before);
                if (index < = 0) {
                    adapter.add(message);
                    adapter.notifyItemInserted(0);
                } else {
                    adapter.add(index, message);
                    adapter.notifyItemInserted(adapter.getItemCount() - index - 1);
                }
            }
    
            @Override
            public void messageRemoved(@NonNull Message message) {
                int index = adapter.indexOf(message);
                if (index != -1) {
                    adapter.remove(index);
                    adapter.notifyItemRemoved(adapter.getItemCount() - index);
                }
            }
    
            @Override
            public void messageChanged(@NonNull Message from, @NonNull Message to) {
                int index = adapter.lastIndexOf(from);
                if (index != -1) {
                    adapter.set(index, to);
                    adapter.notifyItemChanged(adapter.getItemCount() - index - 1, 42);
                }
            }
    
            @Override
            public void allMessagesRemoved() {
                int size = adapter.getItemCount();
                adapter.clear();
                adapter.notifyItemRangeRemoved(0, size);
            }
        }
    }
    

    A list of all methods, as well as complete information about them, can be found in the description of MessageListener.

  3. The MessageTracker is required to retrieve the message history, which is stored on the local device. On the server the history of messages is stored without time limitation. The MessageTracker class object can be retrieved through the newMessageTracker(MessageListener) method of the MessageStream object:

    MessageTracker tracker = session.getStream.newMessageTracker(this);
    

    The newMessageTracker(MessageListener) method of the MessageStream object creates an object of the MessageTracker class, which can be used to control the flow of messages in the context of a client application. You can use the getLastMessages(int limit, GetMessagesCallback callback) method to retrieve the latest messages from the history, but not more than the specified limit.

    Example of using the method:

    int MESSAGES_PER_REQUEST = 25;
    tracker.getLastMessages(MESSAGES_PER_REQUEST, new MessageTracker.GetMessagesCallback() {
                    @Override
                    public void receive(@NonNull final List< ? extends Message> received) {
                        //your code
                    }
                });
    

    To further iterate over the message history, the getNextMessages(int limit, GetMessagesCallback) method is called - it requests a certain number of messages from the history.

    Example of using the method:

    int MESSAGES_PER_REQUEST = 25;
    tracker.getNextMessages(MESSAGES_PER_REQUEST, new MessageTracker.GetMessagesCallback() {
                    @Override
                    public void receive(@NonNull final List< ? extends Message> received) {
                        //your code
                    }
                });
    

    Message is required to store information about messages. Using methods of Message class instances it is possible to get all necessary data about a particular message: unique message number (getId() method), message text (getText() method), information about attached file (getAttachment() method), etc. The methods of the MessageListener interface operate on objects of the Message class. All tools related to this class (methods for working with attachments, message types, etc.) are described here.

    Detailed description of these and other methods can be found in the method guides for iOS and Android.

Step 3: Other Settings

In addition to installing the interfaces listed above, for correct operation of the application based on Rox.Chat Mobile SDK you need to make a number of settings in the application code.

  1. It is necessary to properly configure the visitor fields and hash counting procedure. The account private key should not be stored on the device or anywhere other than the customer's server. Otherwise, there is a serious security threat and the risk of leaking the customer's correspondence to third parties.

    Example of passing the json-encoded object of an SDK visitor:

    .setVisitorFieldsJson("{
        "id":"1234567890987654321",
        "display_name": "Nikita",
        "hash":"ffadeb6aa3c788200824e311b9aa44cb"
    }")
    
  2. An obfuscator can be used for an SDK-based application. In this case it is necessary to set exceptions in obfuscator rules so that certain classes are not obfuscated - this is necessary for correct work of the application based on Rox.Chat Mobile SDK. In particular, when using the Proguard obfuscator, you should set the following in its rules:

    -keep public class com.roxchat.android.sdk.* { *; }
    

    This will mean that the specified package/class will not be "encrypted" by the obfuscator.

  3. provide the necessary network accesses.

    For a mobile device running a mobile application integrated with the Rox.Chat Mobile SDK, outbound ports must be open for the following URLs:

    • https://*.rox.chat/l/v/m/action 443 (POST) - used to transmit actions from clients.

    • https://*.rox.chat/l/v/m/delta 443 (GET) - used to receive incremental updates.

    • https://*.rox.chat/l/v/m/download 443 (GET) (not used in SDK, but needed to download files in mobile app)

    • https://*.rox.chat/l/v/m/upload 443 (POST) - used to send files from client to server.

    • https://*.rox.chat/l/v/m/history 443 (GET) - used to get chat history from the database.

    The following ports must be open to send push notifications:

    If the chat is hosted on the customer's servers, the domain must be changed to their own.

  4. In order to allow the user to rate the operator's performance after the chat is finished, it is necessary to describe the corresponding mechanism in the application. SDK does not implement the evaluation mechanism, but gets it from the client application.

  5. Push notifications are enabled and configured (optional).

  6. The startChat() method may be called to start a chat. If the method is not called, the chat will be started after the visitor's first message.