PushizoDocs
SDK guides

Android SDK

Kotlin, minSdk 23, AGP 8; push via FCM, notification channels, in-app, notification inbox, preferences.

The package is com.pushizo:pushizo-android; push goes through FCM (Pushizo always sends data-only messages and the SDK builds the notification). Example: examples/android-kotlin.

Installation

  1. Create a Firebase project, add your Android app and put the google-services.json file under app/. Root build.gradle.kts: id("com.google.gms.google-services") version "4.4.2" apply false; app/build.gradle.kts: id("com.google.gms.google-services").
  2. Dashboard → Channels → Android Push → upload the Firebase service account JSON and click Verify.
  3. Dependency:
// app/build.gradle.kts
dependencies { implementation("com.pushizo:pushizo-android:0.3.0") }
// From inside the monorepo: settings.gradle.kts → include(":pushizo"); project(":pushizo").projectDir = file("<repo>/sdk/android/pushizo")
//                   and implementation(project(":pushizo"))
  1. Nothing extra is needed in the manifest: INTERNET, POST_NOTIFICATIONS, PushizoMessagingService and NotificationOpenedReceiver are added via manifest merge. For the default icon/color:
<meta-data android:name="com.pushizo.sdk.default_notification_icon" android:resource="@drawable/ic_stat_pushizo" />
<meta-data android:name="com.pushizo.sdk.default_notification_color" android:resource="@color/brand" />

Initialization (Application)

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        Pushizo.initialize(
            this,
            "app_…",
            Pushizo.Options(
                apiUrl = "https://api.pushizo.com",
                requiresPrivacyConsent = false,
                logLevel = HsLog.Level.WARN,
                defaultChannelName = "Notifications",
            ),
        )
        Pushizo.Notifications.addClickListener { event ->
            // event.notification, event.actionId, event.url (the notification URL if the button has no URL)
        }
    }
}

Permission (Android 13+)

Pushizo.Notifications.requestPermission(activity)

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

val observer: (Boolean) -> Unit = { granted -> /* permission changed */ }
Pushizo.Notifications.addPermissionObserver(observer)
Pushizo.Notifications.removePermissionObserver(observer)

Without permission the subscription stays pending; it is registered automatically once permission is granted. Pushizo.Notifications.permission returns the current state synchronously. The observer is called on the main thread when the effective permission actually changes (as a result of a permission request or when the app returns to the foreground); for Java there is the Pushizo.Notifications.PermissionObserver interface.

Amazon Fire OS (ADM)

On Fire OS devices, push arrives through Amazon Device Messaging via the optional com.pushizo:pushizo-android-adm module (adm_push, a secondary subscription alongside the main one). The module starts ADM registration itself, writes the registration ID to the subscription, deletes the old one when the ID is renewed and hands ADM messages to the same notification pipeline as FCM. Permissions, amazon:enable-feature (android:required="false"), handlers and the receiver are added via manifest merge; on Google Play devices the module silently stays disabled.

dependencies {
    implementation("com.pushizo:pushizo-android:0.3.0")
    implementation("com.pushizo:pushizo-android-adm:0.3.0")
    // The Amazon ADM jar is not on Maven: download it from developer.amazon.com and add it as compile-time only.
    compileOnly(files("libs/amazon-device-messaging-1.1.0.jar"))
}

Put your app's ADM API key in app/src/main/assets/api_key.txt, and enter the security profile's Client ID and Client Secret in the dashboard under Channels → Amazon Device Messaging. Details: Extra push channels.

API

Pushizo.setConsentGiven(true)
Pushizo.login("user_42", identityHash = null)
Pushizo.logout()

Pushizo.User.addTag("plan", "pro"); Pushizo.User.addTags(mapOf("a" to "1")); Pushizo.User.removeTag("plan")
Pushizo.User.getTags(); Pushizo.User.setLanguage("tr"); Pushizo.User.id; Pushizo.User.externalId
Pushizo.User.setProperty("plan", "pro")               // user property; null deletes it

