PushizoDocs
SDK guides

Kotlin Multiplatform

com.pushizo:pushizo-kmp — calls the native Android and iOS SDKs from shared Kotlin code. Maven Central release is in preparation.

Source: sdk/kmp-mobile, example: examples/kmp-app. The package doesn't reimplement any logic; on each platform it delegates to the native SDK, so delivery, queueing, sessions, and in-app rendering stay in the native SDK.

Status: The Android (androidTarget) and iOS (iosArm64, iosSimulatorArm64, iosX64) targets are ready and tested. The iOS target wraps the Objective-C facade of Pushizo.xcframework via cinterop and builds only on macOS. Until it is published to Maven Central as com.pushizo:pushizo-kmp, use it from source; after publication the includeBuild line is no longer needed, and the app still embeds Pushizo.xcframework.

To send notifications from your server, use the server client, not this package.

Installation (from source)

settings.gradle.kts:

includeBuild("../pushizo/sdk/kmp-mobile")

The shared module's build.gradle.kts file:

kotlin {
    sourceSets {
        commonMain.dependencies {
            api("com.pushizo:pushizo-kmp:0.3.0")
        }
    }
}

On Android, FCM setup is the same as with the native SDK: google-services.json and the com.google.gms.google-services plugin (Android).

On iOS, first build Pushizo.xcframework (sdk/ios/scripts/build-xcframework.sh; by default the package looks under sdk/ios/build/xcframework, which you can override with -Ppushizo.xcframework=<path>). The shared module produces an iOS framework; your Xcode project adds this framework together with Pushizo.xcframework (Embed & Sign). APNs and Notification Service Extension setup is the same as with the iOS SDK (iOS).

kotlin {
    iosSimulatorArm64().binaries.framework {
        baseName = "Shared"
        export("com.pushizo:pushizo-kmp:0.3.0")
    }
}

Usage

Initialize in Application.onCreate on Android and in application(_:didFinishLaunchingWithOptions:) on iOS. PushizoContext is a Context on Android and the PushizoApplicationContext object on iOS:

Pushizo.initialize(context, "app_…", PushizoOptions())           // Android
Pushizo.initialize(PushizoApplicationContext, "app_…")            // iOS (iosMain)

After that, you can make calls from shared code:

Pushizo.login("user_42")
Pushizo.User.addTags(mapOf("plan" to "pro"))
Pushizo.User.addEmail("ali@example.com")
Pushizo.Session.sendEvent("purchase", mapOf("sku" to "a1"), value = 49.9)
Pushizo.InAppMessages.addTrigger("level", "gold")

val clicks = Pushizo.Notifications.addClickListener { event ->
    println(event.notification.title)
}
clicks.remove()

Notification permission

The permission prompt needs a platform object; PushizoPermissionHost is an Activity on Android and a UIViewController on iOS (on iOS the system dialog opens and the object isn't used). On Android you must also report the result; otherwise the subscription and permission observers aren't updated:

Pushizo.Notifications.requestPermission(activity)

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    Pushizo.Notifications.onPermissionResult()
}

Android delivery hardening

On vendors such as Xiaomi, Huawei, Oppo, Vivo and Samsung, the battery and auto-start manager stops apps in the background, so notifications arrive late or not at all. Pushizo.Delivery reads the restrictions on the device and takes the user to the relevant settings screen. Details: Android delivery hardening.

val status = Pushizo.Delivery.status()            // supported, vendor, rom, risk, restricted, recommendedSettings
if (Pushizo.Delivery.shouldShowGuidance()) {      // at risk and the dialog was not shown in the last 14 days
    Pushizo.Delivery.showGuidance(activity) { opened -> /* whether the settings screen opened */ }
}
Pushizo.Delivery.openSettings(context, PushizoDeliverySetting.AUTO_START) // from your own UI

