### Enable Auto-Tracking Events in Android SDK Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Enables automatic tracking of common user events such as app start, end, screen views, clicks, crashes, and installs using the ThinkingData Android SDK. This feature simplifies event collection by eliminating the need for manual tracking code. It supports enabling multiple event types, adding custom properties to all auto-tracked events, or customizing properties per event via a callback. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDAnalytics.TDAutoTrackEventType; import org.json.JSONObject; // Enable multiple auto-track event types int autoTrackTypes = TDAutoTrackEventType.APP_START | TDAutoTrackEventType.APP_END | TDAutoTrackEventType.APP_VIEW_SCREEN | TDAutoTrackEventType.APP_CLICK | TDAutoTrackEventType.APP_CRASH | TDAutoTrackEventType.APP_INSTALL; TDAnalytics.enableAutoTrack(autoTrackTypes); // Enable with custom properties for all auto-track events JSONObject autoTrackProps = new JSONObject(); autoTrackProps.put("app_version", "2.0.0"); autoTrackProps.put("platform", "android"); TDAnalytics.enableAutoTrack(autoTrackTypes, autoTrackProps); // Enable with callback to customize properties per event TDAnalytics.enableAutoTrack(autoTrackTypes, new TDAnalytics.TDAutoTrackEventHandler() { @Override public JSONObject getAutoTrackEventProperties(int eventType, JSONObject properties) { JSONObject customProps = new JSONObject(); try { if (eventType == TDAutoTrackEventType.APP_START) { customProps.put("launch_source", "notification"); } else if (eventType == TDAutoTrackEventType.APP_VIEW_SCREEN) { customProps.put("screen_orientation", "portrait"); } } catch (Exception e) { e.printStackTrace(); } return customProps; } }); ``` -------------------------------- ### Track Event Duration in Android SDK Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Enables measuring event duration by starting a timer for an event and automatically adding the duration property when the event is tracked. The duration is calculated in seconds between the `timeEvent` call and the `track` call. Dependencies include the TDAnalytics SDK and JSONObject. ```java import cn.thinkingdata.analytics.TDAnalytics; import org.json.JSONObject; // Start timing for an event TDAnalytics.timeEvent("video_watch"); // ... user watches video ... // When event is tracked, #duration property is automatically added (in seconds) JSONObject videoProps = new JSONObject(); videoProps.put("video_id", "vid_12345"); videoProps.put("video_title", "Introduction Tutorial"); videoProps.put("video_length", 300); TDAnalytics.track("video_watch", videoProps); // Result: event includes "#duration": 45.5 (time between timeEvent and track) // Example: Track page view duration TDAnalytics.timeEvent("page_view"); // ... user browses page ... JSONObject pageProps = new JSONObject(); pageProps.put("page_name", "Product Details"); pageProps.put("product_id", "prod_999"); TDAnalytics.track("page_view", pageProps); ``` -------------------------------- ### Create and Use Light SDK Instance (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Demonstrates how to create a lightweight SDK instance for tracking passive events without local caching. This instance can be used to track events and set temporary identities. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.ThinkingAnalyticsSDK; import org.json.JSONObject; // Create a light instance and get its identifier String lightInstanceId = TDAnalytics.lightInstance(); // Access the light instance from the instances map ThinkingAnalyticsSDK lightSDK = TDAnalytics.sInstances.get(lightInstanceId); if (lightSDK != null) { // Track events using the light instance JSONObject props = new JSONObject(); props.put("notification_type", "push"); props.put("notification_id", "notif_12345"); lightSDK.track("notification_received", props); // Set temporary identity for this instance lightSDK.identify("temp_visitor_abc"); lightSDK.login("background_user_123"); // Light instances don't persist identity to local storage lightSDK.logout(); } ``` -------------------------------- ### Initialize ThinkingData SDK for Android Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Initializes the ThinkingData SDK for Android with basic or custom configurations. This step is mandatory before any tracking functions can be used. It requires the application context, App ID, and server URL. Custom configurations include setting the running mode, time zone, and multi-process support. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDConfig; import android.app.Application; import java.util.TimeZone; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Simple initialization TDAnalytics.init(this, "YOUR_APP_ID", "https://your-server-url.com"); // Or with custom configuration TDConfig config = TDConfig.getInstance(this, "YOUR_APP_ID", "https://your-server-url.com"); config.setMode(TDConfig.TDMode.DEBUG); // Enable debug mode for development config.setDefaultTimeZone(TimeZone.getTimeZone("UTC")); config.setMutiprocess(true); // Enable multi-process support TDAnalytics.init(config); // Enable debug logging TDAnalytics.enableLog(true); } } ``` -------------------------------- ### Configure Data Encryption (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Shows how to enable data encryption for secure analytics data transmission using either a version and public key or a custom secret key configuration. It also covers enabling local storage encryption. ```java import cn.thinkingdata.analytics.TDConfig; import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.encrypt.TDSecreteKey; // Method 1: Enable encryption with version and public key TDConfig config = TDConfig.getInstance(this, "YOUR_APP_ID", "https://your-server-url.com"); config.enableEncrypt(1, "YOUR_RSA_PUBLIC_KEY"); TDAnalytics.init(config); // Method 2: Enable encryption with custom secret key configuration TDConfig config2 = TDConfig.getInstance(this, "YOUR_APP_ID_2", "https://your-server-url.com"); TDSecreteKey secretKey = new TDSecreteKey(); secretKey.version = 1; secretKey.publicKey = "YOUR_RSA_PUBLIC_KEY"; secretKey.asymmetricEncryption = "RSA"; secretKey.symmetricEncryption = "AES"; config2.setSecretKey(secretKey); config2.enableEncrypt(true); TDAnalytics.init(config2); // Enable local storage encryption TDAnalytics.encryptLocalStorage(); ``` -------------------------------- ### Enable Third-Party Data Sharing (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Explains how to enable integration with third-party analytics platforms for data synchronization. This can be done with platform type flags or with additional parameters for specific integrations. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.ThinkingAnalyticsSDK; // Enable third-party sharing for specific platforms // Use bitwise OR to combine multiple platform types int thirdPartyTypes = 1 | 2 | 4; // Example platform type flags TDAnalytics.enableThirdPartySharing(thirdPartyTypes); // Enable with additional parameters Object extraParams = new HashMap() { { put("api_key", "third_party_api_key"); put("custom_param", "value"); } }; TDAnalytics.enableThirdPartySharing(1, extraParams); ``` -------------------------------- ### Access Preset Properties in Android SDK Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Provides access to preset device and system properties that are automatically collected by the SDK. These properties include device model, OS version, network type, screen dimensions, and more. Dependencies include the TDAnalytics SDK and TDPresetProperties. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDPresetProperties; // Get all preset properties TDPresetProperties presetProps = TDAnalytics.getPresetProperties(); // Access individual preset properties String bundleId = presetProps.bundleId; // Package name String carrier = presetProps.carrier; // Mobile carrier String deviceId = presetProps.deviceId; // Device ID String deviceModel = presetProps.deviceModel; // Device model (e.g., "Pixel 6") String manufacture = presetProps.manufacture; // Manufacturer (e.g., "Google") String networkType = presetProps.networkType; // Network type (WiFi, 4G, etc.) String os = presetProps.os; // Operating system ("Android") String osVersion = presetProps.osVersion; // OS version (e.g., "13") int screenHeight = presetProps.screenHeight; // Screen height in pixels int screenWidth = presetProps.screenWidth; // Screen width in pixels String systemLanguage = presetProps.systemLanguage; // System language double zoneOffset = presetProps.zoneOffset; // Timezone offset String appVersion = presetProps.appVersion; // App version String installTime = presetProps.installTime; // App install time boolean isSimulator = presetProps.isSimulator; // Is running on simulator String ram = presetProps.ram; // RAM info String disk = presetProps.disk; // Disk info int fps = presetProps.fps; // Frame rate String deviceType = presetProps.deviceType; // Device type // Convert to JSONObject for custom use JSONObject presetJSON = presetProps.toEventPresetProperties(); ``` -------------------------------- ### View Screen and Click Tracking - Java Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Manually trigger screen view tracking for Activities and Fragments, and customize click tracking behavior. Allows setting custom view IDs, properties, and ignoring specific views or view types. ```java import cn.thinkingdata.analytics.TDAnalytics; import android.app.Activity; import android.app.Fragment; import android.view.View; import android.app.Dialog; import org.json.JSONObject; // Manually track Activity screen view TDAnalytics.trackViewScreen(this); // 'this' is an Activity // Track Fragment screen view Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); TDAnalytics.trackViewScreen(fragment); // Enable automatic Fragment tracking TDAnalytics.trackFragmentAppViewScreen(); // Set custom view ID for click tracking View button = findViewById(R.id.purchase_button); TDAnalytics.setViewID(button, "purchase_btn_main"); // Set custom view ID for Dialog Dialog dialog = new AlertDialog.Builder(this).create(); TDAnalytics.setViewID(dialog, "confirmation_dialog"); // Set custom properties for view clicks JSONObject viewProps = new JSONObject(); viewProps.put("button_type", "primary"); viewProps.put("button_location", "header"); TDAnalytics.setViewProperties(button, viewProps); // Ignore specific view from click tracking View adBanner = findViewById(R.id.ad_banner); TDAnalytics.ignoreView(adBanner); // Ignore specific view type from click tracking TDAnalytics.ignoreViewType(AdView.class); // Ignore specific activities from auto-tracking TDAnalytics.ignoreAutoTrackActivity(SplashActivity.class); // Ignore multiple activities List> ignoredActivities = new ArrayList<>(); ignoredActivities.add(SplashActivity.class); ignoredActivities.add(DebugActivity.class); TDAnalytics.ignoreAutoTrackActivities(ignoredActivities); ``` -------------------------------- ### Control SDK Tracking Status - Java Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Manage the SDK's tracking behavior by setting different track statuses like PAUSE, STOP, SAVE_ONLY, and NORMAL. Includes methods for forcing data flushes and setting network types for uploads. ```java import cn.thinkingdata.analytics.TDAnalytics; import cn.thinkingdata.analytics.TDAnalytics.TDTrackStatus; // Pause tracking (stops data collection, resumes with NORMAL) TDAnalytics.setTrackStatus(TDTrackStatus.PAUSE); // Stop tracking completely (clears cache and resets identities) TDAnalytics.setTrackStatus(TDTrackStatus.STOP); // Save only mode (collects data but doesn't upload) TDAnalytics.setTrackStatus(TDTrackStatus.SAVE_ONLY); // Resume normal tracking and reporting TDAnalytics.setTrackStatus(TDTrackStatus.NORMAL); // Force flush cached data to server TDAnalytics.flush(); // Set network type for data upload TDAnalytics.setNetworkType(TDAnalytics.TDNetworkType.WIFI); // Only upload on WiFi TDAnalytics.setNetworkType(TDAnalytics.TDNetworkType.ALL); // Upload on all networks ``` -------------------------------- ### Manage User Identification: Login, Logout, and Distinct IDs (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt This Java code snippet illustrates how to manage user identification within the ThinkingData Android SDK. It covers logging users in and out using account IDs, setting custom distinct IDs to track users across devices, and retrieving current user identifiers. This functionality is crucial for accurate user tracking and analysis. ```java import cn.thinkingdata.analytics.TDAnalytics; // Set account ID when user logs in TDAnalytics.login("user_account_123456"); // Set custom distinct ID (replaces default UUID) TDAnalytics.setDistinctId("custom_visitor_id_789"); // Get current identifiers String distinctId = TDAnalytics.getDistinctId(); String accountId = TDAnalytics.getAccountId(); String deviceId = TDAnalytics.getDeviceId(); // Log current user info System.out.println("Distinct ID: " + distinctId); System.out.println("Account ID: " + accountId); System.out.println("Device ID: " + deviceId); // Clear account ID on logout TDAnalytics.logout(); ``` -------------------------------- ### Manage User Properties: Set, Add, Append, Unset, Delete (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt This Java code demonstrates various operations for managing user profile properties using the ThinkingData Android SDK. It includes setting properties (set, setOnce), modifying numeric properties (add), appending to array properties (append, uniqAppend), removing properties (unset), and deleting the entire user profile. These methods allow for comprehensive user data management. ```java import cn.thinkingdata.analytics.TDAnalytics; import org.json.JSONObject; import org.json.JSONArray; // Set user properties (overwrites existing values) JSONObject userProps = new JSONObject(); userProps.put("name", "John Doe"); userProps.put("email", "john@example.com"); userProps.put("membership_level", "gold"); userProps.put("age", 28); TDAnalytics.userSet(userProps); // Set user properties only once (ignores if already set) JSONObject onceProps = new JSONObject(); onceProps.put("first_login_date", "2024-01-01"); onceProps.put("registration_source", "organic"); TDAnalytics.userSetOnce(onceProps); // Increment numeric user properties JSONObject addProps = new JSONObject(); addProps.put("login_count", 1); addProps.put("total_purchases", 49.99); addProps.put("points_earned", 100); TDAnalytics.userAdd(addProps); // Append to array user properties JSONObject appendProps = new JSONObject(); JSONArray purchasedItems = new JSONArray(); purchasedItems.put("item_001"); purchasedItems.put("item_002"); appendProps.put("purchased_items", purchasedItems); TDAnalytics.userAppend(appendProps); // Append unique values to array (no duplicates) JSONObject uniqAppendProps = new JSONObject(); JSONArray categories = new JSONArray(); categories.put("electronics"); categories.put("books"); uniqAppendProps.put("browsed_categories", categories); TDAnalytics.userUniqAppend(uniqAppendProps); // Remove specific user properties TDAnalytics.userUnset("temporary_flag", "old_preference"); // Delete user completely (irreversible) TDAnalytics.userDelete(); ``` -------------------------------- ### WebView Integration (H5 Bridge) - Java Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Facilitate data integration between the native Android SDK and H5/WebView content in hybrid applications. Supports standard WebViews and Tencent X5 WebViews. ```java import cn.thinkingdata.analytics.TDAnalytics; import android.webkit.WebView; public class WebViewActivity extends Activity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webView = findViewById(R.id.webview); // Enable JavaScript bridge for standard WebView TDAnalytics.setJsBridge(webView); // For Tencent X5 WebView // com.tencent.smtt.sdk.WebView x5WebView = ... // TDAnalytics.setJsBridgeForX5WebView(x5WebView); webView.loadUrl("https://your-web-app.com"); } } ``` -------------------------------- ### Track Custom Events in Android SDK Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Tracks custom events with optional properties, timestamps, and time zones using the ThinkingData Android SDK. This allows for detailed user interaction and behavior analysis. Properties can be any number of key-value pairs, and custom timestamps enable precise event logging. ```java import cn.thinkingdata.analytics.TDAnalytics; import org.json.JSONObject; import java.util.Date; import java.util.TimeZone; // Track simple event TDAnalytics.track("button_click"); // Track event with properties JSONObject properties = new JSONObject(); properties.put("product_name", "Premium Subscription"); properties.put("price", 9.99); properties.put("currency", "USD"); properties.put("category", "subscription"); TDAnalytics.track("purchase", properties); // Track event with custom timestamp and timezone JSONObject eventProps = new JSONObject(); eventProps.put("level", 10); eventProps.put("score", 5000); TDAnalytics.track("level_complete", eventProps, new Date(), TimeZone.getTimeZone("America/New_York")); ``` -------------------------------- ### Calibrate SDK Time - Java Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Ensure accurate event timing by calibrating the SDK's time using either a server-provided timestamp or NTP servers. Also includes a method to retrieve the local region code. ```java import cn.thinkingdata.analytics.TDAnalytics; // Calibrate time with server timestamp (milliseconds since epoch) long serverTimestamp = 1705334400000L; // Get from your server TDAnalytics.calibrateTime(serverTimestamp); // Calibrate time using NTP servers TDAnalytics.calibrateTimeWithNtp("time.google.com", "pool.ntp.org", "time.apple.com"); // Get local region code String region = TDAnalytics.getLocalRegion(); // Returns country code like "US" ``` -------------------------------- ### Set Super Properties in Android SDK Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Allows setting static and dynamic public properties that are automatically included in every tracked event. Static properties are set once, while dynamic properties are evaluated at the time of tracking. Dependencies include the TDAnalytics SDK and JSONObject. ```java import cn.thinkingdata.analytics.TDAnalytics; import org.json.JSONObject; // Set static super properties (included in all events) JSONObject superProps = new JSONObject(); superProps.put("app_version", "3.2.1"); superProps.put("platform", "android"); superProps.put("country", "US"); superProps.put("language", "en"); TDAnalytics.setSuperProperties(superProps); // Set dynamic super properties (evaluated at track time) TDAnalytics.setDynamicSuperProperties(new TDAnalytics.TDDynamicSuperPropertiesHandler() { @Override public JSONObject getDynamicSuperProperties() { JSONObject dynamicProps = new JSONObject(); try { dynamicProps.put("session_duration", getSessionDuration()); dynamicProps.put("battery_level", getBatteryLevel()); dynamicProps.put("network_type", getCurrentNetworkType()); dynamicProps.put("timestamp_local", System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } return dynamicProps; } }); // Get all current super properties JSONObject currentSuperProps = TDAnalytics.getSuperProperties(); // Remove a specific super property TDAnalytics.unsetSuperProperty("temporary_campaign"); // Clear all super properties TDAnalytics.clearSuperProperties(); ``` -------------------------------- ### Register Error Callback (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt Provides a method to register callbacks for receiving notifications when the SDK encounters errors during data transmission. It includes handling different error codes and logging additional information. ```java import cn.thinkingdata.analytics.TDAnalytics; // Register error callback for data sending failures TDAnalytics.registerErrorCallback(new TDAnalytics.TDSendDataErrorCallback() { @Override public void onSDKErrorCallback(int code, String errorMsg, String ext) { // Handle SDK errors System.err.println("ThinkingData Error [" + code + "]: " + errorMsg); switch (code) { case 400: System.err.println("Bad request - check event format"); break; case 401: System.err.println("Authentication failed - check App ID"); break; case 500: System.err.println("Server error - data will be retried"); break; default: System.err.println("Unknown error occurred"); } // Log additional info if available if (ext != null && !ext.isEmpty()) { System.err.println("Additional info: " + ext); } } }); ``` -------------------------------- ### Track Special Event Types: First, Updatable, and Overwritable Events (Java) Source: https://context7.com/thinkingdataanalytics/android-sdk/llms.txt This snippet demonstrates how to track special event types in the ThinkingData Android SDK. It covers 'first' events (deduplicated by a check ID), 'updatable' events (updating specific properties of an existing event), and 'overwritable' events (completely replacing an existing event). These methods help manage event data effectively based on specific use cases. ```java import cn.thinkingdata.analytics.TDFirstEvent; import cn.thinkingdata.analytics.TDUpdatableEvent; import cn.thinkingdata.analytics.TDOverWritableEvent; import cn.thinkingdata.analytics.TDAnalytics; import org.json.JSONObject; // First Event - Only records once per unique firstCheckId JSONObject firstEventProps = new JSONObject(); firstEventProps.put("channel", "google_play"); firstEventProps.put("campaign", "summer_sale"); TDFirstEvent firstEvent = new TDFirstEvent("app_first_launch", firstEventProps); firstEvent.setFirstCheckId("device_unique_id_12345"); // Custom check ID TDAnalytics.track(firstEvent); // Updatable Event - Updates specific properties of existing event JSONObject updateProps = new JSONObject(); updateProps.put("order_status", "shipped"); updateProps.put("shipping_date", "2024-01-15"); TDUpdatableEvent updatableEvent = new TDUpdatableEvent( "order_status_update", updateProps, "order_event_id_67890" // Event ID to update ); TDAnalytics.track(updatableEvent); // Overwritable Event - Completely replaces existing event data JSONObject overwriteProps = new JSONObject(); overwriteProps.put("final_score", 9500); overwriteProps.put("rank", "platinum"); overwriteProps.put("completion_time", 3600); TDOverWritableEvent overwriteEvent = new TDOverWritableEvent( "game_session", overwriteProps, "session_event_id_11111" // Event ID to overwrite ); TDAnalytics.track(overwriteEvent); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.