Pushizo.User.pushSubscription.optIn() / optOut() / id / token / optedIn / state
Pushizo.User.pushSubscription.addObserver { state -> … }

Pushizo.Notifications.addForegroundLifecycleListener { e -> e.preventDefault() } // don't show in the foreground
Pushizo.Session.sendEvent("purchase", mapOf("sku" to "A1"), 49.9)
Pushizo.Session.sendEvent("purchase", mapOf("sku" to "A1"), 49.9, "evt_7f3a9c21") // same event id as the ad pixel

val flagObserver = HsFeatureFlagObserver { /* flags were refreshed */ }
Pushizo.FeatureFlags.addObserver(flagObserver)       // on the main thread; remove with removeObserver
Pushizo.Debug.setLogLevel(HsLog.Level.DEBUG)

Email and SMS

Pushizo.User.addEmail("Ali@Pushizo.com")      // → ali@pushizo.com; IllegalArgumentException if invalid
Pushizo.User.removeEmail("ali@pushizo.com")
Pushizo.User.addSms("+90 (532) 123-45-67")      // → +905321234567
Pushizo.User.removeSms("+905321234567")
Pushizo.User.emails; Pushizo.User.smsNumbers // addresses registered on this device

Registration rules are the same as on iOS: external_id (+ identity_hash) for an identified user, user.subscription_id for an anonymous one; while offline, the record waits in the queue.

User preferences

lifecycleScope.launch {
    val result = Pushizo.User.getPreferences()            // result.preferences: [HsPreference], result.categories: [HsMessageCategory]
    Pushizo.User.setPreferences(listOf(
        HsPreferenceInput("promos", channel = null, optedIn = false),        // opt out on all channels
        HsPreferenceInput("orders", channel = "android_push", optedIn = true),
    ))
}
// Java/bridges: Pushizo.User.getPreferences { r -> } and Pushizo.User.setPreferences(list, callback)

If there is no subscription yet, IllegalStateException is thrown. HsPreference: category, channel (null = all channels), optedIn, explicit, source, updatedAt.

Notification channels

Dashboard → Settings → Android notification categories (/config → android_channels): the SDK creates/updates a NotificationChannel at initialization and on every config refresh (importance: low/default/high/urgent; sound → res/raw/<name>; vibration; group). On an existing channel, Android only updates the name/description/group. A push carrying android_channel_id uses that channel; otherwise Options.defaultChannelId.

In-app messages

Pushizo.InAppMessages.addTrigger("level", "gold")          // addTriggers(map), removeTrigger(s), clearTriggers(), getTriggers()
Pushizo.InAppMessages.setScreen("cart")                    // while the Activity/Composable is visible; setScreen(null) when leaving
Pushizo.Session.sendEvent("cart_viewed")
Pushizo.InAppMessages.paused = true
Pushizo.InAppMessages.addClickListener { e -> /* e.messageId, e.actionId, e.url */ }
Pushizo.InAppMessages.addLifecycleListener(object : HsInAppLifecycleListener {
    override fun onWillDisplay(event: HsInAppLifecycleEvent) {}
    override fun onDidDisplay(event: HsInAppLifecycleEvent) {}
    override fun onWillDismiss(event: HsInAppLifecycleEvent) {}
    override fun onDidDismiss(event: HsInAppLifecycleEvent) {}
})

Rendering: a Dialog with native Views on top of the resumed Activity (no Compose required). If the Activity stops, the message is silently removed and shown again in the next Activity. Trigger rules, frequency and actions (push_prompt calls requestPermission on Android 13+) are identical across all SDKs. Custom rendering: Pushizo.InAppMessages.setRenderer(HsInAppRenderer).

Notification inbox

