Saltar al contenido
Contlo by QuestionPro
Explorar la documentación

Mobile SDKs

The Contlo mobile SDKs connect your app to the same contacts, events and automations as your website. Once the SDK is in, Contlo knows who is using the app and what they do there, and can send them mobile push notifications that bring them back to finish an order or buy again.

App Market → Contlo SDKAndroid · iOS · React Native · ExpoIdentify, events, push

Las guías están en inglés.

Supported platforms

PlatformPackageNotes
Android (Kotlin or Java)com.contlo:android-coreMinimum Android SDK level 19. Uses Firebase Cloud Messaging for push.
iOS (Swift or Objective-C)Contlo-iOS-SDK on CocoaPodsMinimum iOS 11.0. Uses APNs for push.
React Nativecontlo-react-native-sdk on npmWraps the Android SDK. The package does not include an iOS implementation, so use it for Android builds.
Exposuperagi-expo-sdk on npmWraps the Android and iOS SDKs. It contains native code, so it needs a development build and does not run in Expo Go.

Before you start

  1. In Contlo, open App Market, find Contlo SDK and install it.
  2. On the Contlo SDK page, copy the key shown under Private API key. This is the key you pass to the SDK when you initialize it.
  3. For push notifications, add your credentials on the Mobile Push settings page, reached from Settings → Channels: the Firebase service account for Android and the APNs configuration for iOS. See Push settings.
  4. For Android, add Firebase to your app (the google-services.json file and the Google services Gradle plugin). The SDK uses Firebase Cloud Messaging to get the device token.

Install the SDK

// settings.gradle
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url "https://nexus.contlo.com/repository/contlo-android-sdk" }
    }
}

// app/build.gradle
dependencies {
    implementation 'com.contlo:android-core:1.2.0'
}

Initialize with your API key

Initialize once, as early as possible in the app's life. The SDK stores the key and fetches its configuration from Contlo.

import android.app.Application
import com.contlo.core.main.Contlo
import com.contlo.core.lifecycle.ContloSDKLifecycleCallbacks

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Contlo.init(this, "YOUR_API_KEY")
        // Reports app opens, backgrounding and notification taps
        registerActivityLifecycleCallbacks(ContloSDKLifecycleCallbacks(applicationContext))
    }
}
  • Android: instead of passing the key in code, you can add it to AndroidManifest.xml as <meta-data android:name="contlo_api_key" android:value="YOUR_API_KEY" /> inside <application> and call Contlo.init(this).
  • Android: to know whether initialization worked, pass a ContloCallback as the third argument. It receives Contlo Initialized on success and Invalid API Key if no key was found.
  • React Native and Expo on Android: the JavaScript init call does not register ContloSDKLifecycleCallbacks. To record app opens automatically, register it in your native MainApplication as shown in the Android tab.

What the SDK records on its own

MomentAndroid eventiOS event
First launch after installmobile_app_installedMobile_App_Installed
First launch after an app updatemobile_app_updatedMobile_App_Updated
App comes to the foregroundmobile_app_launchedMobile_App_Launched
App goes to the backgroundmobile_app_backgroundedMobile_App_Backgrounded

Every event also carries device details: app name, app version, OS type and source set to Mobile. On Android it also includes the package name, OS version, device model, manufacturer, network type and time zone.

Identify the user

Call this when someone signs up or logs in. It creates or updates the contact in Contlo and ties this device to it. Later events from the device are credited to that contact without passing the email or phone again.

import com.contlo.core.main.Contlo
import com.contlo.core.model.ContloAudience

val audience = ContloAudience(
    userFirstName = "Ada",
    userLastName = "Lovelace",
    userEmail = "ada@example.com",
    userPhone = "+14155550123",
    userCity = "San Francisco",
    userCountry = "United States",
    userZip = "94107",
    customProperties = hashMapOf("loyalty_tier" to "gold")
)

// Second argument: true when updating an existing contact
Contlo.sendUserData(audience, false)
  • Send an email, a phone number or both. On iOS, a call with neither returns Either Email or Phone is mandatory.
  • Custom property values must be strings on every platform.
  • Send phone numbers with a plus sign and country code.
  • When the user logs out, clear the stored identity so the next person's activity is not credited to them: Contlo.logoutUser() on Android, Contlo.logout() on iOS.

Track events

// Name only
Contlo.sendEvent("wishlist_item_added")

// With event properties and contact properties
Contlo.sendEvent(
    "wishlist_item_added",
    null,   // email: null reuses the identified user
    null,   // phone: null reuses the identified user
    hashMapOf("product_id" to "SKU-1042", "price" to "129.00"),
    hashMapOf("last_wishlist_category" to "running")
)
  • Property values must be strings. Convert numbers and booleans before you send them.
  • Spaces in an event name are replaced with underscores, so Wishlist Item Added is stored as Wishlist_Item_Added. Use lowercase snake_case names to keep web and app events consistent. See naming advice.
  • An event needs someone to belong to. On Android, if there is no email, phone or device token yet, the call fails with All identifiers are empty, cannot send Event.
  • On Android, pass a ContloCallback as the last argument of sendEvent to receive the result.
  • On iOS, Contlo.disableTracking(disable: true) stops all events until you turn tracking back on. Calls made in the meantime return Tracking is disabled.
  • In React Native and Expo, set contact properties with the identify call rather than with an event.

