• 1 CrashSight Integration on Mobile Devices
  • 2 iOS SDK Integration
  • 3 iOS Interfaces
  • 4 Android SDK Integration
  • 5 Android Interfaces

SDK Integration for Mobile Applications


1 CrashSight Integration on Mobile Devices

2 iOS SDK Integration

2.1 CocosPods Integration

  1. Add the pod 'CrashSight' to the Podfile

  2. Run pod install or pod update command

  3. Enter the project from the .xcworkspace file (not the .xcodeproj file)

2.2 Manual Integration

  1. After creating a project on the platform, the SDK that matches the platform and engine of the project can be downloaded from the "Tutorial" in the sidebar, as shown in the figure below:
  1. Add iOS SDK Dependencies
  • Drag the CrashSight.framework file into the Xcode project (Select "Copy items if needed")
  • Add dependency library SystemConfiguration.framework, Security.framework,MetricKit.framework, libz.dylib, or libz.tdb, libc++.dylib or libc++.tdb (You can add none if no error message appears.)

2.3 SDK Initialization

2.3.1 Objective-C Initialization

  • Import header file #import <CrashSight/CrashSight.h> in the project's AppDelegate.m file

  • Initialization: Initialize in the

application:didFinishLaunchingWithOptions:

method of the project's AppDelegate.m file

CrashSightConfig* config = [[CrashSightConfig alloc] init];
//  Customize the domain name for reporting (optional)
config.crashServerUrl = @"http://xxxx";
config.debugMode = true;//open debug mode
NSString* appId = @"appId";
[CrashSight startWithAppId:appId config:config];

2.3.2 Swift Initialization

  • If there is no Objective-C Bridging Header in the project, create one.
    · Create a new .h file
    · Find Build Settings->Swift Compiler-General->Objective-C Bridging Header, fill in the path of the .h file you just created
  • Import header file #import <CrashSight/CrashSight.h> in the project's Objective-C Bridging Header
  • Initialize in XXXApp.swift
