Android SDK - 方法参考

Android SDK - 方法参考

本综合参考文档记录了 Android 应用程序 Singular SDK 中所有可用的方法。SDK 提供初始化、事件追踪、收入报告、归因、数据隐私合规和配置等功能。每个方法都附有说明、签名和实用使用示例,帮助开发者将 Singular SDK 功能集成到其应用程序中。

adRevenue

Singular.adRevenue 方法

使用详细的广告数据信息追踪广告收入事件。此方法允许您报告应用程序中显示的广告所产生的收入。

签名

public static void adRevenue(SingularAdData adData);

使用示例

Kotlin Java
// Create ad data object
val adData = SingularAdData("AdMob", "USD", 0.05).apply {
    withAdUnitId("ca-app-pub-123456789/1234567890")
    withAdType("Rewarded")
    withAdPlacementName("level_complete")
}

// Track ad revenue event
Singular.adRevenue(adData)

clearGlobalProperties

Singular.clearGlobalProperties 方法

删除之前设置的所有全局归因。当您需要重置全局归因时很有用,例如用户从您的应用程序登出时。

签名

public static void clearGlobalProperties();

使用示例

Kotlin Java
// Clear all global properties
Singular.clearGlobalProperties()

createReferrerShortLink

Singular.createReferrerShortLink 方法

创建包含推荐人信息的短链接,可用于共享和归因。此方法生成可追踪的链接,可以与用户共享,允许您将安装和活动归因于特定的推荐来源。

签名

public static void createReferrerShortLink(String baseLink, String referrerName, String referrerId,
                                            JSONObject passthroughParams, ShortLinkHandler shortLinkHandler);

使用示例

Kotlin Java
// Create a short link for referral
val passthroughParams = JSONObject().apply {
    put("channel", "sms")
    put("campaign", "summer_promo")
}

Singular.createReferrerShortLink(
    "https://sample.sng.link/B4tbm/v8fp",
    "John Doe",
    "aq239897",
    passthroughParams,
    object : ShortLinkHandler {
        override fun onSuccess(link: String) {
            println("Generated short link: $link")
            // Share the link with users
        }

        override fun onError(error: String) {
            println("Error creating short link: $error")
        }
    }
)

customRevenue

Singular.customRevenue 方法

使用指定的事件名称、货币、金额和可选的产品信息追踪自定义收入事件。这允许使用自定义事件名称进行更具体的收入追踪。

传递 purchase对象时,SDK 仅在该对象是 com.android.billingclient.api.Purchase实例时才提取收据、签名和 SKU 详细信息。其他类型会回退为仅包含货币和金额的基本收入事件。

签名

public static boolean customRevenue(String eventName, String currency, double amount, Object purchase);

public static boolean customRevenue(String eventName, String currency, double amount, Object purchase,
                                    Map<String, Object> attributes);

public static boolean customRevenue(String eventName, String currency, double amount);

public static boolean customRevenue(String eventName, String currency, double amount,
                                    Map<String, Object> attributes);

public static boolean customRevenue(String eventName, String currency, double amount,
                                    String receipt, String receiptSignature);

public static boolean customRevenue(String eventName, String currency, double amount, String productSKU,
                                    String productName, String productCategory, int productQuantity,
                                    double productPrice);

public static boolean customRevenue(String eventName, JSONObject json);

使用示例

Kotlin Java
// Track a custom revenue event
Singular.customRevenue("premium_subscription", "USD", 9.99)

// Track a custom revenue event with attributes
val attributes = mapOf(
    "product_id" to "com.app.gems_pack_small",
    "quantity" to 1
)
Singular.customRevenue("in_app_purchase", "USD", 5.99, attributes)

// Track a custom revenue event from a pre-built JSON payload
val customRevenueJson = JSONObject().apply {
    put("currency", "USD")
    put("amount", 5.99)
    put("product_id", "com.app.gems_pack_small")
}
Singular.customRevenue("in_app_purchase", customRevenueJson)

event

Singular.event 方法