PushizoDeliveryRisk: NONE, ELEVATED, HIGH. PushizoDeliverySetting: AUTO, NOTIFICATIONS, AUTO_START, BATTERY_OPTIMIZATION, APP_DETAILS. shouldShowGuidance(minIntervalDays = 30) changes the interval and showGuidance(host, setting, message) the screen and the text; the SDK never shows the dialog on its own. Android only: on iOS status() returns PushizoDeliveryStatus.UNSUPPORTED (risk is NONE), openSettings(PushizoApplicationContext) returns false, and showGuidance shows nothing and calls onResult(false).

Placements, chat and other native APIs

These native SDK APIs are callable from shared code: embedded placements (Pushizo.Placements), live chat (Pushizo.Chat), in-app click and lifecycle listeners, ads personalization consent and consent records, the advertising ID (Pushizo.Ads), the app badge, removing a single notification or a group, background location permission, and ADM registration (Pushizo.User.registerAdm).

// Embedded placement: returns a model, rendering is yours
val message = Pushizo.Placements.list("home_banner").firstOrNull()
message?.let { Pushizo.Placements.reportImpression(it) }

// In-app clicks and lifecycle
val clicks = Pushizo.InAppMessages.addClickListener { event -> println(event.actionId) }

// Consent, advertising ID, badge, notification removal, background location permission
Pushizo.User.setAdsPersonalizationConsent(true)
val consents = Pushizo.User.getConsents()
Pushizo.Ads.setAdvertisingId(advertisingId)
Pushizo.Notifications.setBadgeCount(3)
Pushizo.Notifications.removeGroupedNotifications("orders")
Pushizo.Location.requestBackgroundPermission(activity)

// Live chat (the data API for your own UI)
val chat = Pushizo.Chat.addListener(object : PushizoChatListener {
    override fun onMessage(message: PushizoChatMessage) { /* … */ }
})
Pushizo.Chat.start(name = "Ali")
Pushizo.Chat.sendMessage("Hello")

Single-platform calls are harmless on the other platform: registerAdm and removeNotification(androidNotificationId) only take effect on Android. A single notification is removed on both platforms with removeNotification(notification.identifier): PushizoNotification.identifier is the request identifier on iOS and the tray ID as text on Android. requestBackgroundPermission and requestAlwaysPermission request the same permission (Android ACCESS_BACKGROUND_LOCATION, iOS "always"); the state is read from the native SDK with permissionGranted and backgroundPermissionGranted.

Live chat, Ads.setAdvertisingId (GAID on Android, IDFA on iOS) and the in-app lifecycle listener are wired to the native SDK on both platforms; Pushizo.Chat.isSupported returns true on both. For chat, value-returning calls throw IllegalStateException if the SDK isn't initialized and IllegalArgumentException for invalid input; listeners are called on the main thread. The lifecycle listener is retained by the bridge until the returned registration is remove()d.

User properties, observers and event IDs

// User property: string, number, boolean, list or map; null removes it
Pushizo.User.setProperty("first_name", "Ali")
Pushizo.User.setProperty("interests", listOf("sports", "music"))
Pushizo.User.setProperty("first_name", null)

// Login with a profile: email, phone, tags and aliases in one call
Pushizo.login("user_42", PushizoUserProfile(email = "ali@example.com", tags = mapOf("plan" to "pro")))

// Event with a deduplication ID (8-64 characters; letters, digits and . _ : -)
Pushizo.Session.sendEvent("purchase", mapOf("sku" to "a1"), value = 49.9, eventId = "order_10042")

// Observers: remove them through the returned registration
val flags = Pushizo.FeatureFlags.addObserver { /* values were refreshed */ }
val inbox = Pushizo.Inbox.addObserver { event -> println("${event.type} ${event.itemId} ${event.unreadCount}") }
flags.remove()
inbox.remove()

// Badge: result and stored count
val shown = Pushizo.Notifications.setBadgeCountWithResult(3)
val count = Pushizo.Notifications.badgeCount