@main
struct XXXApp: App {
    init() {
            let config = CrashSightConfig();
            config.crashServerUrl = "http://xxxx";
            config.debugMode = true;
            let appId = "appId";
            CrashSight.start(withAppId:appId,config:config);
    }
...

Domain name for reporting

2.4 Integration Result Testing

After initializing CrashSight, trigger a crash by a button.
Currently there is no crash test interface in CrashSight iOS mobile SDK (to be added later), a simple trigger code, such as illegal memory access, can be written to cause a crash:

int* a = 0;
a[10000] = 5;
  • a. Enable Debug mode. Initialize CrashSight and assign suitable config parameters
  • b. Network and report: Check if “begin to upload <CSAnalyticsLogic” or “cmd: 641” is printed in the test device log
  • c. Crash detection: Check if “Handle the crash scene in callback” is printed in the test device log
  • d. Report exceptions: Check if “begin to upload <CSCrashLogic” or “cmd: 631” is printed in the test device log

3 iOS Interfaces

3.1 Initialize CrashSight with Specified Configurations

Class:CrashSight
Method:+ (void)startWithAppId:(NSString * CS_NULLABLE)appId
     developmentDevice:(BOOL)development
                config:(CrashSightConfig * CS_NULLABLE)config;
ParameterTypeNote
appidNSString *The appid obtained from the CrashSight backend
developmentBOOLWhether it is a development device
configCrashSightConfig *See CrashSightConfig.h header file for details

3.2 Set User ID

Class:CrashSight
Method:+ (void)setUserIdentifier:(NSString *)userId;
ParameterTypeNote
userIdNSString *User ID

3.3 Set App Version Info

Class:CrashSight
Method:+ (void)updateAppVersion:(NSString *)version;
ParameterTypeNote
versionNSString *App Version

3.4 Set Key Data, Reported with Crash Info

Note: Set the Key-Value data customized by the user. It will be reported together with exception info when sending the crash. Each key shouldn't exceed 100 characters, each value shouldn't exceed 1000 characters, and the total length (all keys+all values) shouldn't exceed 128KB.

View page: Crash Details->Download Attachments->valueMapOthers.txt

Class:CrashSight
Method:+ (void)setUserValue:(NSString *)value
              forKey:(NSString *)key;
ParameterTypeNote
keyNSString *Key
valueNSString *Value

3.5 Set Scene Marks

Class:CrashSight
Method:+ (void)setUserSceneTag:(NSString *)userSceneTag;
ParameterTypeNote
userSceneTagNSString *Scene Mark

3.6 Report Custom Errors

Class:CrashSight
Method:+ (void)reportExceptionWithCategory:(NSUInteger)category
                               name:(NSString *)aName
                             reason:(NSString *)aReason
                          callStack:(NSArray *)aStackArray
                          extraInfo:(NSDictionary *)info
                       terminateApp:(BOOL)terminate;
ParameterTypeNote
categoryNSUIntegerError type:ocoa=3,CSharp=4,JS=5,Lua=6
aNameNSString *Name
aReasonNSString *Error cause
aStackArrayNSArray *Stack
infoNSDictionary *Additional data
terminateBOOLWhether to quit application process after reporting

View page:

info: Crash Details->Download Attachments->extraMessage.txt

3.7 Set Reporting Log Level

Class:CrashSightLog
Method:+ (void)initLogger:(CrashSightLogLevel) level consolePrint:(BOOL)printConsole;
ParameterTypeNote
levelCrashSightLogLevelMinimum reporting log level
printConsoleBOOLWhether to print at the console

3.8 Custom Reporting Log

Note: Shouldn't exceed 30KB.

Class:CrashSightLog
Method:+ (void)level:(CrashSightLogLevel) level log:(NSString *)format, ... NS_FORMAT_FUNCTION(2, 3);
ParameterTypeNote
levelCrashSightLogLevelLog level
formatNSString *Log format
...Variadic parameter

3.9 Set Exception Callback

Class:CrashSightDelegate
Proxy property:delegate
Proxy protocol:CrashSightDelegate
Proxy protocol method:- (NSString * CS_NULLABLE)attachmentForException:(NSException * CS_NULLABLE)exception callbackType:(CSCallbackType)callbackType;

Note: The result returned by proxy protocol method will be reported along with the exception View page: Crash Details->Download Attachments->catch_log.txt

4 Android SDK Integration

The CrashSight Android SDK integration process is as follows:

4.1 Maven Integration

a. Add Tencent maven mirror to the project's build.gradle (below Gradle 7.0) :

allprojects {
    repositories {
        maven { 
            url "https://mirrors.tencent.com/nexus/repository/maven-public" 
        }
    }
}

If using Gradle 7.0 or above, add to setting.gradle:

dependencyResolutionManagement {
    repositories {
        maven { 
            url "https://mirrors.tencent.com/nexus/repository/maven-public" 
        }
    }
}

b. Add dependencies to the build.gradle module:

dependencies {
    implementation 'net.crashsight:crashsight-android:4.2.14'
}

4.2 Manual Integration

After creating a project on the platform, the SDK that matches the platform and engine of the project can be downloaded from the "Tutorial" in the sidebar, as shown in the figure below:

  • If your project has Native code (C/C++) or has other third-party shared libraries integrated, it's recommended to download CrashSight's NDK dynamic library. CrashSight NDK contains shared libraries of various architecture:
  • armeabi
  • armeabi-v7a
  • arm64-v8a
  • x86
  • x86_64

When integrating CrashSight shared libraries, please only keep shared libraries with supported architecture.

Eclipse Project

  • Copy the CrashSight library file to the project's libs directory.

  • Refresh the project.

  • Add project dependency: Right-click the JAR file of CrashSight and add it to compilation path.

Android Studio Project

  • Copy the CrashSight library file to the project's libs directory.
  • To integrate CrashSight NDK, add shared library directory configurations to Module's buid.gradle file.
android {
    sourceSets {
        main.jniLibs.srcDirs = ['libs']
    }
}
  • Click Sync to sync configurations.

To improve readability of APP Crash stack, it's recommended to configure symbol table file to better locate issues:

  • Java-only projects: Just configure the Mapping file generated after obfuscation.
  • Projects containing Native code: it's recommended to configure the Symbol symbol table file extracted by symbol table tools from Debug SO. CrashSight supports manual and auto configurations. For detailed configuration process, please see: "CrashSight Symbol Table Configurations for Android"

4.3 Parameter Config

  • Add permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Note: If you are going to release the app on Google Play Store, you need to block or remove the READ_PHONE_STATE permission, or the app may be removed from the store.

  • Please don't obfuscate CrashSight. Add the following configurations to the ProGuard obfuscation file:
-dontwarn com.uqm.crashsight.**
-keep public class com.uqm.crashsight.**{*;}

4.4 Simple Initialization

Obtain APP ID and copy the following code to onCreate() of the project's Application class. CrashSight will automatically detect the environment and finish configurations: (To ensure accuracy of operation data, please don't initialize CrashSight in a asynchronous thread.)