使用指定的名称和可选的自定义归因追踪事件。使用这些方法来追踪应用程序内的用户操作和互动。

可变参数重载需要键/值对,因此 args必须包含偶数个Meta素。奇数个Meta素会导致调用返回 false且不发送事件。

签名

public static boolean event(String name);

public static boolean event(String name, String extra);

public static boolean event(String name, Object... args);

使用示例

Kotlin Java
// Track a simple event
Singular.event("level_completed")

// Track an event with variable arguments
Singular.event("level_completed",
    "level_id", 5,
    "score", 12500,
    "time_spent", 120,
    "difficulty", "medium"
)

eventJSON

Singular.eventJSON 方法

使用包含自定义归因的 JSON 对象追踪事件。此方法为复杂的事件数据结构提供了更大的灵活性。

签名

public static boolean eventJSON(String name, final JSONObject json);

使用示例

Kotlin Java
// Track an event with JSON object
val eventData = JSONObject().apply {
    put("level_id", 5)
    put("score", 12500)
    put("time_spent", 120)
    put("difficulty", "medium")
}
Singular.eventJSON("level_completed", eventData)

getGlobalProperties

Singular.getGlobalProperties 方法

检索当前设置的所有全局归因。此方法返回一个包含 SDK 已设置的所有全局归因的映射。

签名

public static Map<String, String> getGlobalProperties();

使用示例

Kotlin Java
// Get all global properties
val properties = Singular.getGlobalProperties()
println("Global properties: $properties")

getLimitDataSharing

Singular.getLimitDataSharing 方法

检索当前的数据共享限制状态。此方法返回一个布尔值,指示数据共享当前是否受到限制。

如果 SDK 尚未初始化,无论之前通过 SingularConfig.withLimitDataSharing设置的值如何,都会返回 false。请始终在上下文中检查 false,而不是将其视为用户同意的证据。

签名

public static boolean getLimitDataSharing();

使用示例

Kotlin Java
// Check if data sharing is limited
val isLimited = Singular.getLimitDataSharing()
if (isLimited) {
    println("Data sharing is currently limited")
}

getSessionId

Singular.getSessionId 方法

返回当前会话 ID。可用于追踪并关联同一会话内的事件。

如果 SDK 尚未初始化,则返回 Constants.INVALID。在依赖此值之前,请始终调用 Singular.init()

签名

public static long getSessionId();

使用示例

Kotlin Java
// Get the current session ID
val sessionId = Singular.getSessionId()
println("Current session ID: $sessionId")

init

Singular.init 方法

使用提供的 API 密钥和密文,或者使用配置对象初始化 Singular SDK。这是您开始使用 Singular SDK 时应调用的第一个方法。

签名

public static boolean init(final Context context, final String apiKey, final String secret);

public static boolean init(final Context context, final SingularConfig config);

使用示例

Kotlin Java
// Simple initialization with API key and secret
Singular.init(context, "SDK KEY", "YOUR_SECRET")

// Initialize with configuration object
val config = SingularConfig("SDK KEY", "YOUR_SECRET")
    .withCustomUserId("user_123456")
    .withSessionTimeoutInSec(60)

Singular.init(context, config)

isAllTrackingStopped

Singular.isAllTrackingStopped 方法

检查所有追踪当前是否已停止。此方法返回一个布尔值,指示追踪当前是否已停止。

如果 SDK 尚未初始化,则返回 false。请将 false视为"未停止或未初始化",而不是"正在主动追踪"。

签名

public static boolean isAllTrackingStopped();

使用示例

Kotlin Java
// Check if tracking is stopped
if (Singular.isAllTrackingStopped()) {
    println("Tracking is currently stopped")
}

limitDataSharing

Singular.limitDataSharing 方法

设置数据共享限制状态。请根据用户同意或隐私要求使用此方法来限制数据共享。

签名

public static void limitDataSharing(boolean shouldLimitDataSharing);

使用示例

Kotlin Java
// To limit data sharing (e.g., when user opts out)
Singular.limitDataSharing(true)

