Android - v9.1.0

Updated 

Note:

  1. Sprinklr Messenger for Android supports minimum API 23 without Video Call

  2. Sprinklr Messenger for Android supports minimum API 24 with Video Call

  3. Gradle version has been updated to 8.3.x and Android Gradle Plugin version has been updated to 8.1.x

Step 1: Install Sprinklr Messenger 

1. Add maven URL with https://clients-nexus.sprinklr.com/ the shared credentials in your root’s build.gradle.

allprojects {
  repositories {
      maven {
        url 'https://clients-nexus.sprinklr.com/'
      }
  }
}


2. Force react native version in your root’s build.gradle.

allprojects { 
    configurations.all { 
        resolutionStrategy { 
            dependencySubstitution { 
                it.substitute(it.module("com.facebook.react:react-native")) 
                        .using(it.module("com.facebook.react:react-android:0.75.4")) 
                it.substitute(it.module("com.facebook.react:hermes-engine")) 
                        .using(it.module("com.facebook.react:hermes-android:0.75.4")) 
            } 
            force "com.facebook.react:react-android:0.75.4", "com.facebook.react:hermes-android:0.75.4" 
        } 
    } 
} 


3. Add the following dependency to your app's build.gradle file

dependencies {
  implementation 'com.spr:messengerclient:9.1.0'
}


Note: Before you begin, please note that the clients have to change the version when Sprinklr updates the chat app. 


Step 2:  Add Permissions 

We include the INTERNET permission by default as we need it to make network requests- 

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

You will need to include the following permissions if you have enabled attachments -

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> 
<uses-permission android:name="android.permission.CAMERA" /> 
<uses-permission android:name="android.permission.RECORD_AUDIO" /> 

 

<!-- For android 13 and above --!>  
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> 


Step 3: Initialize the Messenger

Add the following in the onCreate() method of your Application class:

- For Anonymous Users

For anonymous chats you can initialize the messenger using the takeOff method. Behind the scenes we will automatically create the anonymous user for the messenger and initialize the flow for the same. Please note that the takeOff method should be called once in the application lifecycle. You can use separate methods for updating the user or various information in the messenger which are explained in other sections. For the best performance takeOff should be called at the root of the application or as early as possible in your application flow.

SPRMessenger sprMessenger = SPRMessenger.shared(); 
SPRMessengerConfig config = new SPRMessengerConfig(); 
config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr 

config.setAppKey("com.sprinklr.messenger.release"); // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.setDeviceId("UNIQUE_DEVICE_ID"); 
config.setPushAppId("SPR_PUSH_ID"); //Unique id, if not sure pass same as device ID 

config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg PROD2) 
config.setLocale("SPR_LOCALE"); // default value is en 

config.setSkin("MODERN"); // default value is CLASSIC, options: CLASSIC | MODERN 

config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT | DARK

 

sprMessenger.takeOff(this, config);


- For Authenticated Users

This step is done after the user logs in successfully and completes the authentication process within the application and after the authentication process, it should be passed in Sprinklr including the app id. In case, a user is not logged in case (s)he has never used the application then an anonymous user can be created for the same. 

After the authentication process, the client should pass the user bean, the application ID, the messenger activity including the information so that Sprinklr can begin the initial setup process in the background.
To initiate the process, following fields are needed -  

  1. id

  2. firstName

  3. lastName

  4. profileImageUrl

  5. phoneNo

  6. email

config.setLocale("SPR_LOCALE"); // defaulSPRMessenger sprMessenger = SPRMessenger.shared(); 
SPRMessengerUser user = new SPRMessengerUser(); 
user.setUserId("12345"); 
user.setFirstName("John"); 
user.setLastName("Doe"); 
user.setPhoneNumber("9876543210"); 
user.setEmail("John.Doe@example.com"); 
user.setProfileImageUrl("https://example.com/profilePic.jpg"); 
user.setHash("f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22"); // see it below 

 
SPRMessengerConfig config = new SPRMessengerConfig(); 

config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr 

config.setAppKey("com.sprinklr.messenger.release"); // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.setDeviceId("UNIQUE_DEVICE_ID"); 
config.setPushAppId("SPR_PUSH_ID");  //Unique id, if not sure pass same as device ID 

config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg. PROD2) 

config.setSkin("MODERN"); // default value is CLASSIC, options: CLASSIC | MODERN 

config.setLocale("SPR_LOCALE"); // default value is en

config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT | DARK
config.setUser(user.getUser()); 
sprMessenger.takeOff(this, config); 

        

Note: UserID and Hash are mandatory parameters and hash should be generated for every change in user object. To know the procedure of how to generate Hash, check Step - 9 Generate User Hash

- For Authenticated Custom Users​

This step is done to create a custom user account using custom or specific attributes. In other words, it involves creating user accounts with personalized details or characteristics 

Below is the example to initiate the process with custom attributes and Hash, where you can  pass the attributes values: 

  • Custom Attribute 1 

  • Custom Attribute 2 

  • Hash 

    SPRMessenger sprMessenger = SPRMessenger.shared(); 
    SPRMessengerConfig config = new SPRMessengerConfig(); 

    config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr 

    config.setAppKey("com.sprinklr.messenger.release"); // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

    config.setDeviceId("UNIQUE_DEVICE_ID"); 

    config.setPushAppId("SPR_PUSH_ID");  //Unique id, if not sure pass same as device ID 

    config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg. PROD2) 

    config.setSkin("MODERN"); // default value is CLASSIC, options: CLASSIC | MODERN 

    config.setLocale("SPR_LOCALE"); // default value is en

    config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT | DARK


     

    Map<String, Object> customUser = new HashMap<>(); 
    customUser.put("customAttribute1", "value1"); //Add your custom attribute 

    customUser.put("customAttribute2", "value2"); //Add your custom attribute 
    customUser.put("hash","8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"); 
    config.setCustomUser(customUser); 
     
    sprMessenger.takeOff(this, config); 

