Skip to main content
Follow these best practices to build reliable, performant, and secure applications with the CometChat Android SDK. Organized by topic — jump to what’s relevant for your current work.

Initialization & Authentication

PracticeDescription
Initialize once at app startupCall CometChat.init() in your Application class onCreate(). It only needs to be called once per session.
Store credentials in local.propertiesKeep App ID, Region, and Auth Key out of source control. Read them via BuildConfig fields set in build.gradle.
Check for existing sessionsBefore calling login(), use CometChat.getLoggedInUser() to check if a session already exists.
Use Auth Tokens in productionAuth Keys are for development only. Generate Auth Tokens server-side using the REST API.
Handle token expiryImplement a mechanism to detect login failures due to expired tokens. Use the Login Listener to detect session changes.
Logout on sign-outAlways call CometChat.logout() when your user signs out to clear the SDK session and stop real-time events.

Activity & Fragment Lifecycle

PracticeDescription
Register listeners in onResume()Re-register message and call listeners when the Activity or Fragment becomes visible.
Remove listeners in onPause()Remove listeners in onPause() to avoid processing events while the screen is not visible.
Clean up in onDestroy()Remove all remaining listeners and cancel pending requests in onDestroy() to prevent memory leaks.
Use ViewModel for SDK stateHold SDK data (messages, users, groups) in a ViewModel so it survives configuration changes like screen rotation.
Avoid SDK calls in onCreate() before init()Ensure CometChat.init() has completed (in your Application class) before making any SDK calls in an Activity.

Listeners

PracticeDescription
Use unique listener IDsUse descriptive IDs like "MESSAGE_LISTENER_CHAT_SCREEN" to avoid accidental overwrites.
Register after login, remove on cleanupRegister listeners after login() succeeds. Remove them in onPause() or onDestroy() to prevent memory leaks.
Keep callbacks lightweightAvoid heavy processing inside listener callbacks. Post updates to your ViewModel or LiveData.
Use specific listenersOnly register the listener types you need. Don’t register a GroupListener if your screen only handles messages.

Pagination & Caching

PracticeDescription
Use reasonable limitsSet setLimit() to 30–50 for users, messages, and group members.
Reuse request objectsCall fetchNext()/fetchPrevious() on the same request instance. Creating a new object resets the cursor.
Cache frequently accessed dataStore user and group objects in your ViewModel or a local Room database to reduce API calls.

Rate Limits

PracticeDescription
Batch operationsSpace out bulk operations using a queue or throttle mechanism.
Monitor rate limit headersCheck X-Rate-Limit-Remaining in REST API responses to slow down before hitting limits.
Distinguish operation typesCore operations (login, create/delete user) share a 10,000/min limit. Standard operations have 20,000/min. Avoid frequent login/logout cycles.

Messaging

PracticeDescription
Use appropriate message typesChoose text, media, or custom messages based on your content.
Add metadata for contextUse setMetadata() to attach location, device info, or other contextual data.
Handle errors gracefullyAlways implement onError() callbacks to handle network issues or invalid parameters.
Validate file typesBefore sending media messages, verify the file type matches the message type.
Hide deleted/blocked contentUse hideDeletedMessages(true) and hideMessagesFromBlockedUsers(true) for cleaner lists.

Threaded Messages

PracticeDescription
Track active thread IDStore the current thread’s parentMessageId to filter incoming messages.
Use hideReplies(true)Exclude thread replies from the main conversation to avoid clutter.
Show reply countDisplay the number of replies on parent messages to indicate thread activity.

Reactions & Mentions

PracticeDescription
Update UI optimisticallyShow reactions immediately, then sync with the server response.
Use correct mention formatAlways use <@uid:UID> format for mentions in message text.
Highlight mentions in UIParse message text and style mentions differently using SpannableString.

Typing Indicators

PracticeDescription
Debounce typing eventsDon’t call startTyping() on every keystroke — debounce to ~300ms intervals using a Handler or debounce operator.
Auto-stop typingCall endTyping() after 3–5 seconds of inactivity or when the user sends a message.

