public class

ConversationClient

extends Object
java.lang.Object
   ↳ com.nexmo.sdk.conversation.client.ConversationClient

Class Overview

You use a ConversationClient instance to utilise the services provided by Conversation API in your app. A session is the period during which your app is connected to Conversation API. Sessions are established for the length of time given when the authToken was created. Tokens also have a lifetime and can optionally be one-shot which will allow a single login only, before the authToken becomes invalid for another login attempt. If the authToken is revoked while a session is active the session may be terminated by the server. It is only possible to have a single session active over a socket.io connection at a time. Session multiplexing is not supported.

Note: The connection uses socket.io for both web and mobile clients. Upon a successful socket.io connection the client needs to authenticate itself. This is achieved by sending a login request via ConversationClient#login(String, RequestHandler)

Unless otherwise specified, all the methods invoked by this client are executed asynchronously.

For the security of your Nexmo account, you should not embed directly your Conversation credential authToken as strings in the app you submit to the Google Play Store.

First step is to acquire a ConversationClient instance based on user credentials.

To construct a ConversationClient the required parameters are:

  • applicationContext: The application context.

Example usage:

     ConversationClient myClient = new ConversationClient.ConversationClientBuilder()
                     .context(applicationContext)
                     .build();

     myClient.login("authToken", new RequestHandler {
         @Override
         public void onSuccess(User user) {
              // Update the application UI here if needed.
         }
         @Override
         public void onError(NexmoAPIError code error) {
              // Update the application UI here if needed.
         }
    });
 

Conversations synchronisation is done during login, for listening to sync event subscribe to a synchronisationEvent(). When sync is done conversation list can be retrieved synchronously from getConversationList()}

     myClient.synchronisationEvent().add(new ResultListener) {
         @Override
         public void onSuccess(SynchronisingState.STATE state() {
              // Update the application UI here if needed with entire list.
         }
         @Override
         public void onError(NexmoAPIError error) {
              // Unrecoverable error, update UI with some information from error.
         }
    });
 

The list of active conversations can be retrieved asynchronously via ConversationClient#getConversations(RequestHandler>).

Example usage, performing a ConversationClient#getConversations(RequestHandler>) for the logged in user:

     myClient.getConversations(new RequestHandler> () {
         @Override
         public void onSuccess(List conversations) {
              // Update the application UI here if needed.
         }
         @Override
         public void onError(NexmoAPIError error) {
              // Update the application UI here if needed.
         }
    });
 

Joining a conversation is done via Conversation#join(RequestHandler)

Note: any User that joins a Conversation becomes a Member.

Example usage:

     myConversation.join(new RequestHandler() {
         @Override
         public void onSuccess(Member member) {
              // Update the application UI here if needed. From now on the member may send messages in this conversation.
         }
         @Override
         public void onError(NexmoAPIError error) {
              // Update the application UI here if needed.
         }
    });
 
Remember to logout when needed in order to remove current user and disconnect from the underlying socket connection.

Example usage:

     myClient.logout(new RequestHandler() {
         @Override
         public void onSuccess(User user) {
              // Update the application UI here if needed.
         }
         @Override
         public void onError(NexmoAPIError error) {
              // Update the application UI here if needed.
         }
    });
 
Remember to disconnect when needed in order to disconnect from the underlying socket connection. Use this method when your app is not being used. In order to revoke a disconnect, a new Login must be performed.

Example usage:

     myClient.disconnect();
 

Summary