Note: If you wish to implement a Custom User Authentication Flow, kindly get in touch with the Sprinklr Team to initiate discussions about the implementation process.  

Step 4:  Show Messenger

Add the following code in onClick event of the messenger button present inside your application- 

SPRMessenger.shared().startApplication();


Step 5: Messenger Configurations

1) Update user

User attributes can be updated by calling, below is the sample configuration example - 

SPRMessengerUser user = new SPRMessengerUser();
user.setUserId("12345");
user.setFirstName("John");
user.setLastName("Doe");
user.setPhoneNo("9876543210");
user.setEmail("John.Doe@example.com");
user.setProfileImageUrl("https://example.com/profilePic.jpg");
user.setHash("f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22"); 

SPRMessenger.shared().updateUser(user);

Note: UserID and Hash are mandatory parameters and hash should be generated for every change in user object. 

2) Update Custom User 

Custom User attributes can be updated by calling, below is the sample configuration example: 

Map<String, Object> customUser = new HashMap<>(); 
customUser.put("customAttribute1", "value1"); 
customUser.put("customAttribute2", "value2"); 
customUser.put("hash","8cf5a3815eedc5305b53f2cb8c1785d46a94abe39cfb15bd26d1e1f75e66056a"); 
SPRMessenger.shared().updateCustomUser(customUser); 

3) Update language

To update the user language use below function:

SPRMessenger.shared().updateLocale(locale);

Sprinklr messenger supports the following languages: Arabic, Bokmal, Chinese, English, Thai, Turkish, Vietnamese, Portuguese, Spanish, Indonesian, Japanese, Korean, French. 

Few languages with limited availability are: Albanian, Norwegian, Bosnian, Chinese (traditional), Chinese (honk-kong), Croatian, Czech, Danish, Dutch, Estonian, Finnish, German, Hebrew, Hungarian, Italian, Latvian, Lithuanian, Macedonian, Malayalam, Polish, Romanian, Serbian, Slovak, Slovanian, Swedish.

4) Cleanup

You can logout the user and cleanup the associated data from the application by calling logout.

SPRMessenger.shared().logout();

5) Add support of video player

  • Install video player and react native

implementation 'com.sprinklr.externals:react-native-video:5.2.2'
implementation 'com.facebook.react:react-android:0.75.4'

  • Add video package to the messenger config

import com.brentvatne.react.ReactVideoPackage; // import statement for video package

config.setExtraPackages(new ArrayList<>(Arrays.asList(
  new ReactVideoPackage()
)));

[OPTIONAL]: If your app uses exo player and face build issues, install react-native-video instead of react-native-video-exoplayer

implementation 'com.sprinklr.externals:react-native-video:5.2.2'

6) Customize Messenger landing screen

By default, the messenger view opens with a home page displaying all conversations. However, you can customize this behavior and launch MessengerView with a single conversation view.

The following sections list the customization you can do with the default view and the single conversation view:

Default View

Sprinklr Live Chat comprises of two screens: the home screen and the conversation screen. By default, both screens are accessible when the Live Chat opens.

The following are the various ways you can customize the default view according to your use case:

By default, Live Chat opens on the home screen, including the conversation screen. Use the following code to open Live Chat in default view:

SPRMessenger.shared().startApplication();

When Live Chat is set to default view with NEW_CONVERSATION, it initiates a new conversation on behalf of the user, starting with the welcome messages set in the application builder.

To continue any existing conversations, users must return to the home screen.

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "NEW_CONVERSATION");


Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);


SPRMessenger.shared().startApplication(applicationLaunchBundle);

When Live Chat is set to default view with LAST_CONVERSATION, it opens the last conversation that is still open. If there are no open conversation, it initiates a new conversation on behalf of the user starting with the welcome messages set in the application builder.

To continue any existing conversations, users must return to the home screen.

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "LAST_CONVERSATION");

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use the following code to start a new conversation with a custom message from your brand or user, tailored to your specific needs.

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "NEW_CONVERSATION");

Bundle brandMessage = new Bundle();

brandMessage.putString("message", "This is a brand message");

brandMessage.putBoolean("isSentByUser", false);

Bundle userMessage = new Bundle();

userMessage.putString("message", "This is a user message");

userMessage.putBoolean("isSentByUser", true);

bundle.putParcelableArray("initialMessages", new Bundle[]{brandMessage, userMessage});

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

When you want to open a specific conversation (one that’s undeleted and has the most recent published message) for the user, use the captured ID (obtained by listening to events indicating the ongoing conversation).

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "EXISTING_CONVERSATION");


Bundle params = new Bundle();

params.putString("conversationId", "id_of_conversation");


bundle.putBundle("params", params);


Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use the following code to open a new conversation and automatically start a video call, enabling face-to-face interaction.

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "NEW_CONVERSATION");

bundle.putStringArray("initialMessages", new String[]{});

Bundle additional = new Bundle();

additional.putString("callType", "VIDEO");

bundle.putBundle("additional", additional);

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle); SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use the following code to open a new conversation with an automatically initiated audio call for real-time voice communication.