// To enable full data sharing (e.g., when user opts in)
Singular.limitDataSharing(false)

onActivityPaused

Singular.onActivityPaused 方法

当 activity 暂停时通知 SDK。应从您的 activity 的 onPause() 方法中调用此方法,以追踪会话生命周期。

签名

public static void onActivityPaused();

使用示例

Kotlin Java
override fun onPause() {
    super.onPause()
    Singular.onActivityPaused()
}

onActivityResumed

Singular.onActivityResumed 方法

当 activity 恢复时通知 SDK。应从您的 activity 的 onResume() 方法中调用此方法,以追踪会话生命周期。

签名

public static void onActivityResumed();

使用示例

Kotlin Java
override fun onResume() {
    super.onResume()
    Singular.onActivityResumed()
}

resumeAllTracking

Singular.resumeAllTracking 方法

恢复之前停止的所有追踪活动。在追踪被停止后,使用此方法可重新启用追踪。

签名

public static void resumeAllTracking();

使用示例

Kotlin Java
// Resume tracking when user opts back in
Singular.resumeAllTracking()

revenue

Singular.revenue 方法

使用各种参数追踪收入事件,包括货币、金额和产品详细信息。这允许对您的应用程序进行全面的收入追踪。

传递 purchase对象时,SDK 仅在该对象是 com.android.billingclient.api.Purchase实例时才提取收据、签名和 SKU 详细信息。其他类型会回退为仅包含货币和金额的基本收入事件。

签名

public static boolean revenue(String currency, double amount, Object purchase);

public static boolean revenue(String currency, double amount, Object purchase, Map<String, Object> attributes);

public static boolean revenue(String currency, double amount);

public static boolean revenue(String currency, double amount, Map<String, Object> attributes);

public static boolean revenue(String currency, double amount, String receipt, String receiptSignature);

public static boolean revenue(String currency, double amount, String productSKU, String productName,
                              String productCategory, int productQuantity, double productPrice);

public static boolean revenue(JSONObject json);

使用示例

Kotlin Java
// Track revenue with currency and amount
Singular.revenue("USD", 9.99)

// Track revenue with additional attributes
val attributes = mapOf(
    "product_id" to "premium_gems",
    "quantity" to 2
)
Singular.revenue("USD", 19.98, attributes)

// Track revenue with Google Play purchase object
Singular.revenue("USD", 9.99, purchase)

// Track revenue with detailed product information
Singular.revenue("USD", 19.98,
    "SKU123456",
    "Premium Sword",
    "Weapons",
    2,
    9.99
)

// Track revenue from a pre-built JSON payload
val revenueJson = JSONObject().apply {
    put("currency", "USD")
    put("amount", 9.99)
    put("product_id", "premium_gems")
}
Singular.revenue(revenueJson)

setCustomUserId

Singular.setCustomUserId 方法

为当前用户设置自定义用户 ID。这允许您将 Singular 数据与您自己的用户标识系统关联起来。

签名

public static void setCustomUserId(String customUserId);

使用示例

Kotlin Java
// Set custom user ID after user logs in
Singular.setCustomUserId("user_123456")

setDeviceCustomUserId

已弃用功能: 请改用 setCustomUserId。

Singular.setDeviceCustomUserId 方法

在设备级别设置自定义用户 ID。这允许您在设备级别将 Singular 数据与您自己的用户标识系统关联起来。

签名

public static void setDeviceCustomUserId(String customUserId);

使用示例

Kotlin Java
// Set device-level custom user ID
Singular.setDeviceCustomUserId("device_user_123456")

setFCMDeviceToken

Singular.setFCMDeviceToken 方法

设置用于推送通知和卸载追踪的 FCM(Firebase Cloud Messaging)设备 token。在收到 FCM token 时应调用此方法。

签名

public static void setFCMDeviceToken(String fcmDeviceToken);

使用示例