lifecycleScope.launch {
    val page = Pushizo.Inbox.list(limit = 20, cursor = null)  // page.items, page.unreadCount, page.nextCursor, page.hasMore
    Pushizo.Inbox.markRead(page.items.first().id)
    Pushizo.Inbox.markAllRead()
    Pushizo.Inbox.archive(id)
    Pushizo.Inbox.unreadCount()
}
val inboxObserver = HsInboxObserver { event -> badge.text = event.unreadCount.toString() } // event.type, event.itemId
Pushizo.Inbox.addObserver(inboxObserver)              // on the main thread; remove with removeObserver
// Java/bridges: Pushizo.Inbox.list(20, null) { result -> result.getOrNull() }  (HsCallback)

The observer event is HsInboxChangeEvent(type, itemId, unreadCount): read, read_all and archived are always reported; listed and count only when the unread count changes.

Content cards

lifecycleScope.launch {
    val feed = Pushizo.ContentCards.list(limit = 20)   // feed.cards, feed.unviewedCount
    Pushizo.ContentCards.logImpression(feed.cards.first().id)
    Pushizo.ContentCards.logClick(id)                  // click (also counts as an impression)
    Pushizo.ContentCards.dismiss(id)                   // removes it from the feed
}

Ready-made view HsContentCardsView: loading, empty and error states; an impression when a card is half visible; opening the link on tap (if onCardClick returns true, the app handles it); dismissing with ×; dark theme. Override the texts with the hs_cards_* resources.

Cards do not appear in the notification inbox; the feed is ordered pinned → priority → newest. limit is 1-100 (default 50). Log an impression when a card is shown and a click when it is tapped; the stats appear on the campaign detail page.

Live chat

Pushizo.Chat.show(context)        // full-screen ready-made chat screen; Pushizo.Chat.hide() closes it

val chat = HsChatView(context)    // embed it in your own screen
chat.onCloseRequested = { finish() }
chat.onAttachRequested = { pickFile.launch(chat.attachmentMimeTypes) } // result: chat.sendAttachment(uri)

The ready-made UI loads the chat settings and history, starts live listening and marks incoming messages as read. It has loading, error, email pre-chat form and offline message form states, plus attachments, bot quick replies, delivery status and a typing indicator. The theme and accent color follow the app settings; right-to-left languages and TalkBack are supported. The texts ship in 22 languages and can be overridden with the hs_chat_* resources. For your own UI use Pushizo.Chat (start, getMessages, sendMessage, addListener, startListening).

Delivery hardening

On manufacturers such as Xiaomi, Huawei, Honor, Oppo, Realme, OnePlus, Vivo and Samsung, the battery and auto-start manager can stop the app in the background; notifications are delayed or never arrive. Pushizo.Delivery reads the device status and takes the user to the relevant settings screen (ADR-0092). No extra permission is needed. Detailed guide: Android delivery hardening.

val status = Pushizo.Delivery.status()        // manufacturer, ROM, battery exemption, background restriction, bucket, risk
if (Pushizo.Delivery.shouldShowGuidance()) {   // there is a risk and the dialog was not shown in the last 14 days
    Pushizo.Delivery.showGuidance(activity) { opened -> /* whether a settings screen opened */ }
}
Pushizo.Delivery.openSettings(context, HsDeliverySetting.AUTO_START) // directly from your own UI
  • status(): vendor, rom, romVersion, notificationsEnabled, channelBlocked, batteryOptimizationExempt, backgroundRestricted, standbyBucket, powerSaveMode, dataSaverEnabled, risk (NONE/ELEVATED/HIGH), recommendedSettings. Because Android does not expose the auto-start permission, the risk is ELEVATED on aggressive manufacturers when there is no battery exemption.
  • openSettings(context, setting): AUTO, NOTIFICATIONS, AUTO_START, BATTERY_OPTIMIZATION, APP_DETAILS. The manufacturer's screen is tried first; if it does not exist on the device or cannot be opened, the SDK falls back to a standard Android screen (battery optimization list → app details → settings). Returns true if a screen opened; never throws.
  • showGuidance(activity, setting, message, onResult): a ready-made dialog in 22 languages; the app can override the text with the names hs_delivery_title, hs_delivery_message, hs_delivery_message_vendor, hs_delivery_open_settings. The SDK never shows the dialog on its own.
  • Diagnostics (manufacturer, brand, rom, rom_version, delivery.*) go to the server in the subscription device field; they contain no personal data. Stable flags are written as soon as they change, the bucket and saver modes at most once a day. In the dashboard they appear as delivery rate by manufacturer on the Analytics → Android tab.
  • Delivery receipt: while the app is in the background the receipt is scheduled with WorkManager in addition to the persistent queue (it is sent even if the process is stopped), and it carries the moment the device received the message (received_at) and whether FCM lowered the priority (deprioritized).
  • For Android 11+ package visibility, the manufacturer settings packages are declared with <queries> in the SDK manifest; the app does not need to add anything.