Bundle bundle = new Bundle();

bundle.putString("landingScreen", "NEW_CONVERSATION");

bundle.putStringArray("initialMessages", new String[]{});

Bundle additional = new Bundle();

additional.putString("callType", "AUDIO");

bundle.putBundle("additional", additional);

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

Single Conversation View

You can choose to display the single conversation view and hide the home screen completely.

The following are various ways you can customize the single conversation view according to your use case:

Use the following code to display only the conversation screen in Live Chat and hide the home screen

Note: The scope:'CONVERSATION' option limits Live Chat to only the conversation screen.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");


Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);


SPRMessenger.shared().startApplication(applicationLaunchBundle);

When Live Chat is set to single conversation view with NEW_CONVERSATION, it initiates a new conversation on behalf of the user, starting with the welcome messages set in the application builder.

It will always open a conversation pane by initiating a new conversation, and will eventually hide any previous chats that are currently open.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "NEW_CONVERSATION");


Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);


SPRMessenger.shared().startApplication(applicationLaunchBundle);

When Live Chat is set to single conversation view with LAST_CONVERSATION, it opens the last conversation that is still open. If there are no open conversation, it initiates a new conversation on behalf of the user starting with the welcome messages set in the application builder.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "LAST_CONVERSATION");

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use this code to open the single conversation view and start a new conversation with a custom message from your brand or user.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "NEW_CONVERSATION");

Bundle brandMessage = new Bundle();

brandMessage.putString("message", "This is a brand message");

brandMessage.putBoolean("isSentByUser", false);

Bundle userMessage = new Bundle();

userMessage.putString("message", "This is a user message");

userMessage.putBoolean("isSentByUser", true);

bundle.putParcelableArray("initialMessages", new Bundle[]{brandMessage, userMessage});

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

When you want to open a specific conversation without home page (one that’s undeleted and has the most recent published message) for the user, use the captured ID (obtained by listening to events indicating the ongoing conversation).

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "EXISTING_CONVERSATION");


Bundle params = new Bundle();

params.putString("conversationId", "id_of_conversation");


bundle.putBundle("params", params);


Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle);

SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use the following code to open the single conversation view with a new conversation and automatically start a video call for direct face-to-face communication.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "NEW_CONVERSATION");

bundle.putStringArray("initialMessages", new String[]{});

Bundle additional = new Bundle();

additional.putString("callType", "VIDEO");

bundle.putBundle("additional", additional);

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle); SPRMessenger.shared().startApplication(applicationLaunchBundle);

Use the following code to open the single conversation view with a new conversation and automatically start an audio call for real-time voice communication.

Bundle bundle = new Bundle();

bundle.putString("scope", "CONVERSATION");

bundle.putString("landingScreen", "NEW_CONVERSATION");

bundle.putStringArray("initialMessages", new String[]{});

Bundle additional = new Bundle();

additional.putString("callType", "AUDIO");

bundle.putBundle("additional", additional);

Bundle applicationLaunchBundle = new Bundle();

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle); SPRMessenger.shared().startApplication(applicationLaunchBundle);


7) Capture customer context when starting a new conversation from custom view

When chat is being opened from a custom view, sometimes you might want to capture additional context on the conversation/case. 

Example - A button called “Know More about this laptop”  near a laptop product which opens a chat with a predefined contextual welcome message - “Hi there! It looks like you are interested in buying a laptop”. At the same time, you might want to set the case custom fields indicating the “product category: laptop”, “case type: inquiry”.


To do this, 

i) Create the case custom fields and note down their field name →  (Right now it’s not possible to get the field name of custom fields from UI, you can work with support to get the relevant field name of the custom fields).

ii) Pass conversationContext to chatInitialisationContext* when opening a new conversation directly (5ea7fa9e87651f356209878f and 5eb7fa9e87651f356219348e are the two custom field names). All the field values should be passed as an array of strings.

Bundle conversationContext = new Bundle();
conversationContext.putStringArray("5ea7fa9e87651f356209878f", new String[] {"laptop"});
conversationContext.putStringArray("5eb7fa9e87651f356219348", new String[] {"inquiry"});
bundle.putBundle("conversationContext", conversationContext);

* Note: chatInitialisationContext is explained in previous section


8) Capture customer context from the application on all cases of the user

Sometimes you might want to pass some contextual information in case custom fields for all conversations started by the user.

To achieve this,

1. Create the case custom fields and note down their field name → (Right now it’s not possible to get the field name of custom fields from UI, you can work with support to get the relevant field name of the custom fields).

2. You can pass these values in clientContext in the takeOff method called in step 5.  (5e281d040844e435b is the custom field name). All the field values should be passed as an array of strings.

Bundle clientContext = new Bundle();
clientContext.putStringArray("5ea7fa9e87651f356209878f", new String[] {"laptop"});
clientContext.putStringArray("5eb7fa9e87651f356219348", new String[] {"inquiry"});

config.setClientContext(clientContext);


3. You can also update the client context on run time by calling the following method: All the field values should be passed as an array of strings.

Bundle clientContext = new Bundle();
clientContext.putStringArray("5ea7fa9e87651f356209878f", new String[] {"laptop"});

SPRMessenger.shared().updateClientContext(bundle);


9) Update Conversation Context (Case Custom Field) on Demand ​

At times you might want to update the value of conversation context/case custom field during or after a conversation. 

Example: After a purchase is made on the website you might want to set the transaction amount or id on the case for reporting. After doing this, you can attribute sales to each conversation/case. 