Events from the app appear in the same places as web events: segment conditions, automation triggers and Analytics → Events. See where events show up.

Register for push notifications

Contlo sends mobile push through Firebase Cloud Messaging on Android and APNs on iOS. The SDK collects the device token and the user's permission and attaches both to the contact.

Android

  • The SDK registers its own Firebase messaging service, so Contlo notifications are received and displayed without extra code.
  • On Android 13 and later, ask the user for the notification permission yourself, then tell Contlo the answer with Contlo.sendPushConsent(true) or Contlo.sendPushConsent(false).
  • If your app already has its own FirebaseMessagingService, forward messages and tokens to Contlo from it, as shown below. Contlo handles only its own messages and ignores the rest, so your other notifications keep working.
Android: your own FirebaseMessagingService
import com.contlo.core.push.ContloNotification
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        ContloNotification.processContloNotification(this, message)
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        ContloNotification.updateFcmToken(this, token)
    }
}

iOS

Turn on the Push Notifications capability for your app target, then ask for permission, register with APNs and pass the device token to Contlo as a hex string.

iOS: AppDelegate
import UserNotifications
import Contlo_iOS_SDK

func registerForPushNotifications() {
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
        guard granted else { return }
        Contlo.setNotificationPermission(granted: true)
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    Contlo.sendDeviceToken(token: token)
}

React Native and Expo

import { PermissionsAndroid, Platform } from 'react-native';
import * as Contlo from 'contlo-react-native-sdk';

async function enablePush() {
  if (Platform.OS === 'android' && Platform.Version >= 33) {
    await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
  }
  Contlo.subscribeToMobilePush();
}

Notification clicks and deep links

A Contlo push notification can carry a title, body, subtitle, image, a main link and up to two buttons, each with its own link. You set these when you build the message. See Push campaigns.

Android

  • Tapping the notification or a button opens its link with a standard view intent. For a deep link such as myapp://orders/123, declare an intent filter for that scheme and host on the activity that should open. Web links open in the browser. A button without a link opens your app's launch screen.
  • Delivery and dismissal are reported to Contlo automatically.
  • Taps are reported by ContloSDKLifecycleCallbacks when the target activity is created. If the activity is already open and receives the link through onNewIntent, report the tap yourself, as shown below. The React Native package already does this for you.
  • Notifications are posted on a notification channel named Marketing Channel.
Android: activity that receives deep links
import android.content.Intent
import com.contlo.core.lifecycle.LifecycleHandler

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    LifecycleHandler.handleNewIntent(intent, this)
    // then route to the right screen using intent.data
}

iOS

Report the tap to Contlo from your notification center delegate. The SDK records the click. Opening the right screen is up to your app, using the notification's userInfo.

iOS: UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    Contlo.registerNotificationClick(response: response)
    // route to the right screen here
    completionHandler()
}

To report delivery on iOS, call Contlo.registerNotificationReceive(request:) with the incoming UNNotificationRequest, for example from a notification service extension.

Clicks, deliveries and dismissals feed your push reports. See Campaign reports.

In-app messages and advertising ID

  • In-app messages: the SDK packages described here cover identity, events and push. They do not include a component for displaying in-app messages.
  • Advertising ID (Android): if the user has agreed to ad tracking, call Contlo.sendAdvertisingId(true) to attach the device's advertising ID to the contact. The React Native package exposes the same call as sendAdvertisingId(consent).

Troubleshooting

What you seeCause and fix
Invalid API Key on AndroidNo key reached the SDK. Pass it to Contlo.init or add the contlo_api_key meta-data entry to the manifest.
Contlo SDK has not been initializedA method was called before Contlo.init. Initialize in your Application class so it always runs first.
All identifiers are empty, cannot send EventThe event was sent before the user was identified and before a device token was available. Identify the user first, or check your Firebase setup.
Gradle cannot resolve com.contlo:android-coreThe Contlo Maven repository is missing from your repositories block. In React Native and Expo projects, add it to android/build.gradle.
The package 'contlo-react-native-sdk' doesn't seem to be linkedRebuild the app after installing the package. The package does not work in Expo Go.
Push arrives but taps are not counted on AndroidContloSDKLifecycleCallbacks is not registered, or the link is delivered to an activity that is already open. See Notification clicks and deep links.
No push on iOSCheck that the device token reaches Contlo.sendDeviceToken, that the user granted permission, and that your APNs key, Key ID, Team ID and App Bundle ID are saved in Contlo.

Guías relacionadas

¿No encuentras algo? Escríbenos