Notification tray and payload fields

Pushizo.Notifications.clearAll()                           // all Pushizo notifications + group summaries
Pushizo.Notifications.removeNotification(event.notification.androidNotificationId)
Pushizo.Notifications.removeGroupedNotifications("orders") // android_group key
val shown = Pushizo.Notifications.setBadgeCount(3)         // written to later notifications; false = the badge cannot be shown
Pushizo.Notifications.clearBadge()                         // setBadgeCount(0)

Android has no standard API to set the launcher badge number; the badge is derived from the notifications in the tray. setBadgeCount stores the count and writes it to the notifications the SDK shows afterwards (setNumber; launchers that show a number, Android 8+). It returns false before Android 8, when notifications are disabled or when the channel badge is turned off.

Display keys the SDK reads from the FCM data:

KeyAPI fieldBehavior
hs_small_iconsmall_iconDrawable resource name; falls back to the manifest default, then to the SDK icon
hs_large_iconlarge_iconAn http(s) URL is downloaded, or a drawable/mipmap name
hs_accent_colorandroid_accent_colorAARRGGBB or RRGGBB
hs_visibilityandroid_visibility1 public, 0 private, -1 secret
hs_groupandroid_groupNotification group + summary (Android 7+)
hs_channelandroid_channel_idNotification channel
hs_soundandroid_soundres/raw sound (the channel sound takes precedence on Android 8+)

Behavior

  • Regional API root (ADR-0032 §4): if Options.apiUrl is left at its default, the config api_url is adopted and stored in SharedPreferences; on a 421 HS_WRONG_CELL response the SDK switches to the details.api_url root and retries the request once. Only https is accepted.
  • Token: onNewToken → PATCH /subscriptions/{id}; POST if there is no registration. App/OS version is updated every session.
  • Message: onMessageReceived → received record → display with NotificationCompat (title, body, big picture, icons, color, visibility, buttons, channel, collapse_key, group). Tap → opened + url/deep link intent.
  • Offline: a SharedPreferences queue; WorkManager (FlushWorker) sends it when the network is available. Sessions: session_start/session_end via ProcessLifecycleOwner.

Testing

cd sdk/android && gradle :pushizo:testDebugUnitTest, build with gradle :pushizo:assembleDebug; example: cd examples/android-kotlin && gradle :app:assembleDebug. From the emulator, the local API is http://10.0.2.2:4000.

Troubleshooting

SymptomCause / fix
Can't get a tokengoogle-services.json missing or package name mismatch; check the Pushizo tag in Logcat.
Subscription pendingNotification permission not granted (Android 13+) or notifications disabled in system settings.
SENDER_ID_MISMATCHThe service account in the dashboard belongs to a different Firebase project.
Notification not shownA foreground listener called preventDefault(), or the user disabled the channel.
In-app message doesn't showNo subscription, trigger not satisfied (names are case-sensitive), frequency limit reached, or paused; look for the "in-app listesi yenilendi" (in-app list refreshed) line with HsLog.Level.DEBUG.
Inbox.list → IllegalStateExceptionSubscription/user not registered yet; 403 → identityHash missing or wrong at login.

On this page