To do this, 

  1. Create the case custom fields and note down their field name1. 

  2. Whenever you want to update the case custom field, call the following JavaScript function (5e291d040844e435b is the custom field name). 

Bundle context = new Bundle();
context.putStringArray("5ea7fa9e87651f356209878f", new String[] {"laptop"});
context.putStringArray("5eb7fa9e87651f356219348", new String[] {"inquiry"});


Bundle conversationContext = new Bundle();
conversationContext.putBundle("context", context);


SPRMessenger.shared().updateConversationContext(conversationContext);

10) Update the profile context within Profile Custom Fields 

When chat is being opened from a custom button or hyperlink, sometimes you might want to capture some context on the profile/user during the conversation or after the conversation.

To do this, 

  1. Create the profile custom fields and note down their field name. 

  2. Whenever you want to update the profile custom field, call the following JavaScript function and pass the information for profile level custom fields. This can be done via sdk for updating it on-demand.

 ​

Bundle userContext = new Bundle();
userContext.putStringArray("5ea7fa9e87651f356209878f", new String[] {"laptop"});
userContext.putStringArray("5eb7fa9e87651f356219348", new String[] {"inquiry"});
SPRMessenger.shared().updateUserContext(userContext);

11) Close Messenger

You can close messenger from the main application by calling closeMessenger

SPRMessenger.shared().closeMessenger();

12) Add Delegate to listen to external events from messenger

SPRMessenger.shared().setMessengerDelegate(new SPRMessengerDelegate() {
@Override
public void handleExternalAction(HashMap<String, Object> payload) {}
});

13) Get number of open conversations

Sometimes you might want to hide the live chat widget based on the number of open conversation.  To do this,  

  • Call the the below function to get the number of open conversations

SPRMessenger.shared().getNumberOfOpenConversations(); 

  • Add Delegate to listen to the output of above function  

 

 SPRMessenger.shared().setMessengerDelegate(new SPRMessengerDelegate() {  
@Override  
public void onUpdateNumberOfOpenConversations(Integer integer) {  
  
  }  
});  

14) Get number of unread messages 

You can keep track of changes in the total number of unread messages in conversations by using a delegate that accepts responses of type SPRMessagesCountResponse. This way, you'll get notified whenever there's a change in the unread message count. It's a convenient way to stay updated on unread message counts in real-time. 

 

 import com.spr.messengerclient.config.bean.SPRUnreadMessagesCountResponse

… 

 

SPRMessenger.shared().setMessengerDelegate(new SPRMessengerDelegate() {    

 @Override  
public void onUpdateUnreadMessagesCount(SPRUnreadMessagesCountResponse response) { 
  Boolean success = response.getSuccess()
  if (success) { 
    int unreadCount = response.getUnreadMessagesCount()

    // Your Logic 

 
  } else

    String errorMessage = response.getError().getMessage()

    // Handle error logic 

 
 

 
});  

You can also trigger the event to get the current unread messages count by calling following method: 

SPRMessenger.shared().getUnreadMessagesCount(); 

 

Note: You would receive the current unread messages count response in the onUpdateUnreadMessagesCount method of the delegate you attached earlier. 

15) Add Messenger Analytics Handler to Listen to tracking events and screen

SPRMessenger.shared().setMessengerAnalyticsHandler(new SPRMessengerAnalyticsHandler() { 
@Override 
public void trackEvent(String eventType, String payload) {
 
@Override 
public void trackScreen(String ) {} 
}); 

16) Add Messenger Events Listener to SDK events 

The following events can be listened: 

Event Type:

  1. BOOT_FAILED

  2. BOOT_STARTING

  3. BOOT_COMPLETE

  4. USER_LOGOUT

  5. SSL_CERTIFICATE

  6. UPDATE_USER_FAILED

  7. UPDATE_USER_SUCCESS

  8. UPDATE_USER_CONTEXT_FAILED

  9. UPDATE_CLIENT_CONTEXT_FAILED

  10. ANONYMOUS_SESSION_CREATION_STARTING

  11. ANONYMOUS_SESSION_CREATION_SUCCESS

  12. ANONYMOUS_SESSION_CREATION_FAILED

  13. UPDATE_USER_STARTING

Event Type: INTERNET_CONNECTION_STATUS_CHANGED

Event Type:

  1. PUSH_NOTIFICATION_REGISTRATION_EXISTS

  2. PUSH_NOTIFICATION_REGISTRATION_SUCCESS

  3. PUSH_NOTIFICATION_REGISTRATION_FAILED

  4. PUSH_NOTIFICATION_UNREGISTRATION_SUCCESS

  5. PUSH_NOTIFICATION_UNREGISTRATION_FAILED

Event Type:

  1. NEW_CONVERSATION_INITIATION_FAILED

  2. CONVERSATION_CLOSED

  3. CONVERSATION_DELETED

  4. CONVERSATION_CLOSE_FAILED

  5. CONVERSATION_DELETE_FAILED

  6. CONVERSATION_CLOSED_BY_AGENT

SPRMessenger.shared().setMessengerEventsListener(new
SPRMessengerEventsListener() {
  @Override
  public void onEvent(String eventGroup, String
eventType, String eventPayload) {}
});

17) Add Events Logger to SDK Events

The provided code snippet establishes a custom logging system which can handle logging events at different levels. This setup enables us to efficiently track and manage various events within the app.

SPRLoggerConfig sprLoggerConfig = new
SPRLoggerConfig()
.setLevel(SPRLoggerConfig.SPRLogLevel.SPR_INFO) // optional, default
level is SPRLogLevel.SPR_INFO

  
.setEnableLogs(true) // required to enable logs
.setLoggerTransport((level, logs) -> {
// your custom logger transport

   }); // required to set native logger transport

SPRMessengerConfig config = new SPRMessengerConfig();

// set other config

config.setLoggerConfig(sprLoggerConfig);

The following log levels are maintained:

SPR_OFF(0), SPR_FATAL(1), SPR_ERROR(2), SPR_WARN(3), SPR_INFO(4), SPR_DEBUG(5), SPR_TRACE(6), SPR_ALL(7);

18) Update Theme Mode for User on demand

 You can update the theme mode ondemand:

SPRMessenger.shared().updateThemeMode("DARK"); // options: DEFAULT | DARK

Note: Upon invoking the updateThemeMode() method, a confirmation alert will prompt the user to reload the app for the changes in theme to take effect. Furthermore, the parent application should send the updated theme within the configuration while chat initialization

19) Configure your Status Card

Note: To get this capability enabled, please reach out to our support team at tickets@sprinklr.com, providing the live chat application ID. Status Card can be enabled only if you are using the modern skin version of live chat widget.

Using Status Cards, you can update your customers about the health of a key resource. This key resource could be a tool or service that they interact with frequently. By showing the status of this resource directly, customers don’t have to reach to agents repeatedly. Hence, this improves the customer experience while reducing agent workload.

Once status card is enabled for your Livechat widget, you can update the status card by using the following:

SPRMessengerWidgetDetailsConfig widgetDetailsConfig = new SPRMessengerWidgetDetailsConfig();

widgetDetailsConfig.setTitle(“Your title, %%[status]”);

widgetDetailsConfig.setDescription(“Your description, %%[updatedAt]”);

widgetDetailsConfig.setStatus(SPRMessengerWidgetDetailsConfig.SPRStatus.ALL_SYSTEMS_OPERATIONAL);

widgetDetailsConfig.setUpdatedAt(System.currentTimeMillis());

 

SPRMessenger.shared().updateWidget(“WIDGET_ID”, widgetDetailsConfig); // Same ID configured in the Live Chat builder must also be utilized here

You can use the following placeholders for title and description:

  1. %%[updatedAt] --> Placeholder for formatted time

  2. %%[status] --> Placeholder for Status, mentioned below in the table as SPRStatus


Status Placeholder Value


Icon



SPRStatus



All Systems Operational





ALL_SYSTEMS_OPERATIONAL



Service Under Maintenance





SERVICE_UNDER_MAINTENANCE



Partially Degraded Service





PARTIALLY_DEGRADED_SERVICE



Degraded System Service





DEGRADED_SYSTEM_SERVICE



Partial System Outage





MINOR_SYSTEM_OUTAGE



Minor System Outage





PARTIAL_SYSTEM_OUTAGE



Major System Outage





MAJOR_SYSTEM_OUTAGE


20) Disable Attachments for Customer

 You can prevent customers from adding attachments in the chat by hiding the attachment icon from the chat widget.


To do this, you can pass disableAttachment:true in the takeOff method

config.setDisableAttachment(true); // by default, attachments are enabled

21) Integrate Your Brand's Custom Header in Live Chat 

  

Enhance your live chat experience by incorporating your own custom header. This allows you to replace Live Chat default header with one that aligns with your brand identity, creating a consistent and seamless experience for your users. 

Bundle bundle = new Bundle(); 

bundle.putBoolean(“disableHeader”, false); // Default: false. To disable Sprinklr's header, set to true 

 

bundle.putBoolean(“isRenderedAsFullView”, true); // Default: true. If set to false, the brand must manage device top insets 

  

Bundle applicationLaunchBundle = new Bundle(); 

applicationLaunchBundle.putBundle("chatInitialisationContext", bundle); 

  

SPRMessenger.shared().startApplication(applicationLaunchBundle); 

 

 

22) Implement Back Button Handling to Control Hardware Back Button 

 Utilize the below method to handle the back action within your chat application. This function allows users to seamlessly navigate back to the previous screen, enhancing the overall user experience by providing intuitive and efficient navigation 

SPRMessenger.shared().goBack(); 

 

23) Close Conversation 

 Use the method below to close a conversation on live chat. This feature allows brands to efficiently handle conversation endings, providing control over when and how interactions are closed. 

Apply this method only on the conversation screen when the case is open to ensure a seamless transition for users as conversations end. 

SPRMessenger.shared().closeConversation(); 

23) Close All Conversations 

Use the method below to close all conversation on live chat. This option is visible to users with open cases, if there are no cases or all existing cases are already closed then user will not be able to see this option.

SPRMessenger.shared().closeAllConversations();

 

24) Delete Conversation 

Use this method to delete a conversation in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions.  

Apply this method only on the conversation screen to manage deletions effectively. 

SPRMessenger.shared().deleteConversation(); 

 

25) Delete All Conversations 

Use this method to delete all the conversations in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions. Apply this method only on the home screen to manage deletions effectively. 

SPRMessenger.shared().deleteAllConversations();

 

26) Clear User Session

You can now enable users to clear their session details. When a user clears their session, any new conversations will be treated as if they are from a completely new user. This feature is especially useful for users interacting with your brand in public spaces or over a public network.

SPRMessenger.shared().clearSession();

27) Use a Custom Font

You can use a custom font in your Live Chat app to ensure consistent branding across your applications. 