// Set reporting address
CrashReport.setServerUrl(serverUrl);
//Initialization
CrashReport.initCrashReport(getApplicationContext(), "注册时申请的APPID", false);

The third parameter is the switch of SDK debugging mode. Features of the debugging mode's operation include:

  • Outputs detailed CrashSight SDK log.
  • All crashes are reported right away.
  • Custom log will be output in Logcat.
  • Disable error merging, all errors will be reported separately.

You're recommended to set it as true during tests, and as false upon release.

Reporting Address

4.5 Notes on MultiDex

If MultiDex is used, it's recommended to put CrashSight's class into the main Dex through Gradle's "multiDexKeepFile" config or other means. In addition, you're recommended to manually load sub-Dex in the "attachBaseContext" method of Application class.

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(context);
     Multidex.install(this);
  }
}

4.6 Configure Android app bundle software

In the root directory of the project, open the gradle. properties file and add the following line:

APK Configuration required extractNativeLibs = true 
AAB Configuration required enableUncompressedNativeLibs = false

By adding this parameter, the operating system can provide additional information in the event of an application crash to help analyze the cause of the crash.

4.7 Integration Result Testing

Now you can cause a crash (triggering it with "keys" is recommended) to see CrashSight's capabilities. After initializing CrashSight, call CrashSight to test the Java Crash interface.

CrashReport.testJavaCrash();

When executing this code, a crash will happen. The output of Logcat's TAG=CrashSightReport is:

Now you can see the Crash issue just triggered on the "Crash" page (usually delayed by no more than 10s). If the project contains a Native project or uses code obfuscation, you're recommended to configure a symbol table file.

4.8 Enable Javascript's Exception Detection Feature

CrashSight Android SDK 4.2.12 and above versions offer Javascript exception detection and reporting features for developers to detect Javascript exceptions occurring in WebView.

/**
* Set Javascript exception monitoring
* 
* @param webView: specify the webView to monitor
* @param autoInject: whether to inject crashsight.js file automatically
* @return true: successfully set; false: failed to set
*/
CrashReport.setJavascriptMonitor(WebView webView, boolean autoInject)
  • The "crashsight.js" file is in the CrashSight SDK and can be embedded manually via HTML.
  • When auto SDK integration is used, you can choose between auto injection and manual injection. To use auto integration + manual injection, you need to download the "crashsight.js" file.
  • Because versions lower than Android 4.4 have a flawed deflect mechanic, the interface only works in Android 4.4 and higher versions by default.
  • The interface doesn't configure WebViewClient and Listener of webView.
  • The interface enables webView's JS executing capabilities by default.

If non-standard Android WebView is used (such as one with a X5 core), it needs to be used like below:

CrashReport.WebViewInterface webView = new CrashReport.WebViewInterface() {
    /**
     * Obtain WebView URL.
     *
     * @return WebView URL
     */
    @Override
    public String getUrl() {
        // The following is for demonstration only. Please use real logics in real-life scenarios
        return <third-party WebView object>.getUrl();
    }

    /**
     * Activate JavaScript.
     *
     * @param flag true means activated; false means deactivated
     */
    @Override
    public void setJavaScriptEnabled(boolean flag) {
        // The following is for demonstration only. Please use real logics in real-life scenarios
        WebSettings webSettings = <third-party WebView object>.getSettings();
        webSettings.setJavaScriptEnabled(flag);
    }

    /**
     * Load URL.
     *
     * @param url URL to be loaded
     */
    @Override
    public void loadUrl(String url) {
        // The following is for demonstration only. Please use real logics in real-life scenarios
        <third-party WebView object>.loadUrl();
    }

    /**
     * Add JavaScript interface object.
     *
     * @param jsInterface JavaScript interface object
     * @param name JavaScript interface object name
     */
    @Override
    public void addJavascriptInterface(H5JavaScriptInterface jsInterface, String name) {
        // The following is for demonstration only. Please use real logics in real-life scenarios
        <third-party WebView object>.addJavascriptInterface(jsInterface, name);
    }

    /**
     * Obtain content description of WebView.
     *
     * @return Content description of WebView.
     */
    @Override
    public CharSequence getContentDescription() {
        // The following is for demonstration only. Please use real logics in real-life scenarios
        return <third-party WebView object>.getContentDescription();
    }
};
// Just import the WebView interface object created when calling CrashSight to set the JS exception detection interface

4.8.1 Auto Injection

It's recommended to call the interface with the onProgressChanged function of WebChromeClient.

CrashReport.setJavascriptMonitor(webView, true);

Example:

