Telnyx Android WebRTC SDK
Table of Contents
- Project structure
- Project Setup
- Using Jetpack Compose?
- SIP Credentials
- Usage
- Adding push notifications
- Custom Logging
- Call Quality Metrics
- AI Agent Usage
- ProGuard changes
- Additional Resources
- Questions? Comments?
- License
Project structure:
- SDK project: sdk module, containing all Telnyx SDK components as well as tests.
- Demo application: app module, containing a sample demo application utilizing the sdk module.
Project Setup:
- Clone the repository
-
Open the cloned repository in Android Studio and hit the build button to build both the sdk and sample app:
-
Connect a device or start an emulated device and hit the run button
- Enjoy 😎
Using Jetpack Compose?
Have a look at our Jetpack Compose reference application hereSIP Credentials
In order to start making and receiving calls using the TelnyxRTC SDK you will need to get SIP Credentials:- Access to https://portal.telnyx.com/
- Sign up for a Telnyx Account.
- Create a Credential Connection to configure how you connect your calls.
- Create an Outbound Voice Profile to configure your outbound call settings and assign it to your Credential Connection.
Usage
Telnyx Client
NOTE: Remember to add and handle INTERNET, RECORD_AUDIO and ACCESS_NETWORK_STATE permissions
To initialize the TelnyxClient you will have to provide the application context. Once an instance is created, you can call the .connect() method to connect to the socket. An error will appear as a socket response if there is no network available:
Logging into Telnyx Client
To log into the Telnyx WebRTC client, you’ll need to authenticate using a Telnyx SIP Connection. Follow our quickstart guide to create JWTs (JSON Web Tokens) to authenticate. To log in with a token we use the tokinLogin() method. You can also authenticate directly with the SIP Connectionusername and password with the credentialLogin() method:
Creating a call invitation
In order to make a call invitation, you need to provide your callerName, callerNumber, the destinationNumber (or SIP credential), and your clientState (any String value).Accepting a call
In order to be able to accept a call, we first need to listen for invitations. We do this by getting the Telnyx Socket Response. Recommended approach using SharedFlow (Kotlin Flows):Handling Multiple Calls
The Telnyx WebRTC SDK allows for multiple calls to be handled at once. You can use the callId to differentiate the calls..- Hold/UnHold
currentCall.onHoldUnholdPressed(callId: UUID) - Mute/UnMute
currentCall.onMuteUnmutePressed() - AcceptCall
currentCall.acceptCall(...) - EndCall
currentCall.endCall(callId: UUID)
Adding push notifications
The Telnyx Android Client WebRTC SDK makes use of Firebase Cloud Messaging in order to deliver push notifications. If you want to receive notifications for incoming calls on your Android mobile device you have to enable Firebase Cloud Messaging within your application. In order to do this you need to:- Set up a Firebase console account
- Create a Firebase project
- Add Firebase to your Android Application
- Setup a Push Credential within the Telnyx Portal
- Generate a Firebase Cloud Messaging instance token
- Send the token with your login message
Providing our SDK with the FCM Token to receive Push Notifications
You will need to provide theconnect(..) method with a CredentialConfig or TokenConfig that contains an fcmToken value (received from FirebaseMessaging like in the above code snippet).
Once the fcmToken has been provided, we can provide push notifications to the application when a call is received but the device is not actively connected to the socket. (eg. Killed or Backgrounded states)
Custom Logging
The Telnyx WebRTC SDK allows you to implement your own custom logging solution by providing aTxLogger implementation. This gives you full control over how logs are handled, allowing you to route them to your own logging frameworks or analytics services.
Using Custom Logger
- Create a class that implements the
TxLoggerinterface:
- Pass your custom logger when creating the configuration:
Default Behavior
If no custom logger is provided, the SDK will use its default logging implementation based on Android’s Log class. ThelogLevel parameter still controls which logs are generated, regardless of whether you’re using a custom logger or the default one.
Best Practices
Handling Push Notifications
In order to properly handle push notifications, we recommend using a call type (Foreground Service)[https://developer.android.com/develop/background-work/services/foreground-services] with a broadcast receiver to show push notifications. An answer or reject call intent withtelnyxPushMetaData can then be passed to the MainActivity for processing.
Declining Push Notifications
The SDK now provides a simplified way to decline incoming calls from push notifications using theconnectWithDeclinePush() method. This new approach automatically handles the decline process by:
- Connecting to the socket with a
decline_pushparameter - Sending the appropriate decline message
- Disconnecting automatically
connectWithDeclinePush() instead of the standard connect() method when declining calls from push notifications.
Best Practices for Push Notifications
- Play a ringtone when a call is received from push notification using the
RingtoneManager
- Make Sure to set these flags for your pendingIntents, so the values get updated anytime when the notification is clicked
Android 14 Requirements
In order to receive push notifications on Android 14, you will need to add the following permissions to your AndroidManifest.xml file and request a few at runtime:Handling Missed Call Notifications
The backend sends a missed call notification when a call is ended while the socket is not yet connected. It comes with theMissed call! message. In order to handle missed call notifications, you can use the following code snippet in the FirebaseMessagingService class:
Handling Multiple Calls
The Telnyx WebRTC SDK allows for multiple calls to be handled at once. You can use the callId to differentiate the calls.AI Agent Usage
The Android WebRTC SDK supports Voice AI Agent implementations. To get started, follow the steps described here to build your first AI Assistant. Once your AI Agent is up and running, you can use the SDK to communicate with your AI Agent with the following steps:1. Logging in to communicate with the AI Agent
To connect with an AI Assistant, you can use theconnectAnonymously method. This allows you to establish a connection without traditional authentication credentials.
This method takes a targetId which is the ID of your AI assistant, and an optional targetVersionId. If a targetVersionId is not provided, the SDK will use the latest version available.
Note: After a successful anonymous connection, any subsequent call, regardless of the destination, will be directed to the specified AI Assistant.
Here’s an example of how to use it:
newInvite method to start a conversation with the AI Assistant.
2. Starting a Conversation with the AI Assistant
After a successfulanonymousLogin, you can initiate a call to your AI Assistant using the newInvite method. Because the session is now locked to the AI Assistant, the destinationNumber parameter in the newInvite method will be ignored. Any values provided for callerName and callerNumber will be passed on, but the call will always be routed to the AI Assistant specified during the login.
Here is an example of how to start the call:
endCall, mute, etc.
3. Receiving Transcript Updates
During an AI Assistant conversation, the SDK provides real-time transcript updates that include both the caller’s speech and the AI Assistant’s responses. This allows you to display a live conversation transcript in your application. To receive transcript updates, use thetranscriptUpdateFlow SharedFlow on your TelnyxClient instance:
TranscriptItem contains the following properties:
id: Unique identifier for the transcript itemrole: Either “user” (for the caller) or “assistant” (for the AI Agent)content: The transcribed text contenttimestamp: When the transcript item was createdisPartial: Whether this is a partial response (for streaming AI responses)
anonymousLogin. Regular calls between users do not provide transcript functionality.
4. Sending a text message to the AI Agent
In addition to voice conversation, you can send text messages directly to the AI Agent during an active call. This allows for mixed-mode communication where users can both speak and type messages to the AI Assistant. To send a text message to the AI Agent, use thesendAIAssistantMessage method:
- The
sendAIAssistantMessagemethod is only available during AI Assistant conversations - Text messages sent this way will appear in the transcript updates alongside spoken conversation
- The AI Agent will process and respond to text messages just like spoken input
- You must have an active call established before sending text messages
ProGuard changes
NOTE: In the case that you need to modify your application’s proguard settings in order to obfuscate your code, such as we have done below:app/build.gradle
app/proguard-rules.pro
Additional Resources
- Android Precompiled WebRTC Library - For developers who need more control over WebRTC implementation
- WebRTC Official Documentation
- Official SDK Documentation
License
MIT Licence © Telnyx