Nested Classes
class ConversationClient.ConversationClientBuilder API for creating ConversationClient instances. 
class ConversationClient.ConversationClientConfig POJO which contains current configuration (has to be built by Builder) First step is to acquire a ```ConversationClient``` instance based on a context. 
class ConversationClient.IPSHeader HTTP headers to be provided to access IPS service's media  
Public Methods
void call(List<String> users, RequestHandler<Call> callCreateListener)
Initiate an outbound call to multiple app users.
EventSource<Call> callEvent()
Register for receiving incoming Call events.
void callPhone(String phoneNumber, RequestHandler<Call> callStateListener)
Initiate an outbound call to a specific phone number.
void disconnect()
Explicitly disconnect the socket connection.
void enableAllPushNotifications(boolean enable, RequestHandler<Void> pushEnableListener)
Enable or Disable any push notifications triggered by any of the available conversations, using Firebase Cloud Messaging.
void enablePushNotificationsForConversation(boolean enable, String conversationId, RequestHandler<Void> pushEnableListener)
NOTE This is not yet implemented service-side! Enable or Disable push notifications for certain conversations.
Call getCall(String cid)
Get call based on conversation unique ID, synchronously.
ConversationClient.ConversationClientConfig getConfig()
Get config used to build ConversationClient.
Context getContext()
Get the context we used for building ConversationClient#config.
Conversation getConversation(String cid)
Get conversation based on unique ID, synchronously.
List<Conversation> getConversationList()
Get list of active conversation where user has been either invited, or joined, synchronously.
void getConversations(RequestHandler<List<Conversation>> conversationListListener)
Reload conversation list.
NetworkState getNetworkingState()
Check whether the ConversationClient is trying to connect to the backend socket or not.
String getPushDeviceToken()
Retrieve the push registration token that was once set.
RequestHandler<Void> getPushEnableListener()
static String getSDKversion()
Returns the current version of the Nexmo Conversation SDK.
SynchronisingState.STATE getSynchronisingState()
Get the current synchronising State.
String getToken()
Get the last used jwt for login.
final User getUser()
Get the current logged in User if available.
void getUser(String userId, RequestHandler<User> userInfoListener)
Get user info for given userId.
EventSource<Invitation> invitedEvent()
Register for receiving invitation events from new conversations.
List<ConversationClient.IPSHeader> ipsHeaders()

If you rely on your own mechanism for downloading images - instead of download(ImageRepresentation.TYPE, RequestHandler) - bear those custom headers in mind, so your request is authorized.

boolean isLoggedIn()
Check whether a User has been successfully logged in.
EventSource<Conversation> joinedToNewConversationEvent()
void listenToConnectionEvents(NetworkingStateListener listener)
Attach a listener for connection events.
void login(String token, RequestHandler<User> loginListener)
Login this ConversationClient instance based on the builder information and login details.
void logout(RequestHandler logoutListener)
Logout current user.
void newConversation(String conversationName, RequestHandler<Conversation> conversationCreateListener)
Create a new Conversation for a given name.
void newConversation(boolean withJoin, String conversationName, RequestHandler<Conversation> conversationCreateListener)
Helper to create a new Conversation for a given name.
void removeConnectionListener(NetworkingStateListener listener)
EventSource<SessionError> sessionErrorEvent()
Register for receiving session events.
void setPushDeviceToken(String pushDeviceToken)
Set/Reset the push registration authToken whenever there is a new one available, via FirebaseInstanceIdService, prior to login(String, RequestHandler).
EventSource<SynchronisingState.STATE> synchronisationEvent()
Register for receiving synchronisation events.
String toString()
[Expand]
Inherited Methods
From class java.lang.Object

Public Methods

public void call (List<String> users, RequestHandler<Call> callCreateListener)

Initiate an outbound call to multiple app users. Helper method to create a Conversation and invite multiple users to an Audio Call.

Parameters
users The optional users to get invited to the new Call.
callCreateListener The request completion listener.

public EventSource<Call> callEvent ()

Register for receiving incoming Call events.

Call properties:

< Upon receiving incoming call, following options are available:

/p>

public void callPhone (String phoneNumber, RequestHandler<Call> callStateListener)

Initiate an outbound call to a specific phone number.

Callbacks will be dispatched each time there is a Call.CALL_STATE change.

Order of events:

Parameters
phoneNumber The phone number.
callStateListener The request completion listener.

public void disconnect ()

Explicitly disconnect the socket connection.

Use this when your app is not being in use. In order to reconnect the socket back, user must re-login.

Explicit disconnect also:
  • disables and terminates any audio stream
  • removes any event listeners and
  • deletes any locally stored data.

If there is no ongoing socket connection the method will return.

public void enableAllPushNotifications (boolean enable, RequestHandler<Void> pushEnableListener)