WebView webView = new WebView(this);
// Set WebChromeClient
webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView webView, int progress) {
        // Add Javascript exception monitoring
        CrashReport.setJavascriptMonitor(webView, true);
        super.onProgressChanged(webView, progress);
    }
});
// Load HTML
webView.loadUrl(url);

4.8.2 Manual Injection

Download crashsight.js file and add it to the HTML where Javascript exception monitoring is needed:

<html>
  <script src="crashsight.js" ></script>
<body>
    ...
</body>
</html>

After WebView has loaded the HTML, configure Javascript's exception detection feature:

WebView webView = new WebView(this);
// Load HTML
webView.loadUrl(url);
// Add Javascript exception monitoring
CrashReport.setJavascriptMonitor(webView, false);

After CrashSight Android SDK has detected a Javascript exception, the following info will be reported by default:

  • Android device info;
  • Javascript exception stack and other info;
  • Java stack;
  • WebView info, which only includes ContentDescription at present.

5 Android Interfaces

5.1 Error Reporting

public static void postException(int category, String errorType, String errorMsg, String stack, Map<String, String> extraInfo)

Note: Active reporting of error info

ParameterTypeNote
categoryintException type, C#: 4, js: 5, lua: 6 (For Java error reporting, you can use 4)
errorTypeStringException Name
errorMsgStringException Info
stackStringStack
extraInfoMap<String, String>Other Info

View page:

extraInfo: Crash Details->Download Attachments->extraMessage.txt

5.2 Set User ID

public static void setUserId(String userId)

Note: Set User ID. Please call it after initialization.

ParameterTypeNote
userIdStringUserID

5.3 Mark a Scene

public static void setUserSceneTag(int tagId)

Note: Mark a Scene

ParameterTypeNote
tagIdintScene ID

5.4 Add Custom Data

public static void putUserData(Context context, String key, String value)

Set the Key-Value data customized by the user. It will be reported together with exception info when sending the crash. Each key shouldn't exceed 100 characters, each value shouldn't exceed 1000 characters, and the total length (all keys+all values) shouldn't exceed 64KB. Supports use in callbacks.

View page:

Crash Details->Download Attachments->valueMapOthers.txt

ParameterTypeNote
keyStringKey
valueStringValue

5.5 Custom Log

import com.uqm.crashsight.crashreport.CrashSightLog;

Verbose level log:

public static void v(String tag, String content)

Debug level log

public static void d(String tag, String content)

info level log

public static void i(String tag, String content)

warn level log

public static void w(String tag, String content)

error level log

public static void e(String tag, String content)

Note: The custom log shouldn't exceed 30KB. Android does not support writing custom logs in crash callbacks.

ParameterTypeNote
tagStringTag
contentStringContent

5.6 Set Callback

Note: Set the callback function for crash and error reporting.

View page:

onCrashHandleStart: Crash Details->Download Attachments->extraMessage.txt

onCrashHandleStart2GetExtraDatas: Crash Details->Download Attachments->userExtraByteData

CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(MainActivity.this);
// Set CrashSight callback
strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
    /**
      * Customize the crash callback for info reporting
      *
      * @param crashType     Error type: CRASHTYPE_JAVA, CRASHTYPE_NATIVE, CRASHTYPE_U3D, CRASHTYPE_ANR
      * @param errorType     Error type name
      * @param errorMessage  Error message
      * @param errorStack    Error stack
      * @return Return extra custom info reporting
      */
    @Override
    public synchronized Map<String, String> onCrashHandleStart(int crashType, String errorType, String errorMessage, String errorStack) {
        // Obtain custom info Map of parent class
        Map<String, String> userDatas = super.onCrashHandleStart(crashType, errorType, errorMessage, errorStack);
        if (userDatas == null) {
            userDatas = new HashMap<>();
        }
        for (String k : extraMap.keySet()) {
            userDatas.put(k, extraMap.get(k));
        }
        return userDatas;
    }

    /**
      * Crash callback of binary info reporting
      *
      * @param crashType     Error type: CRASHTYPE_JAVA, CRASHTYPE_NATIVE, CRASHTYPE_U3D, CRASHTYPE_ANR
      * @param errorType Error type name
      * @param errorMessage Error message
      * @param errorStack Error stack
      * @return byte[] Report extra binary content
      */
    @Override
    public byte[] onCrashHandleStart2GetExtraDatas(int crashType, String errorType, String errorMessage, String errorStack) {
        return "test onCrashHandleStart2GetExtraDatas".getBytes();
    }
});
CrashReport.initCrashReport(MainActivity.this, appId, true, strategy);
Last Updated: