---
source_url: https://www.pubnub.com/docs/sdks/kotlin
title: Kotlin API & SDK Docs 13.3.0
updated_at: 2026-05-22T11:06:55.559Z
sdk_name: PubNub Kotlin SDK
sdk_version: 13.3.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Kotlin API & SDK Docs 13.3.0

PubNub Kotlin SDK, use the latest version: 13.3.0

Install:

```bash
Add PubNub dependency to your build@13.3.0
```

:::warning Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and [Java](https://www.pubnub.com/docs/sdks/java) SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted [status events](https://www.pubnub.com/docs/sdks/kotlin/status-events). These changes can impact applications built with previous versions (< `9.0.0` ) of the Kotlin SDK.
For more details about what has changed, refer to [Java/Kotlin SDK migration guide](https://www.pubnub.com/docs/sdks/kotlin/migration-guides/kotlin-v9-migration-guide).
:::

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your Kotlin application. Since Kotlin is commonly used across different platforms, we provide two implementation paths:

* **Android app development**: For developers building Android applications with Kotlin
* **Non-mobile platforms**: For developers using Kotlin in other environments (server-side, desktop, etc.)

The core PubNub concepts and API usage remain the same across both paths, but implementation details like lifecycle management and UI updates differ. Select the appropriate tab in each section to see platform-specific guidance.

:::note Chat applications
If you want to create a mobile chat application on Android with PubNub, refer to [Kotlin Chat SDK](https://www.pubnub.com/docs/chat/kotlin-chat-sdk) for details on all available chat features.
:::

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of Kotlin
* Android Studio or your preferred Kotlin IDE
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

###### Android app development

To integrate PubNub into your Android project, add this dependency to your app-level `build.gradle` file:

```bash
implementation 'com.pubnub:pubnub-kotlin:13.3.0'

// Optional: Add Kotlin coroutines for better async handling
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
```

Don't forget to add internet permission to your `AndroidManifest.xml`:

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

:::tip Pro tip
You can also add the dependency through the Android Studio UI:
* Right-click on your project.
* Select **Open Module Settings**.
* Go to the **Dependencies** tab.
* Click the **+** button.
* Search for `pubnub-kotlin`.
:::

#### Configure ProGuard

If you're using ProGuard, configure it as follows.

```bash
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

-keepattributes Exceptions, InnerClasses, Signature, Deprecated, SourceFile, LineNumberTable, *Annotation*, EnclosingMethod

-keep class com.google.android.gms.ads.identifier.** { *; }

# Joda-Time
-dontwarn org.joda.time.**
-keep class org.joda.time.** { *; }

# Gson
-dontwarn sun.misc.**
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.examples.android.model.** { *; }
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

# OkHttp3
-dontwarn okhttp3.**
-dontwarn org.codehaus.mojo.animal_sniffer.*
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

# Okio
-dontwarn okio.**

# Retrofit 2.X
-dontwarn retrofit2.**
-dontwarn javax.annotation.**
-keepclassmembers,allowshrinking,allowobfuscation interface * {
    @retrofit2.http.* <methods>;
}
-keepclasseswithmembers class * {
    @retrofit2.http.* <methods>;
}

# Logback and slf4j-api
-dontwarn ch.qos.logback.core.net.*
-dontwarn org.slf4j.**
-keep class ch.qos.** { *; }
-keep class org.slf4j.** { *; }

# PubNub
-dontwarn com.pubnub.**
-keep class com.pubnub.** { *; }

# org.json is provided by the Android framework. Prevent R8/ProGuard from
# renaming its methods to avoid NoSuchMethodError crashes at runtime.
-keepnames class org.json.** {
    *;
}
```

:::tip Troubleshooting ProGuard crashes
If your release build crashes on startup with errors related to `org.json` or other classes, see the [Kotlin SDK Troubleshooting guide](https://www.pubnub.com/docs/sdks/kotlin/troubleshoot) for additional ProGuard rules and fixes.
:::

###### Non-mobile platforms

Choose your preferred way to add the PubNub SDK to your project:

#### Maven

To integrate PubNub into your project using Maven, add this dependency to you `pom.xml`:

```xml
<dependency>
  <groupId>com.pubnub</groupId>
  <artifactId>pubnub-kotlin</artifactId>
  <version>13.3.0</version>
</dependency>
```

#### Gradle

To integrate PubNub into your project using Gradle, add this dependency to your `build.gradle` file:

```bash
implementation 'com.pubnub:pubnub-kotlin:13.3.0'
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/kotlin):

```bash
git clone https://github.com/pubnub/kotlin
```

## Steps

### Initialize PubNub

#### Android app development

In Android Studio, create a new Android project with Kotlin support. Add PubNub initialization code to your main Activity or Fragment class. This is the minimum configuration you need to send and receive messages with PubNub in your Android application.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```kotlin
// Import required classes
import com.google.gson.JsonObject
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
import com.pubnub.api.v2.PNConfiguration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class PubNubActivity : AppCompatActivity() {
    private lateinit var pubnub: PubNub
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pubnub)
        
        // Set up PubNub configuration
        val config = PNConfiguration.builder(UserId("androidUser"), "demo").apply {
            publishKey = "demo" // Replace with your publish key
        }.build()
        
        // Create a PubNub instance
        pubnub = PubNub.create(config)
        
        // Initialize your PubNub implementation here
        setupPubNub()
    }
    
    private fun setupPubNub() {
        // We'll add listeners and subscription code here
    }
    
    override fun onDestroy() {
        // Clean up PubNub resources when activity is destroyed
        pubnub.destroy()
        super.onDestroy()
    }
}
```

#### Non-mobile platforms

In the IDE of your choice, create a new Kotlin project. In that project, create a new `App` class with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```kotlin
// Step 1: Initialize PubNub with configuration
val config = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
    publishKey = "demo"
}.build()

val pubnub = PubNub.create(config)
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/kotlin/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

There are two main types of listeners you'll need to set up:

* Status listener - for connection state changes and operational events
* Event listener - for messages and presence events

#### Android app development

In your Android application, add these methods to your Activity or Fragment.

```kotlin
import com.pubnub.api.enums.PNStatusCategory
import com.pubnub.api.models.consumer.PNStatus
import com.pubnub.api.models.consumer.pubsub.PNMessageResult
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult
import com.pubnub.api.v2.callbacks.EventListener
import com.pubnub.api.v2.callbacks.StatusListener
import android.widget.Toast

private fun setupPubNub() {
    // Add a status listener to track connection state
    pubnub.addListener(object : StatusListener {
        override fun status(pubnub: PubNub, status: PNStatus) {
            when (status.category) {
                PNStatusCategory.PNConnectedCategory -> {
                    // Update UI on the main thread
                    runOnUiThread {
                        Toast.makeText(this@PubNubActivity, "Connected to PubNub", Toast.LENGTH_SHORT).show()
                    }
                }
                PNStatusCategory.PNDisconnectedCategory,
                PNStatusCategory.PNUnexpectedDisconnectCategory -> {
                    // Update UI on the main thread
                    runOnUiThread {
                        Toast.makeText(this@PubNubActivity, "Disconnected from PubNub", Toast.LENGTH_SHORT).show()
                    }
                }
                else -> {}
            }
        }
    })
    
    // Continue with channel subscription...
}
```

#### Non-mobile platforms

Add the following code to set up these listeners:

```kotlin
// Step 3: Set up connection status listener
pubnub.addListener(object : StatusListener {
    override fun status(pubnub: PubNub, status: PNStatus) {
        when (status.category) {
            PNStatusCategory.PNConnectedCategory -> println("Connected/Reconnected")
            PNStatusCategory.PNDisconnectedCategory,
            PNStatusCategory.PNUnexpectedDisconnectCategory -> println("Disconnected/Unexpectedly Disconnected")
            else -> {}
        }
    }
})
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/kotlin/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This is done in three steps:

1. Define a channel to subscribe to.
2. Set up subscription options (if needed).
3. Create and activate a subscription with event listeners.

#### Android app development

Continue building on the `setupPubNub()` method in your Activity.

```kotlin
import com.pubnub.api.v2.subscriptions.SubscriptionOptions

private fun setupPubNub() {
    // Status listener code from previous step...
    
    // Define the channel you want to subscribe to
    val myChannel = "myChannel"
    val channel = pubnub.channel(myChannel)
    
    // Set up subscription options (optional - here we're enabling presence events)
    val options = SubscriptionOptions.receivePresenceEvents()
    
    // Create a subscription for the channel
    val subscription = channel.subscription(options)
    
    // Add an event listener to the subscription
    subscription.addListener(object : EventListener {
        override fun message(pubnub: PubNub, result: PNMessageResult) {
            // Update UI on the main thread
            runOnUiThread {
                val message = result.message.asJsonObject
                // Display the message in your UI
                updateMessageUI(message.toString())
            }
        }
        
        override fun presence(pubnub: PubNub, result: PNPresenceEventResult) {
            // Handle presence events if needed
        }
    })
    
    // Activate the subscription to start receiving messages
    subscription.subscribe()
    
    // Store subscription reference to manage lifecycle
    this.subscription = subscription
}

private fun updateMessageUI(message: String) {
    // Update your UI components with the message
    // For example:
    findViewById<TextView>(R.id.messageTextView).text = message
}

// Don't forget to unsubscribe when appropriate
override fun onPause() {
    super.onPause()
    subscription?.unsubscribe()
}

override fun onResume() {
    super.onResume()
    subscription?.subscribe()
}
```

#### Non-mobile platforms

Let's implement the subscription in your main function or class.

```kotlin
// Step 4: Create a subscription
val channel = pubnub.channel(myChannel)
val options = SubscriptionOptions.receivePresenceEvents()
val subscription = channel.subscription(options)

// Step 5: Add event listeners
subscription.addListener(object : EventListener {
    override fun message(pubnub: PubNub, result: PNMessageResult) {
        println("Received message ${result.message.asJsonObject}")
    }

    override fun presence(pubnub: PubNub, result: PNPresenceEventResult) {
        // Handle presence events
    }
})

// Step 6: Activate the subscription
subscription.subscribe()
```

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/kotlin/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

#### Android app development

Add a method to publish messages to your Android Activity.

```kotlin
private fun sendMessage(text: String) {
    // Create a message
    val myMessage = JsonObject().apply {
        addProperty("msg", text)
    }
    
    // Using Kotlin coroutines for async operations
    CoroutineScope(Dispatchers.IO).launch {
        try {
            // Publish the message to the channel
            val channel = pubnub.channel(myChannel)
            val result = channel.publish(myMessage).sync()
            
            // Update UI on the main thread
            runOnUiThread {
                Toast.makeText(
                    this@PubNubActivity, 
                    "Message sent successfully!", 
                    Toast.LENGTH_SHORT
                ).show()
            }
        } catch (e: Exception) {
            // Handle error on the main thread
            runOnUiThread {
                Toast.makeText(
                    this@PubNubActivity, 
                    "Failed to send message: ${e.message}", 
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

// Add this to your Activity's UI setup
private fun setupUI() {
    // Set up a button click listener to send messages
    findViewById<Button>(R.id.sendButton).setOnClickListener {
        val messageInput = findViewById<EditText>(R.id.messageInput)
        val messageText = messageInput.text.toString()
        
        if (messageText.isNotEmpty()) {
            sendMessage(messageText)
            messageInput.text.clear()
        }
    }
}
```

#### Non-mobile platforms

Let's create a function to publish messages to a PubNub channel:

```kotlin
// Step 7: Publish a message
channel.publish(myMessage).async { result ->
    result.onFailure { exception ->
        println("Error while publishing")
        exception.printStackTrace()
    }.onSuccess { value ->
        println("Message sent, timetoken: ${value.timetoken}")
    }
}
// Keep the program running to receive the published message
Thread.sleep(2000)
```

### Run the app

#### Android app development

To test your Android application:

1. Connect your Android device or start an emulator.
2. Run your app from Android Studio.
3. You should see the connection status toast appear.
4. Enter a message in the input field and tap the send button.
5. You should see your message appear in the UI as it's received back through the subscription.

#### Non-mobile platforms

To test the code from your `App.kt` file, run it with `gradle run` in the terminal. You can use the terminal that is built in your IDE or the one that your operating system provides.

When you run the application, you should see output similar to the following:

```text
Message to send: {"msg":"Hello, world"}  // First, we see the message we're about to send
Connected/Reconnected                     // Then we get confirmation that we're connected to PubNub
Received message {"msg":"Hello, world"}   // We receive the message we just sent (because we're subscribed to the same channel)
Message sent, timetoken: 16967543908123456  // Finally, we see the timetoken confirming the message was sent successfully
```

## Complete example

```kotlin
package com.pubnub.docs.basicUsage

import com.google.gson.JsonObject
import com.pubnub.api.PubNub
import com.pubnub.api.UserId
import com.pubnub.api.enums.PNStatusCategory
import com.pubnub.api.models.consumer.PNStatus
import com.pubnub.api.models.consumer.pubsub.PNMessageResult
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult
import com.pubnub.api.v2.callbacks.EventListener
import com.pubnub.api.v2.callbacks.StatusListener
import com.pubnub.api.v2.subscriptions.SubscriptionOptions

fun main() {
    
    // Step 1: Initialize PubNub with configuration
    val config = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
        publishKey = "demo"
    }.build()

    val pubnub = PubNub.create(config)
    

    // Step 2: Define a channel and prepare a message
    val myChannel = "myChannel"
    val myMessage = JsonObject().apply {
        addProperty("msg", "Hello, world")
    }

    println("Message to send: $myMessage")

    
    // Step 3: Set up connection status listener
    pubnub.addListener(object : StatusListener {
        override fun status(pubnub: PubNub, status: PNStatus) {
            when (status.category) {
                PNStatusCategory.PNConnectedCategory -> println("Connected/Reconnected")
                PNStatusCategory.PNDisconnectedCategory,
                PNStatusCategory.PNUnexpectedDisconnectCategory -> println("Disconnected/Unexpectedly Disconnected")
                else -> {}
            }
        }
    })
    

    
    // Step 4: Create a subscription
    val channel = pubnub.channel(myChannel)
    val options = SubscriptionOptions.receivePresenceEvents()
    val subscription = channel.subscription(options)

    // Step 5: Add event listeners
    subscription.addListener(object : EventListener {
        override fun message(pubnub: PubNub, result: PNMessageResult) {
            println("Received message ${result.message.asJsonObject}")
        }

        override fun presence(pubnub: PubNub, result: PNPresenceEventResult) {
            // Handle presence events
        }
    })

    // Step 6: Activate the subscription
    subscription.subscribe()
    

    // Wait for connection to establish before publishing
    Thread.sleep(4000)

    
    // Step 7: Publish a message
    channel.publish(myMessage).async { result ->
        result.onFailure { exception ->
            println("Error while publishing")
            exception.printStackTrace()
        }.onSuccess { value ->
            println("Message sent, timetoken: ${value.timetoken}")
        }
    }
    // Keep the program running to receive the published message
    Thread.sleep(2000)
    
}
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered. |
| Build errors | Ensure you've added the PubNub dependency correctly., Check that you're using a compatible version of Kotlin., Make sure all imports are correct. |

For Android-specific issues like ProGuard configuration problems or API compatibility errors, see our [Kotlin SDK Troubleshooting guide](https://www.pubnub.com/docs/sdks/kotlin/troubleshoot).

## Next steps

Great job! 🎉 You've successfully created your first PubNub Kotlin application. Here are some exciting things you can explore next:

### Build chat

* Learn about the [Kotlin Chat SDK](https://www.pubnub.com/docs/chat/kotlin-chat-sdk) for ready-to-use chat features.
* Add typing indicators and read receipts.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/kotlin/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/kotlin/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/kotlin/api-reference/access-manager) to secure your channels.

### Real examples

* Look at the [Digital Health Reference Implementation](https://github.com/pubnub/kotlin-telemedicine-demo) for a real-world example.
* Explore our [GitHub repository](https://github.com/pubnub/kotlin/) for more code samples.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/kotlin/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.