Enable or Disable any push notifications triggered by any of the available conversations, using Firebase Cloud Messaging.

User must be logged in and set setPushDeviceToken(String) obtained by extending a FirebaseInstanceIdService.

By default push notifications are disabled, until setPushDeviceToken(String) and any of the enableAllPushNotifications(boolean, RequestHandler) or enablePushNotificationsForConversation(boolean, String, RequestHandler) are set.

Parameters
enable True or False.
pushEnableListener Completion listener.

public void enablePushNotificationsForConversation (boolean enable, String conversationId, RequestHandler<Void> pushEnableListener)

NOTE This is not yet implemented service-side! Enable or Disable push notifications for certain conversations. Push notifications must be enabled first via enableAllPushNotifications(boolean, RequestHandler).

Parameters
enable True or False.
conversationId The conversation id.
pushEnableListener Completion listener.

public Call getCall (String cid)

Get call based on conversation unique ID, synchronously.

Parameters
cid The unique conversation ID.
Returns
  • The call, if any found for that specific id.

public ConversationClient.ConversationClientConfig getConfig ()

Get config used to build ConversationClient.

Returns
  • the config

public Context getContext ()

Get the context we used for building ConversationClient#config.

Returns
  • a context.

public Conversation getConversation (String cid)

Get conversation based on unique ID, synchronously. The list is composed of conversations we last synchronised.

If the conversation list becomes out of sync, force a re-sync with ConversationClient#getConversations(RequestHandler>)

Parameters
cid The unique conversation ID.
Returns
  • The conversation, if any found for that specific id.

public List<Conversation> getConversationList ()

Get list of active conversation where user has been either invited, or joined, synchronously. Subscribe to synchronisationEvent() to get notified once all conversations are synchronised.

Returns
  • List of conversations.

public void getConversations (RequestHandler<List<Conversation>> conversationListListener)

Reload conversation list. Retrieve a full list of conversations the logged in user is a Member of asynchronously.

