API Cheat Sheet

A quick reference guide to the Chat SDK API

Code Examples

The demo projects on Github contain some useful code examples.

Configuration

The Chat SDK can be configured using the configuration service.

Config config = ChatSDK.config();

// Example
config.setGoogleMaps("Google Maps API Key");

Messaging Server API

The Chat SDK uses a series of services to make requests to the messaging server. These services are contained in a class called NetworkAdapter.

BaseNetworkAdapter a = ChatSDK.shared().a();

Each of these services contains methods to make requests to the server. Here is a full list of the services available:

// Core Methods
CoreHandler core = networkAdapter.core;
AuthenticationHandler auth = networkAdapter.auth;
ThreadHandler thread = networkAdapter.thread;
ImageMessageHandler imageMessage = networkAdapter.imageMessage;
LocationMessageHandler locationMessage = networkAdapter.locationMessage;
ContactHandler contact = networkAdapter.contact;
SearchHandler search = networkAdapter.search;
PublicThreadHandler publicThread = networkAdapter.publicThread;

// Free modules
PushHandler push = networkAdapter.push;
UploadHandler upload = networkAdapter.upload;

// Paid modules
VideoMessageHandler videoMessage = networkAdapter.videoMessage;
AudioMessageHandler audioMessage = networkAdapter.audioMessage;
TypingIndicatorHandler typingIndicator = networkAdapter.typingIndicator;
LastOnlineHandler lastOnline = networkAdapter.lastOnline;
BlockingHandler blocking = networkAdapter.blocking;
NearbyUsersHandler nearbyUsers = networkAdapter.nearbyUsers;
ReadReceiptHandler readReceipts = networkAdapter.readReceipts;
StickerMessageHandler stickerMessage = networkAdapter.stickerMessage;
FileMessageHandler fileMessage = networkAdapter.fileMessage;
EncryptionHandler encryption = networkAdapter.encryption;

Examples:

Core Service - Methods connected with the current user

// Push the user's profile data to the server
ChatSDK.core().pushUser().subscribe(() -> {

}, throwable -> {

});

// Get the current user
User user = ChatSDK.core().currentUser();

// Get a user and update their proifle from the server 
ChatSDK.core().getUserForEntityID("User Entity ID").subscribe(otherUser -> {

}, throwable -> {

});

Auth Service - Methods for Authentication

// Login
ChatSDK.auth().authenticate(AccountDetails.username("Username", "Password")).subscribe(() -> {

}, throwable -> {

});

// Check if user is logged in
boolean isLoggedIn = ChatSDK.auth().isAuthenticated();

// Log out
ChatSDK.auth().logout().subscribe();

Thread Service - Methods related to Conversation Threads

// Create thread
User otherUser = ChatSDK.core().getUserNowForEntityID("EntityID");
ChatSDK.thread().createThread("Name", Collections.singletonList(otherUser)).subscribe(thread1 -> {

    // Send a message
    ChatSDK.thread().sendMessageWithText("Hi", thread1).subscribe();

});

// Get a list of public threads
List<Thread> threads = ChatSDK.thread().getThreads(ThreadType.Private1to1);

Messaging Server Notifications

Since messaging happens in realtime, we also need to get notifications from the server. This happens through several mechanisms. For more details see:

Some available for Android and others for iOS:

1. Event Bus (Android)

Predicate<NetworkEvent> filter = NetworkEvent.filterType(EventType.MessageAdded, EventType.MessageRemoved);

Disposable d = ChatSDK.events()
        .source()
        .filter(filter)
        .subscribe(networkEvent -> {

            // Handle Event Here
            if (networkEvent.getMessage() != null) {
                Logger.debug(networkEvent.getMessage().getText());
            }
    
        });

// Stop listening
d.dispose();

2. Hooks

// Hooks
ChatSDK.hook().addHook(Hook.sync(data -> {
    Message message = (Message) data.get(HookEvent.Message);
}), HookEvent.MessageReceived);

// Asynchronous code
ChatSDK.hook().addHook(Hook.async(data -> Completable.create(emitter -> {
    // ... Async code here
    emitter.onComplete();
})), HookEvent.MessageReceived);

Available Hooks

public static String DidAuthenticate = "DidAuthenticate";

public static String UserOn = "UserOn";

public static String MessageReceived = "MessageReceived";
public static String MessageWillSend = "MessageWillSend";
public static String MessageSent = "MessageSent";
public static String IsNew_Boolean = "IsNew_Boolean";

public static String DidLogout = "DidLogout";
public static String WillLogout = "WillLogout";

public static String UserDidConnect = "UserDidConnect";
public static String UserWillDisconnect = "UserWillDisconnect";

public static String ContactWillBeAdded = "ContactWillBeAdded";
public static String ContactWasAdded = "ContactWasAdded";
public static String ContactWillBeDeleted = "ContactWillBeDeleted";
public static String ContactWasDeleted = "ContactWasDeleted";

3. Notification Center (iOS Deprecated)

NotificationCenter.default.addObserver(forName: bNotificationLogout, object: nil, queue: nil, using: { notification in
    
})

UI Modification Service

Chat SDK provides a way to modify the user interface without forking the library. This can be achieved using the UI server.

InterfaceAdapter interfaceAdapter = ChatSDK.ui();

The UI service is used to inject views into the app. It also defines which tabs are displayed and much more. For example, you can override Activites, Fragments, and ViewControllers by subclassing them and injecting them using the UI service.

// Override an activity
ChatSDK.ui().setChatActivity(CustomChatActivity.class);

// Override a fragment
ChatSDK.ui().setProfileFragmentProvider(user -> {
    ProfileFragment fragment =  new AProfileFragment();
    fragment.setUser(user);
    return fragment;
});

For more details see:

Local Database

The Chat SDK has a powerful local database that is automatically synchronized with the messaging server. It can be accessed using the database service.

StorageManager storageManager = ChatSDK.db();

The database service can be used to fetch, create, and delete entities. For example:

// Create entity
User user = ChatSDK.db().createEntity(User.class);

// Fetch an entity with a given ID
Thread thread = ChatSDK.db().fetchEntityWithEntityID("threadEntityID", Thread.class);

// Fetch or create an entity with a given ID
User otherUser = ChatSDK.db().fetchOrCreateEntityWithEntityID(User.class, "userEntityID'");

Each entity then has many methods that can be used. For example:

user.setName("Test");
user.setAvatarURL("http://something.png");

List<User> users = thread.getUsers();
List<Message> messages = thread.getMessages();

// etc...

Note: Creating an entity locally doesn't automatically add it to the server or populate the data from the server. To do that you have to use the network adapter service.

Last updated