Kotlin Java
// In your Firebase Messaging Service
override fun onNewToken(token: String) {
    super.onNewToken(token)
    Singular.setFCMDeviceToken(token)
}

setGCMDeviceToken

已弃用功能: 请改用 setFCMDeviceToken。

Singular.setGCMDeviceToken 方法

设置 GCM(Google Cloud Messaging)设备 token。此方法已弃用;对于 Firebase Cloud Messaging,请改用 setFCMDeviceToken。

签名

public static void setGCMDeviceToken(String gcmDeviceToken);

使用示例

Kotlin Java
// Deprecated - use setFCMDeviceToken instead
Singular.setGCMDeviceToken(token)

setGlobalProperty

Singular.setGlobalProperty 方法

设置将随所有事件一起发送的全局归因。这允许您为所有事件添加一致的归因,而无需每次都指定它们。

如果键为 null 或空,或 SDK 尚未初始化,或 SDK 已经持有最多 5 个全局归因,则返回 false。在假定归因已被保存之前,请检查返回值。

签名

public static boolean setGlobalProperty(final String key, final String value,
                                        final boolean overrideExisting);

使用示例

Kotlin Java
// Set a global property
val success = Singular.setGlobalProperty("user_tier", "premium", true)
if (success) {
    println("Global property set successfully")
}

setIMEI

Singular.setIMEI 方法

设置用于追踪的设备 IMEI。在允许且首选 IMEI 追踪的地区中使用。

签名

public static void setIMEI(String imei);

使用示例

Kotlin Java
// Set device IMEI
Singular.setIMEI("123456789012345")

setLimitAdvertisingIdentifiers

Singular.setLimitAdvertisingIdentifiers 方法

启用或禁用混合受众应用中广告标识符的使用。该选项影响 SDK 收集和使用设备标识符进行追踪的方式。

签名

public static void setLimitAdvertisingIdentifiers(boolean enabled);

使用示例

Kotlin Java
// Enable limited identifiers mode
Singular.setLimitAdvertisingIdentifiers(true)

setWrapperNameAndVersion

Singular.setWrapperNameAndVersion 方法

当通过包装器(例如 Unity、React Native)使用 SDK 时,设置包装器名称和版本。这有助于识别正在使用哪个包装器框架。

签名

public static void setWrapperNameAndVersion(final String wrapper, final String version);

使用示例

Kotlin Java
// Set wrapper information
Singular.setWrapperNameAndVersion("Unity", "1.2.3")

stopAllTracking

Singular.stopAllTracking 方法

停止所有追踪活动。当用户选择退出或出于隐私合规的目的禁用追踪时,请使用此方法。

签名

public static void stopAllTracking();

使用示例

Kotlin Java
// Stop tracking when user opts out
Singular.stopAllTracking()

trackingOptIn

Singular.trackingOptIn 方法

表明用户已选择加入追踪。当用户明确同意追踪和数据收集时,请调用此方法。

签名

public static void trackingOptIn();

使用示例

Kotlin Java
// User has opted in to tracking
Singular.trackingOptIn()

trackingUnder13

Singular.trackingUnder13 方法

表明用户未满 13 岁。请调用此方法以符合 COPPA 和其他针对 13 岁以下用户的法规。

签名

public static void trackingUnder13();

使用示例

Kotlin Java
// Notify Singular the user is under 13 years old
Singular.trackingUnder13()

unsetCustomUserId

Singular.unsetCustomUserId 方法

删除之前设置的自定义用户 ID。当用户登出或您不再希望将事件与当前用户 ID 关联时,请调用此方法。

签名

public static void unsetCustomUserId();

使用示例

Kotlin Java
// Clear custom user ID when user logs out
Singular.unsetCustomUserId()

unsetGlobalProperty

Singular.unsetGlobalProperty 方法

删除之前设置的全局归因。当您不再希望特定全局归因随事件一起发送时,请调用此方法。

签名

public static void unsetGlobalProperty(String key);

使用示例

Kotlin Java
// Remove a global property
Singular.unsetGlobalProperty("user_tier")