​To use a custom font in Live Chat, follow these steps:

  1. Link your custom font files in your Android project natively, such that the fonts are available throughout the project. For steps, see Android documentation.

  2. Open a Sprinklr support ticket at tickets@sprinklr.com. In the support ticket, mention the font file names and the supported font weights for the texts. Refer to the following table for the supported font weights.

Note: Ensure you provide at least one of the supported font weights in the support ticket. If you provide a single font weight, it will be applied throughout the app, overriding all the other font weights. 

Similarly, if any of the font weights are not mentioned in the support ticket, the font weight closest to the non-mentioned font weight will be applied in the app.

Supported font weights​

The following table lists the supported font weights:

Font weight

Description

Light

The light font weight is for subtle accents, secondary text, and areas where minimal emphasis is required.

Regular

The standard font weight for most text elements.

Medium

Medium is used for subheadings, labels, or emphasis on certain text sections without the bold impact.

Semibold

Works well for headings, button labels, or any text that needs more attention but doesn’t require bold styling.

Bold

Bold is designed for titles, primary headings, and call-to-action elements.

Step 6: Push Notifications

For more details on mobile push notifications, please refer here

Prerequisite

  1. Google service.json file

Note:

  • Google service.json file can be different for sandbox/prod env.

  • If the Google service.json file is different sandbox/prod env and you are testing the push notification setup on prod mobile application, plesae ensure to use Android release build

Configuration

To enable push notifications on Android(ARN Setup), please raise a support ticket to tickets@sprinklr.com with the following information:

  1. Google service.json file

  2. Live Chat AppID

  3. Partner ID

  4. Env

1) Register/Unregister for push notifications- 

You can register the messenger for sending push notifications by providing push token received from apns/fcm as below:

SPRMessenger.shared().pusher().setRegistrationToken(token);

You can unregister for messenger push notifications by sending empty token as below:

SPRMessenger.shared().pusher().setRegistrationToken("");


2) Handle Messenger Push Notifications

  • Once you have registered for messenger push notifications then you might receive notifications from your platform as well as messenger. To check if notification is messenger notification you can check as below:

Boolean isMessengerNotification = SPRMessenger.shared().pusher().canHandlePushEvent(remoteData); // remote data is fcm RemoteMessage received in onMessageReceived of firebase service

  • Once you have identified if the notification is messenger notification you need to follow the below step to handle push notification.

SPRMessenger.shared().pusher().handlePushEvent(this, remoteData);

  • You can now open the conversation screen directly from a push notification when the app is in the background and the Messenger SDK is mounted.

SPRMessenger.shared().pusher().handlePushNotification(remoteData);

3) Open Live Chat Messenger

Open live chat view with initial notification: Messenger view can be presented with initial notification as the result of opening from notifications or in-app notification banners:

Bundle notificationBundle = new Bundle();
notificationBundle.putString("type", SPRMessenger.LaunchType.NOTIFICATION.toString());
notificationBundle.putBundle("data", notificationData);

Bundle appLaunchBundle = new Bundle();
appLaunchBundle.putBundle("launchOptions", notificationBundle);
SPRMessenger.shared().startApplication(appLaunchBundle);

4) Controlling Push Notification Permissions

Note: Below Step 1 and Step 2 should be done before takeOff()

 

Prior to initializing the Messenger, you have the option to contol push notifications based on the user's app settings and permission request, provided your app has already obtained permission from the user.

1) To deactivate the push notifications according to the user’s application setting or if the user has not granted notification permission to your application:

SPRMessenger.shared().pusher().setNotificationEnabled(false); // Disable if app settings are disabled

 

2) The live chat application will never request notification permission again if it has already been granted. When your application has not obtained notification permissions and if you also wish to prevent the live chat application from requesting notification permission when 'takeOff' is called, you can set the 'autoRequestPermission' parameter to false.

SPRMessenger.shared().pusher().setAutoRequestNotificationPermissions(false);

// App will not ask the permission for push notifications

3) Whenever the user has granted notification permission to your application, we need to ensure that the push notifications for live chat application are also enabled. To do this:

SPRMessenger.shared().pusher().setNotificationEnabled(true);

5) Customizing Notification preferences 

Brands can customize various aspects of Push notifications.  

1. Customize the icons according to your preference 

Brands have the flexibility to customize the small, large, and call icons for Push notifications based on their preferences. Please find the relevant code below for reference. 

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 
 
notificationPreference.setSmallIcon(R.drawable.notification_icon); 
notificationPreference.setLargeIcon(R.drawable.notification_icon); 
notificationPreference.setCallIcon(R.drawable.call_icon); 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference);

2. Customize Sound for Push Notifications 

Brands have the option to enable a custom sound for their Push notifications. Please find the relevant code below for reference. 

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 

 
Uri soundUri = Uri.parse("android.resource://" + this.getPackageName() + "/"+ R.raw.notification_sound); 

  

notificationPreference.setSound(soundUri); 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference); 

3. Disable Sound 

Brands have the option to disable sound for Push notifications based on their preferences. Please find the relevant code below for reference. 

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 

 
notificationPreference.setSoundDisabled(true); default value is false 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference); 

 

Step 7: In-App Push Notifications

In-app notifications are messages or alerts displayed within a mobile application itself, rather than on the device's main notification tray or lock screen. These notifications are specifically tailored to communicate information directly to the user while they are actively engaged with the app. 

1) Enable/Disable In-App Notifications 

