### Android Backtrace SDK Full Integration Example (Java) Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Demonstrates a comprehensive integration of the Backtrace Android SDK. It covers initialization with credentials, database configuration for offline storage, setting global attributes, enabling native crash reporting, ANR detection, breadcrumb tracking, crash-free metrics, and a before-send event listener for adding runtime information. This example is intended for production environments. ```java import android.app.Application; import backtraceio.library.*; import backtraceio.library.enums.*; import backtraceio.library.models.*; import backtraceio.library.models.database.BacktraceDatabaseSettings; import java.util.*; public class MyApplication extends Application { private BacktraceClient backtraceClient; @Override public void onCreate() { super.onCreate(); // Initialize Backtrace with comprehensive configuration backtraceClient = initializeBacktrace(); // Enable global exception handling BacktraceExceptionHandler.enable(backtraceClient); // Add example breadcrumb for app startup backtraceClient.addBreadcrumb("Application started", BacktraceBreadcrumbLevel.INFO); } private BacktraceClient initializeBacktrace() { // Configure credentials BacktraceCredentials credentials = new BacktraceCredentials( "https://submit.backtrace.io/my-universe/my-token" ); // Configure database for offline storage String dbPath = getFilesDir().getAbsolutePath() + "/backtrace_db"; BacktraceDatabaseSettings dbSettings = new BacktraceDatabaseSettings(dbPath); dbSettings.setMaxRecordCount(100); dbSettings.setMaxDatabaseSize(50); dbSettings.setRetryBehavior(RetryBehavior.ByInterval); dbSettings.setRetryInterval(30000); dbSettings.setAutoSendMode(true); dbSettings.setRetryOrder(RetryOrder.Queue); BacktraceDatabase database = new BacktraceDatabase(this, dbSettings); // Set global attributes Map attributes = new HashMap<>(); attributes.put("app.version", BuildConfig.VERSION_NAME); attributes.put("app.build", BuildConfig.VERSION_CODE); attributes.put("environment", BuildConfig.BUILD_TYPE); // Configure attachments for native crashes List attachments = new ArrayList<>(); attachments.add(getFilesDir() + "/app.log"); // Create client BacktraceClient client = new BacktraceClient( this, credentials, database, attributes, attachments ); // Enable native crash reporting database.setupNativeIntegration(client, credentials, true); // Enable ANR detection (5 second threshold) client.enableAnr(5000); // Enable breadcrumbs tracking EnumSet breadcrumbTypes = EnumSet.of( BacktraceBreadcrumbType.USER, BacktraceBreadcrumbType.LOG, BacktraceBreadcrumbType.NAVIGATION, BacktraceBreadcrumbType.SYSTEM ); client.enableBreadcrumbs(this, breadcrumbTypes); // Enable crash-free metrics BacktraceMetricsSettings metricsSettings = new BacktraceMetricsSettings( credentials, BacktraceMetrics.defaultBaseUrl, BacktraceMetrics.defaultTimeIntervalMs ); client.metrics.enable(metricsSettings); // Configure before-send callback client.setOnBeforeSendEventListener(data -> { // Add runtime information data.attributes.attributes.put("memory.free", Runtime.getRuntime().freeMemory()); data.attributes.attributes.put("memory.max", Runtime.getRuntime().maxMemory()); return data; }); return client; } public BacktraceClient getBacktraceClient() { return backtraceClient; } } // Usage in Activity public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); BacktraceClient client = ((MyApplication) getApplication()).getBacktraceClient(); // Add breadcrumb for screen navigation client.addBreadcrumb("MainActivity created"); // Example error handling findViewById(R.id.button).setOnClickListener(v -> { try { performRiskyOperation(); } catch (Exception e) { Map errorAttrs = new HashMap<>(); errorAttrs.put("action", "button_click"); errorAttrs.put("screen", "MainActivity"); client.send(e, errorAttrs, result -> { if (result.status == BacktraceResultStatus.Ok) { Toast.makeText(this, "Error reported", Toast.LENGTH_SHORT).show(); } }); } }); } } ``` -------------------------------- ### Include Directories and Client-Side Unwinding Setup Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Adds include directories for Backtrace headers and, if client-side unwinding is enabled, sets a compile definition and adds the 'libbun' subdirectory. ```cmake # Includes include_directories(${PROJECT_SOURCE_DIR}/include) if (CLIENT_SIDE_UNWINDING) target_compile_definitions(backtrace-native PRIVATE -DCLIENT_SIDE_UNWINDING) # Bun Libraries set(LIBUNWINDSTACK_ENABLED TRUE) add_subdirectory(libbun) endif () ``` -------------------------------- ### CMake Project and Library Setup Source: https://github.com/backtrace-labs/backtrace-android/blob/master/example-app/src/main/cpp/CMakeLists.txt This snippet demonstrates how to initialize a CMake project and define a shared native library. It specifies the minimum CMake version, names the project, and creates a shared library named 'native-lib' from 'native-lib.cpp'. ```cmake cmake_minimum_required(VERSION 3.10.2) project("myapplication") add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). native-lib.cpp ) ``` -------------------------------- ### Enable ANR Detection with Backtrace Android Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Demonstrates how to enable ANR (Application Not Responding) detection using the Backtrace Android SDK. It shows default settings, custom timeouts, specific detection types (Threshold and ApplicationExit), and custom event handlers for pre-report modifications. Also includes an example of code that would trigger ANR. ```java import backtraceio.library.anr.AnrType; import backtraceio.library.watchdog.OnApplicationNotRespondingEvent; import backtraceio.library.models.json.BacktraceReport; // Enable ANR detection with default settings (5 seconds) client.enableAnr(); // Enable ANR detection with custom timeout (3 seconds) client.enableAnr(3000); // Enable ANR detection with specific detection type // AnrType.Threshold: Watchdog-based detection monitoring main thread // AnrType.ApplicationExit: Uses Android's ApplicationExitInfo API (Android 11+) client.enableAnr(AnrType.Threshold); // Enable ANR detection with custom event handler client.enableAnr(5000, new OnApplicationNotRespondingEvent() { @Override public BacktraceReport onEvent(BacktraceReport report) { // Add custom logic before sending ANR report report.attributes.put("anr.custom_action", "logged"); report.attributes.put("anr.thread_state", "blocked"); return report; } }, false); // false = send reports even when debugger is attached // Example code that would trigger ANR detection public void simulateAnr() throws InterruptedException { // This will block the main thread and trigger ANR Thread.sleep(6000); } ``` -------------------------------- ### Log Breadcrumbs with Backtrace Android SDK Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Illustrates how to enable and use breadcrumbs logging in the Backtrace Android SDK. It covers enabling with all automatic tracking, selecting specific types (USER, LOG, NAVIGATION), adding manual breadcrumbs with default or specific levels, and including custom attributes. An example demonstrates logging breadcrumbs within an application flow. ```java import backtraceio.library.enums.BacktraceBreadcrumbType; import backtraceio.library.enums.BacktraceBreadcrumbLevel; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; // Enable breadcrumbs with all automatic tracking boolean enabled = client.enableBreadcrumbs(context); // Enable only specific breadcrumb types EnumSet breadcrumbTypes = EnumSet.of( BacktraceBreadcrumbType.USER, // Manual breadcrumbs BacktraceBreadcrumbType.LOG, // Log events BacktraceBreadcrumbType.NAVIGATION // Navigation events ); client.enableBreadcrumbs(context, breadcrumbTypes); // Add manual breadcrumb with default level (INFO) client.addBreadcrumb("User clicked checkout button"); // Add breadcrumb with specific level client.addBreadcrumb("Payment validation failed", BacktraceBreadcrumbLevel.WARNING); // Add breadcrumb with custom attributes and type Map breadcrumbAttrs = new HashMap<>(); breadcrumbAttrs.put("screen", "checkout"); breadcrumbAttrs.put("item_count", 3); breadcrumbAttrs.put("total_price", 149.99); client.addBreadcrumb( "Checkout process started", breadcrumbAttrs, BacktraceBreadcrumbType.USER, BacktraceBreadcrumbLevel.INFO ); // Example usage in application flow public void processOrder() { client.addBreadcrumb("Starting order processing"); try { validateCart(); client.addBreadcrumb("Cart validated successfully"); processPayment(); client.addBreadcrumb("Payment processed"); } catch (Exception e) { client.addBreadcrumb("Order processing failed", BacktraceBreadcrumbLevel.ERROR); client.send(e); // Report will include all breadcrumbs } } ``` -------------------------------- ### Initialize BacktraceClient with Credentials and Database (Java) Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Demonstrates the basic initialization of the Backtrace client using submission URL and credentials. It also shows how to configure the SDK for offline crash storage using BacktraceDatabase with custom settings for record count and database size, along with auto-send mode. ```java import backtraceio.library.BacktraceClient; import backtraceio.library.BacktraceCredentials; import backtraceio.library.BacktraceDatabase; import backtraceio.library.models.database.BacktraceDatabaseSettings; import android.content.Context; import java.util.HashMap; import java.util.Map; // Basic initialization with submission URL Context context = getApplicationContext(); BacktraceCredentials credentials = new BacktraceCredentials("https://submit.backtrace.io/universe-name/token"); BacktraceClient client = new BacktraceClient(context, credentials); // Initialization with database for offline storage String dbPath = context.getFilesDir().getAbsolutePath(); BacktraceDatabaseSettings dbSettings = new BacktraceDatabaseSettings(dbPath); dbSettings.setMaxRecordCount(100); dbSettings.setMaxDatabaseSize(1000); // Size in MB dbSettings.setAutoSendMode(true); BacktraceDatabase database = new BacktraceDatabase(context, dbSettings); // Initialization with custom attributes Map attributes = new HashMap() { put("environment", "production"); put("version", "1.2.3"); put("user.id", "12345"); }; BacktraceClient clientWithDb = new BacktraceClient(context, credentials, database, attributes); ``` -------------------------------- ### Enable Crash-Free Metrics with Backtrace Android SDK Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Shows how to enable application stability metrics tracking using the Backtrace Android SDK. Includes enabling with default settings and with custom configurations like endpoint and interval. Also demonstrates sending custom summed and unique events for more granular metric tracking. ```java import backtraceio.library.models.BacktraceMetricsSettings; import backtraceio.library.BacktraceCredentials; // Enable metrics with default settings client.metrics.enable(); // Enable metrics with custom settings BacktraceMetricsSettings metricsSettings = new BacktraceMetricsSettings( credentials, "https://events.backtrace.io/api", // Metrics endpoint 1800000 // 30 minutes interval in milliseconds ); client.metrics.enable(metricsSettings); // Metrics are automatically tracked and include: // - Application launches // - Crash-free sessions // - Crash-free users // - Session duration // Send custom summed event client.metrics.addSummedEvent("api.requests", new HashMap() {{ put("endpoint", "/api/users"); put("method", "GET"); }}); // Send custom unique event client.metrics.addUniqueEvent("feature.used", new HashMap() {{ put("feature_name", "dark_mode"); put("user_segment", "premium"); }}); ``` -------------------------------- ### Clone Backtrace Android Repository Source: https://github.com/backtrace-labs/backtrace-android/blob/master/CONTRIBUTING.md Clones the Backtrace Android SDK repository from GitHub to your local machine. This is the first step in setting up your development environment. ```bash git clone https://github.com/backtrace-labs/backtrace-android.git ``` -------------------------------- ### Event Callbacks and Response Handling in Java Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt This snippet illustrates how to implement event listeners for handling server responses and modifying reports before they are sent using the Backtrace Android SDK. It covers setting up 'before-send' events to add global attributes, filter sensitive data, or skip reports, and 'server error' events for custom error handling. It also shows how to process different server response statuses via `OnServerResponseEventListener`. Dependencies include backtraceio.library event and model classes. ```java import backtraceio.library.events.OnServerResponseEventListener; import backtraceio.library.events.OnBeforeSendEventListener; import backtraceio.library.models.BacktraceResult; import backtraceio.library.models.types.BacktraceResultStatus; // Set global before-send event to filter or modify reports client.setOnBeforeSendEventListener(new OnBeforeSendEventListener() { @Override public BacktraceData onEvent(BacktraceData data) { // Add global attributes to all reports data.attributes.attributes.put("app.environment", "production"); data.attributes.attributes.put("app.commit_hash", BuildConfig.GIT_HASH); // Filter out sensitive information if (data.attributes.attributes.containsKey("user.password")) { data.attributes.attributes.remove("user.password"); } // Skip sending reports for certain conditions if (data.classifier.contains("OutOfMemoryError")) { return null; // Returning null prevents sending } return data; } }); // Set server error event listener for handling API failures client.setOnServerErrorEventListener(new OnServerErrorEventListener() { @Override public void onEvent(Exception e) { System.err.println("Failed to send report to Backtrace: " + e.getMessage()); // Implement custom error handling, logging, or fallback } }); // Send report with response callback client.send(new BacktraceReport("Error occurred"), new OnServerResponseEventListener() { @Override public void onEvent(BacktraceResult result) { switch (result.status) { case Ok: System.out.println("Report submitted successfully"); System.out.println("Report ID: " + result.message); break; case ServerError: System.err.println("Server error: " + result.message); break; case NetworkError: System.err.println("Network error, will retry"); break; case LimitReached: System.err.println("Rate limit reached"); break; } } }); ``` -------------------------------- ### Link Backend-Specific Libraries and Crashpad Handler Options Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Links necessary libraries based on the selected backend. For CRASHPAD_BACKEND, it configures Crashpad handler options and links 'client' and 'handlerlib'. For BREAKPAD_BACKEND, it appends Breakpad and Curl libraries. If client-side unwinding is enabled, it appends the 'bun' library. ```cmake if (BACKEND STREQUAL "CRASHPAD_BACKEND") # Pass 16 KB linker flags to Crashpad’s handler so libcrashpad_handler.so loads on 16 KB kernels. set(CRASHPAD_GN_ARGS_FILE "${CMAKE_CURRENT_SOURCE_DIR}/build_args/args_android.gn") set(CRASHPAD_HANDLER_GENERATE_STATIC_LIB true) add_subdirectory(crashpad) target_link_libraries(backtrace-native client) target_link_libraries(backtrace-native handlerlib) elseif (BACKEND STREQUAL "BREAKPAD_BACKEND") list(APPEND LIBS breakpad_client) list(APPEND LIBS curl else () message("No native debugging backend selected") endif () if (CLIENT_SIDE_UNWINDING) list(APPEND LIBS bun) endif () target_link_libraries(${LIBS}) ``` -------------------------------- ### Configure Linker Options for ARM64 and x86_64 Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Applies specific linker options for ARM64 and x86_64 ABIs to ensure 16 KB page alignment for load segments, which is beneficial for newer kernels. ```cmake # Android 15 & later: make every LOAD segment 16 KB-aligned so the .so files # can work on kernels that use 16 KB pages. Has zero impact on 4 KB devices. if (ANDROID_ABI STREQUAL "arm64-v8a" OR ANDROID_ABI STREQUAL "x86_64") target_link_options(backtrace-native PRIVATE -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384) endif() ``` -------------------------------- ### Configure Backtrace Android Database for Offline Storage Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt This section explains how to configure the offline error storage database. It covers setting maximum reports, database size, retry behaviors (interval, no retry), retry order (FIFO, LIFO), automatic sending, initializing the client with the database, manually sending reports, checking pending counts, and clearing the database. ```java import backtraceio.library.enums.database.RetryBehavior; import backtraceio.library.enums.database.RetryOrder; // Create database with comprehensive settings String databasePath = context.getFilesDir().getAbsolutePath() + "/backtrace"; BacktraceDatabaseSettings settings = new BacktraceDatabaseSettings(databasePath); // Set maximum number of stored reports settings.setMaxRecordCount(250); // Set maximum database size in megabytes settings.setMaxDatabaseSize(50); // Configure retry behavior // RetryBehavior.ByInterval: Retry at fixed intervals // RetryBehavior.NoRetry: Don't retry failed reports settings.setRetryBehavior(RetryBehavior.ByInterval); settings.setRetryInterval(60000); // Retry every 60 seconds settings.setMaximumRetries(5); // Configure retry order // RetryOrder.Queue: FIFO order // RetryOrder.Stack: LIFO order settings.setRetryOrder(RetryOrder.Queue); // Enable automatic sending when network becomes available settings.setAutoSendMode(true); // Create database with settings BacktraceDatabase database = new BacktraceDatabase(context, settings); // Initialize client with database BacktraceClient client = new BacktraceClient(context, credentials, database); // Manually trigger sending of queued reports database.send(); // Get count of pending reports int pendingCount = database.count(); System.out.println("Pending reports: " + pendingCount); // Clear all stored reports database.clear(); ``` -------------------------------- ### Configure Backend-Specific Compile Definitions and Libraries Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Sets compile definitions for the selected backend (CRASHPAD_BACKEND or BREAKPAD_BACKEND). For BREAKPAD_BACKEND, it also imports static and shared libraries for Breakpad and Curl, and includes necessary header directories. ```cmake if (BACKEND STREQUAL "CRASHPAD_BACKEND") target_compile_definitions(backtrace-native PRIVATE -DCRASHPAD_BACKEND) elseif (BACKEND STREQUAL "BREAKPAD_BACKEND") target_compile_definitions(backtrace-native PRIVATE -DBREAKPAD_BACKEND) # Breakpad Libraries add_library(breakpad_client STATIC IMPORTED) set_property(TARGET breakpad_client PROPERTY IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/breakpad-builds/${ANDROID_ABI}/libbreakpad_client.a) # Curl Libraries add_library(curl SHARED IMPORTED) set_property(TARGET curl PROPERTY IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/curl-builds/${ANDROID_ABI}/libcurl.so) # Breakpad Headers include_directories(${PROJECT_SOURCE_DIR}/breakpad-builds/${ANDROID_ABI} ${PROJECT_SOURCE_DIR}/breakpad-builds/${ANDROID_ABI}/src ${PROJECT_SOURCE_DIR}/breakpad-builds/${ANDROID_ABI}/src/common/android/include) else () message("No native debugging backend selected") endif () ``` -------------------------------- ### Configure Native Crash Handling with Backtrace Android Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt This snippet demonstrates how to set up native crash reporting for JNI/NDK crashes. It covers basic integration, enabling client-side unwinding for better stack traces, advanced unwinding modes, adding file attachments, custom attributes, generating reports without crashing, and dynamically enabling/disabling the integration. ```java import backtraceio.library.enums.UnwindingMode; import java.util.ArrayList; import java.util.List; // Basic native crash handler setup BacktraceDatabase database = new BacktraceDatabase(context, dbSettings); database.setupNativeIntegration(client, credentials); // Enable native crash handling with client-side unwinding for better stack traces database.setupNativeIntegration(client, credentials, true); // Advanced configuration with custom unwinding mode database.setupNativeIntegration( client, credentials, true, // Enable client-side unwinding UnwindingMode.REMOTE_DUMPWITHOUTCRASH ); // Specify file attachments for native crashes (must be set at initialization) List nativeAttachments = new ArrayList<>(); nativeAttachments.add(context.getFilesDir() + "/config.json"); nativeAttachments.add(context.getFilesDir() + "/session.log"); BacktraceClient clientWithAttachments = new BacktraceClient( context, credentials, database, attributes, nativeAttachments ); // Add custom attributes to native crash reports database.addAttribute("native.version", "1.0.5"); database.addAttribute("native.build", "release"); // Generate a native crash report without crashing (for testing) client.dumpWithoutCrash("Manual native crash report for diagnostics"); // Disable and re-enable native integration at runtime client.disableNativeIntegration(); // ... perform operations without native monitoring client.enableNativeIntegration(); ``` -------------------------------- ### Report Customization with Attachments in Java Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt This snippet demonstrates how to attach custom files and additional context to error reports using the Backtrace Android SDK. It includes creating a log file, specifying attachment paths, and adding detailed attributes to a BacktraceReport object. Dependencies include the backtraceio.library and standard Java IO classes. The output is a configured BacktraceReport ready for sending. ```java import backtraceio.library.models.json.BacktraceReport; import java.util.ArrayList; import java.util.List; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; // Create a custom log file File logFile = new File(context.getFilesDir(), "app_log.txt"); try (FileOutputStream fos = new FileOutputStream(logFile)) { String logContent = "Application Log:\n" + "2023-11-15 10:30:45 - User logged in\n" + "2023-11-15 10:31:12 - Started checkout process\n" + "2023-11-15 10:31:45 - Payment failed\n"; fos.write(logContent.getBytes()); } // Create report with attachments BacktraceReport report = new BacktraceReport("Payment processing error"); // Add file attachments List attachments = new ArrayList<>(); attachments.add(logFile.getAbsolutePath()); attachments.add(context.getFilesDir() + "/user_session.json"); attachments.add(context.getFilesDir() + "/error_screenshot.png"); report.attachmentPaths = attachments; // Add detailed attributes report.attributes.put("payment.processor", "stripe"); report.attributes.put("payment.error_code", "card_declined"); report.attributes.put("payment.attempt", 2); report.attributes.put("user.subscription_tier", "premium"); report.attributes.put("device.memory_available", Runtime.getRuntime().freeMemory()); // Send report with attachments client.send(report, new OnServerResponseEventListener() { @Override public void onEvent(BacktraceResult result) { if (result.status == BacktraceResultStatus.Ok) { logFile.delete(); // Clean up after successful upload } } }); ``` -------------------------------- ### Configure CMake Minimum Version and Backend Selection Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Sets the minimum required CMake version and determines the native crash reporting backend based on Android NDK version and ABI. Supports BREAKPAD_BACKEND and CRASHPAD_BACKEND. ```cmake cmake_minimum_required(VERSION 3.13) # Determine native crash backend # ANDROID_NDK_MAJOR not defined until ndk 17+ # https://github.com/android/ndk/issues/596 if (ANDROID_ABI STREQUAL "x86") message("Native crash reporting not supported for x86 emulator") elseif (ANDROID_ABI STREQUAL "x86_64" AND (NOT ANDROID_NDK_MAJOR OR ANDROID_NDK_MAJOR LESS 17)) message("Breakpad not supported for x86_64 emulator") elseif (NOT ANDROID_NDK_MAJOR) set(BACKEND "BREAKPAD_BACKEND") elseif (ANDROID_NDK_MAJOR LESS 17) set(BACKEND "BREAKPAD_BACKEND") elseif (ANDROID_NATIVE_API_LEVEL LESS 21) set(BACKEND "CRASHPAD_BACKEND") # 64 bit architectures will always have min API level 21 # https://stackoverflow.com/a/56467008 if (NOT ANDROID_ABI STREQUAL "armeabi-v7a") set(CLIENT_SIDE_UNWINDING TRUE) endif () else () set(BACKEND "CRASHPAD_BACKEND") set(CLIENT_SIDE_UNWINDING TRUE) endif () ``` -------------------------------- ### Initialize and Use Backtrace Client Source: https://github.com/backtrace-labs/backtrace-android/blob/master/README.md Initialize the Backtrace client with your submission URL and configure it to capture uncaught exceptions, enable ANR detection, and enable Crash Free metrics. Replace '' with your actual Backtrace submission URL. ```java // replace with your submission url BacktraceCredentials credentials = new BacktraceCredentials(""); BacktraceClient backtraceClient = new BacktraceClient(getApplicationContext(), credentials); // send test report backtraceClient.send("test"); // Capture uncaught exceptions BacktraceExceptionHandler.enable(backtraceClient); // Enable ANR detection backtraceClient.enableAnr(); // Enable Crash Free metrics backtraceClient.metrics.enable(); ``` ```kotlin // replace with your submission url val credentials = BacktraceCredentials("") val backtraceClient = BacktraceClient(applicationContext, credentials) // send test report backtraceClient.send("test") // Capture uncaught exceptions BacktraceExceptionHandler.enable(backtraceClient) // Enable ANR detection backtraceClient.enableAnr() // Enable Crash Free metrics backtraceClient.metrics.enable() ``` -------------------------------- ### Enable Automatic Unhandled Exception Handling (Java) Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Shows how to enable the Backtrace SDK to automatically capture and report unhandled exceptions. It includes setting up a global exception handler and optionally adding custom attributes to these automatically reported exceptions. ```java import backtraceio.library.models.BacktraceExceptionHandler; // Enable automatic capture of unhandled exceptions BacktraceClient client = new BacktraceClient(context, credentials); BacktraceExceptionHandler.enable(client); // Optional: Add custom attributes to unhandled exception reports Map customAttributes = new HashMap<>(); customAttributes.put("crash.handler", "backtrace"); customAttributes.put("severity", "critical"); BacktraceExceptionHandler.setCustomAttributes(customAttributes); // Now any unhandled exception will be automatically reported // Example: This will be caught and sent to Backtrace throw new RuntimeException("Unexpected error occurred"); ``` -------------------------------- ### Find NDK Log Library and Link Libraries Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Locates the NDK's 'log' library using find_library and appends it to the LIBS list. It then defines the final list of libraries to link against the 'backtrace-native' target. ```cmake # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. list(APPEND LIBS backtrace-native) list(APPEND LIBS ${log-lib}) ``` -------------------------------- ### Update Git Submodules Source: https://github.com/backtrace-labs/backtrace-android/blob/master/CONTRIBUTING.md Updates Git submodules recursively, ensuring all dependencies are up-to-date. This command should be run to fetch the latest submodule content. ```bash git submodule update --recursive --remote git submodule update --init --recursive ``` -------------------------------- ### Push Changes to Remote Repository Source: https://github.com/backtrace-labs/backtrace-android/blob/master/CONTRIBUTING.md Pushes the local branch containing your changes to the remote repository. This makes your contributions available for review. ```bash git push origin jira-ticket/your-feature-name ``` -------------------------------- ### Send Error Reports with Different Inputs (Java) Source: https://context7.com/backtrace-labs/backtrace-android/llms.txt Illustrates how to send various types of error reports to Backtrace. This includes sending simple text messages, caught exceptions, exceptions with custom attributes, and structured BacktraceReports with a server response callback. ```java import backtraceio.library.models.json.BacktraceReport; import backtraceio.library.events.OnServerResponseEventListener; import java.util.HashMap; import java.util.Map; // Send a simple message client.send("Application encountered an error"); // Send an exception try { int result = 10 / 0; } catch (ArithmeticException e) { client.send(e); } // Send exception with custom attributes try { processUserData(); } catch (Exception e) { Map errorAttributes = new HashMap<>(); errorAttributes.put("operation", "data_processing"); errorAttributes.put("user_action", "submit_form"); client.send(e, errorAttributes, null); } // Send report with callback for server response BacktraceReport report = new BacktraceReport("Critical error in payment flow"); report.attributes.put("payment.amount", 99.99); report.attributes.put("payment.currency", "USD"); client.send(report, new OnServerResponseEventListener() { @Override public void onEvent(BacktraceResult result) { if (result.status == BacktraceResultStatus.Ok) { System.out.println("Report sent successfully: " + result.message); } else { System.out.println("Failed to send report: " + result.message); } } }); ``` -------------------------------- ### Add Backtrace Android SDK Dependency Source: https://github.com/backtrace-labs/backtrace-android/blob/master/README.md Add the Backtrace reporting library to your Android project using Gradle or Maven. Ensure you replace '' with the actual latest version of the library. ```groovy // provide the latest version of the Backtrace reporting library. dependencies { implementation 'com.github.backtrace-labs.backtrace-android:backtrace-library:' } ``` ```xml com.github.backtrace-labs.backtrace-android backtrace-library aar ``` -------------------------------- ### Create Feature Branch with Jira Ticket Source: https://github.com/backtrace-labs/backtrace-android/blob/master/CONTRIBUTING.md Creates a new Git branch for a feature or bugfix, optionally prefixed with a Jira ticket number. This helps organize contributions. ```bash git checkout -b jira-ticket/your-feature-name ``` -------------------------------- ### Define Shared Library Sources and Features Source: https://github.com/backtrace-labs/backtrace-android/blob/master/backtrace-library/src/main/cpp/CMakeLists.txt Appends source files to the SOURCES list and defines the target shared library 'backtrace-native'. It also sets the C++ standard to C++17. ```cmake # Sources list(APPEND SOURCES backtrace-native.cpp) list(APPEND SOURCES backends/backend.cpp) list(APPEND SOURCES client-side-unwinding.cpp) if (BACKEND STREQUAL "CRASHPAD_BACKEND") list(APPEND SOURCES backends/crashpad-backend.cpp) elseif (BACKEND STREQUAL "BREAKPAD_BACKEND") list(APPEND SOURCES backends/breakpad-backend.cpp) else () message("No native debugging backend selected") endif () add_library(# Sets the name of the library. backtrace-native # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${SOURCES}) target_compile_features(backtrace-native PRIVATE cxx_std_17) ``` -------------------------------- ### CMake Find and Link NDK Log Library Source: https://github.com/backtrace-labs/backtrace-android/blob/master/example-app/src/main/cpp/CMakeLists.txt This code demonstrates how to find and link the NDK's 'log' library. It uses `find_library` to locate the 'log' system library and then `target_link_libraries` to make it available to the 'native-lib'. ```cmake find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) target_link_libraries( # Specifies the target library. native-lib # Links the target library to the log library # included in the NDK. ${log-lib} ) ``` -------------------------------- ### CMake Android ABI Specific Link Options Source: https://github.com/backtrace-labs/backtrace-android/blob/master/example-app/src/main/cpp/CMakeLists.txt This snippet configures linker options specifically for ARM64-v8a and x86_64 ABIs on Android. It sets the maximum and common page sizes to 16384 bytes for Android 15 and later, optimizing memory usage. ```cmake if (ANDROID_ABI STREQUAL "arm64-v8a" OR ANDROID_ABI STREQUAL "x86_64") target_link_options(native-lib PRIVATE -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384) endif() ``` -------------------------------- ### Commit Changes with Imperative Message Source: https://github.com/backtrace-labs/backtrace-android/blob/master/CONTRIBUTING.md Commits staged changes to the local repository using a clear and concise message in the imperative mood. This is a standard practice for Git commit messages. ```bash git commit -m "Add feature X to improve functionality" ``` -------------------------------- ### CMake Compile Features and Options Source: https://github.com/backtrace-labs/backtrace-android/blob/master/example-app/src/main/cpp/CMakeLists.txt This section shows how to specify C++ standard features and compiler options for a target library. It ensures C++11 compatibility and disables frame pointer omission for debugging purposes. ```cmake target_compile_features(native-lib PRIVATE cxx_std_11) target_compile_options(native-lib PRIVATE -fno-omit-frame-pointer) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.