setProperty throws IllegalArgumentException for a blank key; the native iOS SDK logs and ignores keys longer than 64 characters and lists/maps that contain null. A login with a profile goes to the native call on both platforms: if the profile or the identity proof is invalid, no login happens and IllegalArgumentException is thrown; if the SDK isn't initialized, IllegalStateException is thrown. With an invalid eventId the native SDK generates its own ID.

FeatureFlags.addObserver is called on the main thread every time values are successfully refreshed from the server, Inbox.addObserver whenever the inbox changes. PushizoInboxChangeEvent.type: listed, read, read_all, archived, count; itemId is set only for read and archived events. read, read_all and archived are always reported, listed and count only when the unread count changes.

The badge now goes to the native SDK on Android too: the count is stored and written to the notifications the SDK shows from then on (launchers that display a number, Android 8+). setBadgeCountWithResult returns true on Android if the badge can be shown on this device (false before Android 8, when notifications are off, or when the channel badge is off); on iOS it always returns true. badgeCount returns the last stored count on Android and the app icon badge on iOS.

Ready-made chat screen and Live Activities

// Ready-made chat screen
Pushizo.Chat.show(context)            // Android: Context · iOS: PushizoApplicationContext
Pushizo.Chat.show(host)               // Android: Activity · iOS: UIViewController
if (Pushizo.Chat.isPresented) Pushizo.Chat.hide()

// Live Activities (iOS): the general-purpose type
if (Pushizo.LiveActivities.isSupported) {
    Pushizo.LiveActivities.setupDefaultLiveActivity()
    Pushizo.LiveActivities.startDefaultLiveActivity(
        "order_42",
        attributes = mapOf("title" to "Order"),
        contentState = mapOf("step" to 2, "done" to false),
    )
}

Chat.show starts the HsChatActivity screen on Android (in the same task when given an Activity, in a new task when given only a context) and presents the chat screen modally on iOS (from the topmost view controller when none is given). If the screen is already open, no second one is opened. hide() returns true if a screen was open. isPresented is the native value on iOS; Android has no native counterpart, so the bridge tracks the chat screen's lifecycle, and tracking starts with the bridge's initialize or show call.

Pushizo.LiveActivities only takes effect on iOS: setupDefaultLiveActivity() starts tracking the general-purpose type (defaultActivityType), and startDefaultLiveActivity starts a local activity (iOS 16.1+). activityId must be 1-100 characters (letters, digits and _ . : -), values must be strings, finite numbers or booleans, keys must be 1-64 characters, and the pushizo key is reserved inside attributes; otherwise IllegalArgumentException is thrown. On iOS, IllegalStateException is thrown if the SDK isn't initialized, UnsupportedOperationException before iOS 16.1 and on Mac Catalyst, and RuntimeException if the system rejects the activity. On Android isSupported is false, defaultActivityType is null, and the calls do nothing and return false. Your own ActivityAttributes types are registered from Swift (iOS).

Scope

Shared API: initialization, privacy consent, login / logout, JWT refresh, tags, aliases, language, email and SMS, push subscription, notification permission, click and foreground listeners, events, in-app triggers, location sharing and background geofencing, notification inbox (Pushizo.Inbox), content cards (Pushizo.ContentCards), preferences (Pushizo.Preferences), feature flags (Pushizo.FeatureFlags), embedded placements (Pushizo.Placements), live chat and the ready-made chat screen (Pushizo.Chat), the advertising ID (Pushizo.Ads), the general-purpose Live Activities type (Pushizo.LiveActivities), and Android delivery hardening (Pushizo.Delivery).

APIs tied to native views and types aren't in the shared API: custom in-app renderers (setRenderer), the embeddable chat and content card views (HsChatView, HSChatViewController, HsContentCardsView), Live Activities with your own ActivityAttributes types, and chat attachments from a file address (Uri). Call them through com.pushizo.sdk.Pushizo from androidMain on Android, and through com.pushizo.kmp.ios (the Objective-C facade) from iosMain or from Swift on iOS.

iOS differences: because notification permission can only be read asynchronously, permission is the last known value (read at initialization and updated on permission and subscription changes).

On this page