Delivery & Read Receipts

PracticeDescription
Mark as delivered on fetchCall markAsDelivered() when messages are fetched and displayed.
Mark as read on viewCall markAsRead() when the user actually views or scrolls to a message.
Batch receiptsMark the last message in a batch — all previous messages are automatically marked.

Groups

PracticeDescription
Use meaningful GUIDsChoose descriptive, unique GUIDs (e.g., "project-alpha-team").
Set group type carefullyGroup type cannot be changed after creation. Choose between PUBLIC, PASSWORD, and PRIVATE.
Add members at creationUse createGroupWithMembers() to add initial members in a single API call.
Check hasJoined before joiningAvoid unnecessary API calls by checking the group’s hasJoined property first.
Transfer ownership before leavingOwners must transfer ownership to another member before they can leave.
Use joinedOnly(true)Filter to joined groups when building sidebars or group lists.

Group Members

PracticeDescription
Batch member additionsAdd multiple members in a single addMembersToGroup() call.
Set appropriate scopesAssign PARTICIPANT by default. Only use ADMIN or MODERATOR when needed.
Handle partial failuresCheck each entry in the response for "success" or an error message.
Use scope constantsUse CometChatConstants.SCOPE_ADMIN instead of raw strings.
Kick vs. BanUse kick when the user can rejoin. Use ban for permanent removal until unbanned.

Calling

PracticeDescription
Initialize Calls SDK after Chat SDKAlways initialize Chat SDK (CometChat.init()) before Calls SDK (CometChatCalls.init()).
Store session ID immediatelySave the session ID from initiateCall() response — you’ll need it for accept, reject, and cancel.
Handle all call statesImplement handlers for all listener events (accepted, rejected, cancelled, busy, ended).
Generate tokens just-in-timeGenerate call tokens immediately before starting a session rather than caching them.
Clean up on session endAlways call CometChatCalls.endSession() in both onCallEnded and onCallEndButtonPressed callbacks.
Request permissions before callingCheck and request CAMERA and RECORD_AUDIO permissions at runtime before initiating a call.
Inform users about recordingAlways notify participants when recording starts — this is often a legal requirement.
Limit presenters to 5Additional users should join as viewers.

Permissions

PracticeDescription
Request permissions at the right timeRequest CAMERA, RECORD_AUDIO, and READ_EXTERNAL_STORAGE permissions contextually, not at app launch.
Handle permission denial gracefullyShow a rationale dialog if the user denies a permission, and disable the relevant feature rather than crashing.
Use ActivityResultContractsUse the modern registerForActivityResult API instead of the deprecated onRequestPermissionsResult.

Connection & WebSocket

PracticeDescription
Register connection listener earlyAdd the listener right after CometChat.init() succeeds.
Show connection status in UIDisplay a banner when disconnected so users know messages may be delayed.
Queue actions during disconnectionQueue user actions and retry once onConnected fires.
Don’t poll getConnectionStatus()Use the listener-based approach instead.
Reconnect on app foregroundCall CometChat.connect() in onResume() if you disconnect in the background.

AI Features

PracticeDescription
Register both listeners for AI AgentsUse AIAssistantListener for streaming events and MessageListener for persisted messages.
Handle streaming progressivelyRender the assistant’s reply token-by-token using Text Message Content events.
Show pending state for moderationDisplay a visual indicator when getModerationStatus() returns PENDING.
Handle disapproved messages gracefullyShow a placeholder or notification so the sender understands what happened.
Track pending messagesMaintain a local map of pending message IDs to update UI when moderation results arrive.

Upgrading from V3

PracticeDescription
Follow the setup guide firstComplete the v4 setup instructions before changing dependencies.
Update Gradle dependencyReplace the v3 artifact with com.cometchat:chat-sdk-android:4.x.x in your build.gradle.
Test incrementallyTest each feature area (messaging, calling, groups) individually after updating.
Remove old packagesRemove the v3 dependency from build.gradle and sync to avoid conflicts.

Next Steps

Troubleshooting

Common issues and solutions

Setup SDK

Installation and initialization guide