By default, in-app notifications are enabled. To disable or enable in-app notifications again for Sprinklr Live Chat, please contact Sprinklr Support at tickets@sprinklr.com. Be sure to raise separate support tickets for sandbox and production environments. 

 

2) Customizing Notification preference 

Brands can customize various aspects of In-App notifications. To configure these settings, please refer to the code provided below: 

1. Customize the small, large and call icons according to your preference 

Brands have the flexibility to customize the small, large, and call icons for In-App notifications based on their preferences. Please find the relevant code below for reference. 

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 
 
notificationPreference.setSmallIcon(R.drawable.notification_icon); 
notificationPreference.setLargeIcon(R.drawable.notification_icon); 
notificationPreference.setCallIcon(R.drawable.call_icon); 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference);

  

2. Customize Sound for Push Notifications 

Brands have the option to enable a custom sound for their In-App notifications. Please find the relevant code below for reference.

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 

 
Uri soundUri = Uri.parse("android.resource://" + this.getPackageName() + "/"+ R.raw.notification_sound); 

  

notificationPreference.setSound(soundUri); 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference);

  

3. Disable Sound  

Brands have the option to disable sound for In-App notifications based on their preferences. Please find the relevant code below for reference.

SPRNotificationPreferences notificationPreference = new SPRNotificationPreferences(); 

 
notificationPreference.setSoundDisabled(true); default value is false 

SPRMessenger.shared().pusher().setNotificationPreferences(notificationPreference); 

 


Step 8: Enable SSL Pinning 

Enable SSL Pinning and Public key provided by sprinklr by creating SPRSSLPinning object and pass it to SPRMessengerConfig 

SPRMessenger sprMessenger = SPRMessenger.shared();

SPRMessengerConfig config = new SPRMessengerConfig();

config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr 

config.setAppKey("com.sprinklr.messenger.release"); // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

config.setDeviceId("UNIQUE_DEVICE_ID"); 

config.setPushAppId("SPR_PUSH_ID");  //Unique id, if not sure pass same as device ID 

config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg. PROD2) 

config.setSkin("MODERN"); // default value is CLASSIC, options: CLASSIC | MODERN 

config.setLocale("SPR_LOCALE"); // default value is en

config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT | DARK

SPRSSLPinningConfig sprsslPinningConfig = new SPRSSLPinningConfig();

sprsslPinningConfig.setEnabled(true);

sprsslPinningConfig.setPublicKey("SPR_PUBLIC_KEY"); // This will be provided by sprinklr

config.setSslPinningConfig(sprsslPinningConfig);

sprMessenger.takeOff(this, config);

 Note: Please raise a support ticket to tickets@sprinklr.com for generating the Public Key

 

Step 9: Taking video call on messenger

Note: Please follow the below Step 8 - Taking video call on messenger if you are using Video Calls

Video call is a feature that allows brands to make video calls on the mobile application. Video calls can be initiated by agents. Sprinklr provides video call solution in integration with 1 vendor as of today i.e. with Zoom.

Pre-Requisites

  1. Zoom account

  2. Permission to access to care console in the Sprinklr platform

Note: You can enable Zoom account to make and receive video calls by reaching out to Sprinklr support at tickets@sprinklr.com

Pricing

  1. Video call solution has a usage-based pricing i.e. per minute per participant costs. Eg- a call between an agent and a customer makes 2 participants

  2. Zoom charges $0.0034 per minute per attendee (one attendee is an agent and the other is a customer)

Note: 

  • Checkout out permission which is required for video call in Step 2 

  • Step 6 is mandatory for this

  • Sprinklr Messenger for Android supports minimum API 24 with Video Call 

  1. Install zoom sdk and react native

    implementation 'com.sprinklr.externals:zoom-react-native-videosdk:1.11.0'

    implementation 'com.facebook.react:react-android:0.75.4' 

  2. Add video package to the messenger config 

    import com.reactnativezoom.videosdk.RNZoomVideoSdkPackage; 

    // import statement for zoom sdk package 

  3. Create config for takeOff as done in Step 3

    SPRMessenger sprMessenger = SPRMessenger.shared();  
    SPRMessengerConfig config = new SPRMessengerConfig();  
    config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr  

    config.setAppKey("com.sprinklr.messenger.release");  // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.

    config.setDeviceId("UNIQUE_DEVICE_ID");  
    config.setPushAppId("SPR_PUSH_ID"); //Unique id, if not sure pass same as device ID  

    config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg PROD2)  
    config.setLocale("SPR_LOCALE"); // default value is en

    config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT| DARK

    sprMessenger.takeOff(this, config); 

      

  4. Pass RNZoomVideoSdkPackage 

    config.setExtraPackages(new ArrayList<>(Arrays.asList( 

        new RNZoomVideoSdkPackage() 

    ))); 

  5. Pass video call provider to SPRMessengerConfig 

    config.setVideoCallProvider(SPRVideoCallProviders.ZOOM); 

  6. Set theme color to display accept call action icon in call view

    SPRThemeConfig themeConfig = new SPRThemeConfig(); 

    themeConfig.setPrimaryColor(Color.parseColor("#0828cc")); // Default Value is black 

    themeConfig.setSecondaryColor(Color.parseColor("#0828cc")); // Default Value is white if primary color is on darker side and black if primary color is on lighter side 

     

    config.setThemeConfig(themeConfig); 

  7. Call takeOff with all the configs defined above 

    sprMessenger.takeOff(this, config); 

Step 10: Enable Co-Browsing