A Member is part of a Conversation if:

    • he gets invited by some other Member.
      simply joins because he knows the conversation id.
  • Parameters
    conversationListListener The listener in charge of dispatching the result.

    public NetworkState getNetworkingState ()

    Check whether the ConversationClient is trying to connect to the backend socket or not. Use this method whenever you want a single fast check of the connection status. Nevertheless, NetworkingStateListener does notify upon all of the different connection statuses as well.

    Returns

    public String getPushDeviceToken ()

    Retrieve the push registration token that was once set.

    Returns
    • The Firebase push registration token.

    public RequestHandler<Void> getPushEnableListener ()

    public static String getSDKversion ()

    Returns the current version of the Nexmo Conversation SDK.

    Returns
    • The current version of the Nexmo Conversation SDK.

    public SynchronisingState.STATE getSynchronisingState ()

    Get the current synchronising State. Use this method whenever you want a single fast check of the sync status. Nevertheless, synchronisationEvent() does notify upon all the different synchronisation statuses as well.

    Returns
    • The synchronisation most recent status. One of the SynchronisingState.STATE.

      The order of sync events is important, depending on which STATE has been synced, UI will be ready for update with fresh info.

      • CONVERSATIONS: Conversations preview has been synced. At this point all members can be displayed in the UI. Wait for the next state for updating members information in the UI.
      • MEMBERS: all information about the members has been synced. At this point all members can be displayed in the UI.

    public String getToken ()

    Get the last used jwt for login.

    Returns
    • Last authentication token.

    public final User getUser ()

    Get the current logged in User if available.

    Returns
    • The current user.

    public void getUser (String userId, RequestHandler<User> userInfoListener)

    Get user info for given userId.

    Parameters
    userId id of user
    userInfoListener listener to be notified

    public EventSource<Invitation> invitedEvent ()

    Register for receiving invitation events from new conversations.

    Returns
    • Invitation which holds: the conversation you've been invited to, your new member details and the sender of the invite.

    public List<ConversationClient.IPSHeader> ipsHeaders ()

    If you rely on your own mechanism for downloading images - instead of download(ImageRepresentation.TYPE, RequestHandler) - bear those custom headers in mind, so your request is authorized.

    To access any static content on Nexmo IPS user must attach headers returned by this method

    Returns
    • List of (key, value) user should put to server

    public boolean isLoggedIn ()

    Check whether a User has been successfully logged in.

    Returns
    • boolean.

    public EventSource<Conversation> joinedToNewConversationEvent ()

    public void listenToConnectionEvents (NetworkingStateListener listener)

    Attach a listener for connection events. Any application should listen for those events as the socket might get disconnected/reconnecting at any stage without prior notice.

    Parameters
    listener The NetworkingStateListener.

    public void login (String token, RequestHandler<User> loginListener)

    Login this ConversationClient instance based on the builder information and login details.

    Only one login(String, RequestHandler) action can be performed at a time. In case there is a user already logged in onUserAlreadyLoggedIn() will be fired, and explicit logout(RequestHandler) needs to be performed.

    Depending on the validity of the supplied token, a NexmoAPIError can be fired for:

    • INVALID_TOKEN. Supplied token is not valid, your application needs to retrieve another one in order to complete login.
    • EXPIRED_TOKEN. Supplied token has expired, your application needs to retrieve another one in order to complete login.

    A network connection will be established with the Conversation service, make sure you listen to connection events listenToConnectionEvents(NetworkingStateListener)

    Required parameters are:
    • authToken: The backend authorization authToken.
    • listener The completion listener.

    Parameters
    token The backend authorization jwt.
    loginListener The completion listener.

    public void logout (RequestHandler logoutListener)

    Logout current user. Logout also:

    • disconnects from the socket connection
    • disables and terminates any audio stream.
    • removes any event listeners and
    • deletes any locally stored data.

    Only one {ConversationClient#logout(RequestHandler)} can be performed at a time.

    Parameters
    logoutListener The RequestHandler.

    public void newConversation (String conversationName, RequestHandler<Conversation> conversationCreateListener)

    Create a new Conversation for a given name.

    In order for a User to be able to send and receive events from a Conversation, he must either:

    • explicitly Conversation#join(RequestHandler) and receive a Member instance.
    • accept an invitation. Listen for incoming invitations using memberInvitedEvent() }

    Parameters
    conversationName The optional conversation name. Must be unique, but it's case-insensitive.
    conversationCreateListener The request completion listener.

    public void newConversation (boolean withJoin, String conversationName, RequestHandler<Conversation> conversationCreateListener)

    Helper to create a new Conversation for a given name.

    This helper optionally combines newConversation(String, RequestHandler) and join(RequestHandler) into a single method call.

    Parameters
    withJoin Specify if the new conversation should be automatically joined after creation.
    conversationName The optional conversation name. Must be unique, but it's case-insensitive.
    conversationCreateListener The request completion listener.

    public void removeConnectionListener (NetworkingStateListener listener)

    public EventSource<SessionError> sessionErrorEvent ()

    Register for receiving session events.

    Returns
    • Any session error, due to either socket getting disconnected or token expiry events.

    public void setPushDeviceToken (String pushDeviceToken)

    Set/Reset the push registration authToken whenever there is a new one available, via FirebaseInstanceIdService, prior to login(String, RequestHandler).

    User must perform another login if a new push pushDeviceToken is issued.

    Parameters
    pushDeviceToken The instance ID that uniquely identifies an app/device pairing for push purposes. Remember to update the pushDeviceToken provided by a FirebaseInstanceIdService each time the InstanceID pushDeviceToken is updated.

    public EventSource<SynchronisingState.STATE> synchronisationEvent ()

    Register for receiving synchronisation events.

    The order of sync events is important, depending on which STATE has been synced, UI will be ready for update with fresh info.

    • CONVERSATIONS: Conversations preview has been synced. At this point all members can be displayed in the UI. Wait for the next state for updating members information in the UI.
    • MEMBERS: all information about the members has been synced. At this point all members can be displayed in the UI.

    The Conversation Client holds the current state information. Fetch it at any point via getSynchronisingState() ()}

    Returns
    • The most recent synchronisation state.

    public String toString ()