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.
الأدلة متوفرة باللغة الإنجليزية.
Supported platforms
| Platform | Package | Notes |
|---|---|---|
| Android (Kotlin or Java) | com.contlo:android-core | Minimum Android SDK level 19. Uses Firebase Cloud Messaging for push. |
| iOS (Swift or Objective-C) | Contlo-iOS-SDK on CocoaPods | Minimum iOS 11.0. Uses APNs for push. |
| React Native | contlo-react-native-sdk on npm | Wraps the Android SDK. The package does not include an iOS implementation, so use it for Android builds. |
| Expo | superagi-expo-sdk on npm | Wraps 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
- In Contlo, open App Market, find Contlo SDK and install it.
- 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.
- 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.
- For Android, add Firebase to your app (the
google-services.jsonfile 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.xmlas<meta-data android:name="contlo_api_key" android:value="YOUR_API_KEY" />inside<application>and callContlo.init(this). - Android: to know whether initialization worked, pass a
ContloCallbackas the third argument. It receivesContlo Initializedon success andInvalid API Keyif no key was found. - React Native and Expo on Android: the JavaScript
initcall does not registerContloSDKLifecycleCallbacks. To record app opens automatically, register it in your nativeMainApplicationas shown in the Android tab.
What the SDK records on its own
| Moment | Android event | iOS event |
|---|---|---|
| First launch after install | mobile_app_installed | Mobile_App_Installed |
| First launch after an app update | mobile_app_updated | Mobile_App_Updated |
| App comes to the foreground | mobile_app_launched | Mobile_App_Launched |
| App goes to the background | mobile_app_backgrounded | Mobile_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 Addedis stored asWishlist_Item_Added. Use lowercasesnake_casenames 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
ContloCallbackas the last argument ofsendEventto receive the result. - On iOS,
Contlo.disableTracking(disable: true)stops all events until you turn tracking back on. Calls made in the meantime returnTracking 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)orContlo.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.
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.
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
ContloSDKLifecycleCallbackswhen the target activity is created. If the activity is already open and receives the link throughonNewIntent, 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.
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.
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 assendAdvertisingId(consent).
Troubleshooting
| What you see | Cause and fix |
|---|---|
Invalid API Key on Android | No 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 initialized | A method was called before Contlo.init. Initialize in your Application class so it always runs first. |
All identifiers are empty, cannot send Event | The 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-core | The 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 linked | Rebuild the app after installing the package. The package does not work in Expo Go. |
| Push arrives but taps are not counted on Android | ContloSDKLifecycleCallbacks is not registered, or the link is delivered to an activity that is already open. See Notification clicks and deep links. |
| No push on iOS | Check 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. |
أدلة ذات صلة
- REST APISend contacts and events to Contlo from your server: authentication, the identify and track endpoints, request and response examples, limits and errors.
- Track events and identify visitorsUse the Contlo browser methods to tell Contlo who a visitor is and what they did, then use those events in segments, automations and analytics.
- Push settingsDesign the web push opt-in prompt for your store and add the Firebase and APNs credentials that let Contlo send mobile push to your app.
- Push campaignsSend web push and mobile push campaigns: title, message, image, link or deep link, buttons, expiry and test sends.
- API keys, webhooks and callback URLsFind your public API key, create and revoke private API keys, and learn where webhooks and callback URLs live in Contlo.