Co-browsing will allow agents to get full visibility into the customer’s screen, enabling them to guide customers through product purchases, complex form filling, or confusing information on mobile application. For more details, please refer here.

 

Prerequisite

To enable co-browsing, please raise a support ticket at tickets@sprinklr.com with the following details

  • Partner Name

  • Partner ID

  • Concurrent co-browsing sessions expected

  • Number of agents who will be using co-browsing (Concurrent sessions)

 

1) Install co-browsing sdk and react native

implementation 'com.facebook.react:react-android:0.75.4'
implementation 'com.sprinklr.externals:cobrowse-sdk-react-native:2.18.2'

implementation 'io.cobrowse:cobrowse-sdk-android:2.30.3'

2) Add Co-Browsing package to the messenger config

import io.cobrowse.reactnative.CobrowseIOPackage; // import statement for co-browsing sdk package

3) Create config for takeOff as done in Step 3

SPRMessenger sprMessenger = SPRMessenger.shared(); 
SPRMessengerConfig config = new SPRMessengerConfig(); 
config.setAppId("SPR_APP_ID"); // This will be provided by sprinklr
config.setAppKey("com.sprinklr.messenger.release"); // Should be "com.sprinklr.messenger.adhoc" for staging/dev builds.
config.setDeviceId("UNIQUE_DEVICE_ID");
config.setPushAppId("SPR_PUSH_ID"); //Unique id, if not sure pass same as device ID

config.setEnvironment("SPR_ENVIRONMENT"); // This will be provided by sprinklr (eg PROD2)
config.setLocale("SPR_LOCALE");// default value is en

config.setSkin("MODERN"); // default value is CLASSIC, options: CLASSIC | MODERN
config.setThemeMode("DEFAULT"); // default value is DEFAULT, options: DEFAULT| DARK

sprMessenger.takeOff(this, config);

4) Pass Co-Browsing Package and set co-browsing flag to true

config.setExtraPackages(new ArrayList<>(Arrays.asList(

new CobrowseIOPackage()

)));

config.setCobrowsingEnabled(true);

Step 11: Generate User Hash

The userHash is a generated HMAC or Hash-based Message Authentication Code. For HMAC Sprinklr uses the sha256 hash function. You need to generate HMAC for the following "string" of user details. User details are concatenated to form a string, separated by underscore as shown below -

userId_firstName_lastName_profileImageUrl_phoneNo_email

So for the above example, the string for which you need to generate the hash would be

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com

Sample function to generate hash in Java - 


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.xml.bind.DatatypeConverter;

class Main {
public static void main(String[] args) {
try {
      String key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";
      String message = "12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com";

      Mac hasher = Mac.getInstance("HmacSHA256");
      hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
      byte[] hash = hasher.doFinal(message.getBytes());
 
      System.out.println((DatatypeConverter.printHexBinary(hash)).toLowerCase());
  }
  catch (NoSuchAlgorithmException e) {}
  catch (InvalidKeyException e) {}
}
}


Run the above Java code online - https://repl.it/@AbhishekPriyam/HMACJavaExample

The secret key which is used in HMAC for your application can be found on the Sprinklr platform inside live chat application as shown below (displayed as API Key).


Note:

  • UserID and Hash are mandatory parameters and hash should be generated for every change in user object. 

  • User details are supposed to be concatenated to form a string, separated by underscore as shown below:

userId_firstName_lastName_profileImageUrl_phoneNo_email

  •  If you don’t have a few values, you need not send anything but keep the underscores as is. For example, let’s say you don’t have profileimageUrl, there will be 2 underscores after lastName. The string will be as shown below: 

userId_firstName_lastName__phoneNo_email

Troubleshooting 

If you are not able to see the application after following all the above-mentioned steps then look for the following errors- 

1) More than one file was found with OS independent path

Add the following lines to your app's build.gradle file - 

android {
    packagingOptions {
        pickFirst 'lib/armeabi-v7a/*.so'
        pickFirst 'lib/arm64-v8a/*.so'
        pickFirst 'lib/x86/*.so'
        pickFirst 'lib/x86_64/*.so'
        exclude 'META-INF/LICENSE'
    }
}

 2) Dex Archive Builder Exception

If you face build error of this type - 

"Com.android.builder.dexing.dexarchivebuilderexception"

Then, Include the below mentioned code in app/build.gradle

android {
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

3) If your build fails due to Lint Error then add

android {
  lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
  }
}

4) If you are unable to load the live chat screen and see an infinite loader or error screen, then check following

  • Reach out to product team to set the "enforceSecurity" flag to false for your live chat application

5) LiveChat not showing up while passing authenticated user details 

Check the expected hash for any authenticated user passed inside chat settings. 

  1. Hover over the Options icon alongside your Live Chat Application and select Validate User Hash

     

  2. On the Validate User Hash window, enter User ID, Profile Image URL, First Name, Last Name, Phone Number and Email. Click Copy Generated Hash and verify it with the hash generated by you. 

     

 

6) Check if correct FCM Server key is being used for push notifications using Open API of FCM

​Please use the following curl with your FCM server key and registration device token, to check if the FCM Server key is correct or not:

/curl --location 'https: //fcm.googleapis.com/fcm/send' \--header 'Content-Type: application/json' \--header 'Authorization: key=<YOUR_FCM_SERVER_KEY>' \--data '{    "to": "<REGISTERED_DEVICE_TOKEN>",    "data": {        "title": "Title", //Title of the push notification        "message": "New Message" //Message of the push notification    }}'