Skip to main content
Version: 3.7.0

SDK API

1. Startup Configuration Interfaces

<#Config Address#> and <#AppID#> can be obtained from the platform. For the method to obtain them, please refer to How to Query AppID and Config Address?. If you have any questions, please contact technical support.

Startup configuration interfaces are configured using chain calls along with Bonree.withAppID("<#AppID#>").start(getApplicationContext());. These configurations must be done after calling withAppID but before calling the start function. Multiple configurations can be set simultaneously. Configurations after the start function are invalid.

Set Config Address

One platform or private deployment users need to set the private deployment config address during startup.

  • Interface Description
Bonree withConfigAddress(java.lang.String configAddress)
ParameterDescriptionParameter RestrictionsFailure Result
configAddressPrivate cloud config addressString length must be greater than 0 and less than or equal to 2083, otherwise interface call failsAgent stops
  • Example
Bonree.withAppID("<#AppID#>")
.withConfigAddress("<#Config Address#>")
.start(getApplicationContext());

Configure Custom Business Headers

Configure key Http Request Header keys in native network requests. When the actual request data collected by the SDK contains these keys in the Request Header, the corresponding keys and values will be displayed separately.

Bonree withCustomBusinessHeaders(java.lang.String[] headers)
ParameterDescriptionParameter RestrictionsFailure Result
headersCustom business Header keys to retrieve from request headers, multiple can be setArray elements must be strings with length >0 and ≤256, without special characters (only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ allowed; empty or null strings are invalid), otherwise filtered out
Array must have >0 elements, otherwise interface call fails
Array elements ≤64, truncated if exceeded
Current setting invalid
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.start(getApplicationContext());

Set Custom Device ID

If a custom device ID is set through this method, the SDK will report this ID instead of using the default obtained ID.

Bonree withDeviceID(java.lang.String deviceID)
ParameterDescriptionParameter RestrictionsFailure Result
deviceIDCustom device IDString length must be >0 and ≤256, and must not contain special characters (only letters, numbers, underscore _, hyphen - allowed), otherwise interface call failsCurrent setting invalid
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.withDeviceID("custom_device_id")
.start(getApplicationContext());

Set Custom App Version

If a custom app version is set through this method, the SDK will report this version instead of using the default obtained version.

Bonree withAppVersion(java.lang.String version)
ParameterDescriptionParameter RestrictionsFailure Result
versionCustom version numberString length must be >0 and ≤64, otherwise interface call failsCurrent setting invalid
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.withDeviceID("custom device id")
.withAppVersion("custom app version")
.start(getApplicationContext());

Set Custom Application Environment

Set application environment field through this method.

Bonree withAppEnvironment(java.lang.String environment)
ParameterDescriptionParameter RestrictionsFailure Result
environmentApplication environment stringString length >0 and ≤256, truncated if exceeded; must not contain special characters (allows spaces (but not pure spaces), letters, Chinese characters, numbers, -, _, ., @, /, :, *, #, !)Current setting invalid
  • Example
Bonree.withAppID("<#AppID#>")
.withAppEnvironment("PROD")
.start(this.context.getApplicationContext());

Set User Channel ID

Distinguish application distribution channels. Channel information will be displayed in the platform's performance data.

Bonree withChannelID(java.lang.String channelID)
ParameterDescriptionParameter RestrictionsFailure Result
channelIdCustom channel numberString length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.withDeviceID("custom device id")
.withAppVersion("custom app version")
.withChannelID("Huawei Store")
.start(getApplicationContext());

Multi-process SDK Initialization

Whether to initialize SDK in all processes. Default is disabled if not set.

Bonree withAllLaunch(boolean enabled)
ParameterDescription
enabledtrue: enable, false: disable
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.withDeviceID("custom device id")
.withAppVersion("custom app version")
.withChannelID("Huawei Store")
.withAllLaunch(true)
.start(getApplicationContext());

Android Box Data Collection Mode

Whether to collect ANR indicator data according to Box mode. Default is disabled if not set.

Bonree withAndroidBoxEnabled(boolean enabled)
ParameterDescription
enabledtrue: enable, false: disable
  • Example
Bonree.withAppID("<#AppID#>")
.withCustomBusinessHeaders("User-Agent", "Content-Type")
.withDeviceID("custom device id")
.withAppVersion("custom app version")
.withChannelID("Huawei Store")
.withAndroidBoxEnabled(true)
.start(getApplicationContext());

Set Synchronous SDK Initialization

Whether to enable synchronous SDK startup.

Bonree withSyncStart(boolean isSync)
ParameterDescription
isSynctrue: synchronous startup, false: asynchronous startup
  • Example
Bonree.withAppID("<#AppID#>")
.withSyncStart(true)
.start(getApplicationContext());

Use Custom Cold Launch End Time

Whether to use custom cold launch end time.

Bonree withUseCustomLaunch(boolean used)
ParameterDescription
usedtrue: use custom end, false: don't use
  • Example
Bonree.withAppID("<#AppID#>")
.withUseCustomLaunch(true)
.start(getApplicationContext());

Set Continuous Frame Drop Time

Continuous frame drop time required to determine stuttering.

Bonree withDropFrameTime(int dropFrameTime)
ParameterDescription
dropFrameTimeContinuous frame drop time (s), 0 < dropFrameTime ≤ 30, default 5s if not set
  • Example
Bonree.withAppID("<#AppID#>")
.withDropFrameTime(5)
.start(getApplicationContext());

Set SDK Request Headers

This interface is used to set custom request headers for network requests initiated by the SDK itself.

Bonree withSDKRequestHeaders(Map<String, String> headers)
ParameterDescription
headersRequest header key-value pairs to set (maximum 64 pairs, key length limited to 256 characters, value length limited to 512 characters)
  • Example
Map<String, String> headers = new HashMap<>();
headers.put("headerKey1", "headerValue1");
headers.put("headerKey2", "headerValue2");
headers.put("headerKey3", "headerValue3");

Bonree.withAppID("<#AppID#>")
.withSDKRequestHeaders(headers)
.start(getApplicationContext());

Enable Encryption and Set Encryption Information

This interface is used to set whether to use national encryption for SDK's own requests.

The encryption function currently only supports the One platform. Before using this function, be sure to communicate with technical support or implementation to obtain the encryption Key to ensure consistency with the platform configuration, otherwise it will cause abnormal SDK data requests.

Bonree withEnableGMSM4Encrypt(byte[] secretKey, java.lang.String identifier)
ParameterDescriptionParameter RestrictionsFailure Result
secretKeyEncryption keyRequired, byte[] type, key length must be exactly 16 bytesEncryption function disabled
identifierKey identifierRequired, string cannot be empty or null
String length ≤256, and must not contain special characters (only letters, numbers, underscore _, hyphen - allowed)
Encryption function disabled
  • Example
byte[] secretKey = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
//assert secretKey.length == 16;
String identifier = "v30";
Bonree.withAppID("<#AppID#>")
.withEnableGMSM4Encrypt(secretKey, identifier)
.start(getApplicationContext());

or

String secretKeyStr = "1234567890123456";
byte[] secretKey = secretKeyStr.getBytes();
//assert secretKey.length == 16; Must ensure the actual character length is 16 bytes, do not use < > & ' " % special characters
String identifier = "v31";
Bonree.withAppID("<#AppID#>")
.withEnableGMSM4Encrypt(secretKey, identifier)
.start(getApplicationContext());

Set View Data Desensitization Rules

This interface is used to set view/control desensitization rules. Controls that match the rules will be desensitized.

Affected functional modules:

  1. Action (Operation): Control content that matches desensitization rules will be set to ***.
  2. SessionReplay (Session Playback): Controls that match desensitization rules will be masked.
  3. Trace (Trajectory): Control content that matches desensitization rules will be set to ***.
Bonree withViewSensitiveRules(List<SensitiveViewRule> sensitiveRules)
SensitiveViewRule constructors:
SensitiveViewRule(SensitiveType sensitiveType, String content)
SensitiveViewRule(SensitiveType sensitiveType, int id)
ParameterDescription
sensitiveRulesRule queue to set (maximum 200, content length limited to 256 characters)
  • Example
ArrayList<SensitiveViewRule> sensitiveViewRules = new ArrayList<>();
SensitiveViewRule ruleA = new SensitiveViewRule(SensitiveViewRule.SensitiveType.VIEW, AppCompatTextView.class.getName());
SensitiveViewRule ruleB = new SensitiveViewRule(SensitiveViewRule.SensitiveType.ID, R.id.battery_wakeLock);
SensitiveViewRule ruleC = new SensitiveViewRule(SensitiveViewRule.SensitiveType.STRING_ID, "location");
sensitiveViewRules.add(ruleA);
sensitiveViewRules.add(ruleB);
sensitiveViewRules.add(ruleC);
Bonree.withAppID("<#AppID#>")
.withViewSensitiveRules(sensitiveViewRules)
.start(getApplicationContext());

2. Data Acquisition Interfaces

Get Device ID

If the withDeviceID interface was set during SDK startup, the custom ID will be returned.

static java.lang.String getDeviceID()
  • Example
String deviceID = Bonree.getDeviceID();
Log.w("TAG", "BRSDK: " + deviceID);

Get Current SDK Version

Get the current SDK version.

static java.lang.String getSdkVersion();
  • Example
String sdkVersion = Bonree.getSdkVersion();
Log.w("TAG", "BRSDK: " + sdkVersion);

3. Custom Information Setting Interfaces

Custom User Information

BonreeSDK supports setting user-related information to complete scenarios where performance data needs to be associated with actual users.

There are two ways to set user information:

  • Set user ID to identify the user with a string
static void setUserID(java.lang.String userID);
ParameterDescriptionParameter RestrictionsFailure Result
userIDIdentify user with stringCan be empty or null string
String length ≤256, and must not contain special characters (only numbers, letters, Chinese characters, colons, spaces, slashes, underscores, hyphens, periods, asterisks, exclamation marks, @, # allowed; empty or null strings are invalid), otherwise interface call fails
Current setting invalid
  • Example
Bonree.setUserID("18988888888");

Set User Additional Information

  • Set more detailed additional user information.
static void setUserExtraInfo(java.util.Map<java.lang.String, java.lang.Object> extraInfo);
ParameterDescriptionParameter RestrictionsFailure Result
extraInfoUser additional informationMap can have maximum 64 kv pairs, only 64 retained if exceeded; key length <256, invalid if exceeded; value <512, truncated if exceededCurrent setting invalid
  • Example
HashMap<String, Object> userInfo = new HashMap<>(3);
userInfo.put("phoneNumber", "18988888888");
userInfo.put("clientID", "android device id");
userInfo.put("type", "vip");
Bonree.setUserExtraInfo(userInfo);

Add User Additional Information

  • Add user additional information
static void addUserExtraInfo(java.lang.String key, java.lang.Object value)
ParameterDescriptionParameter RestrictionsFailure Result
keyKey to addkey length <256, invalid if exceededCurrent setting invalid
valueValue corresponding to keyvalue <512, truncated if exceededCurrent setting invalid
  • Example
Bonree.addUserExtraInfo("age", "18");

Remove User Additional Information

  • Remove user additional information
static void removeUserExtraInfo(java.lang.String key)
ParameterDescriptionParameter RestrictionsFailure Result
keyKey to removekey length <256, invalid if exceededCurrent setting invalid
  • Example
Bonree.removeUserExtraInfo("age");

Accumulate User Numerical Information

  • Accumulate user numerical information
static void increaseUserExtraInfo(java.lang.String key, java.lang.Number value)
ParameterDescriptionParameter RestrictionsFailure Result
keyKey to addkey length <256, invalid if exceededCurrent setting invalid
valueValue corresponding to keyvalue only supports Number typeCurrent setting invalid
  • Example
Bonree.increaseUserExtraInfo("number", 1);

User Additional Information (Deprecated)

  • This interface is deprecated Please use the setUserExtraInfo interface.
@Deprecated
static void setExtraInfo(java.util.Map<java.lang.String, java.lang.Object> extraInfo)
ParameterDescriptionParameter RestrictionsFailure Result
extraInfokv stores more user informationMap can be empty or null collection
Length after converting to JSON must be within 7000 characters, otherwise interface call fails
Current setting invalid
  • Example
HashMap<String, Object> userInfo = new HashMap<>(3);
userInfo.put("phoneNumber", "18988888888");
userInfo.put("clientID", "android device id");
userInfo.put("type", "vip");
Bonree.setExtraInfo(userInfo);

Add Event Common Attributes

  • Add event common attributes
static void addEventAttributes(java.util.Map<String, Object> attributes, boolean isSaveLocal)
ParameterDescriptionParameter RestrictionsFailure Result
attributesInformation to add, same key will overwrite previous settingsmap can have maximum 64 kv pairs, only 64 retained if exceededCurrent setting invalid
isSaveLocalWhether to persist locally, true: common attributes will be persisted locally, will still carry common attributes when app opens next time. false: only effective during current usage periodCurrent setting invalid
  • Example
HashMap<String, Object> attributes = new HashMap<>(3);
attributes.put("onclick", "1");
attributes.put("page", "1");
attributes.put("type", "vip");
Bonree.addEventAttributes(attributes, true);

Add Single Event Common Attribute

  • Add single event common attribute
static void addEventAttribute(java.lang.String key, java.lang.Object value, boolean isSaveLocal)
ParameterDescriptionParameter RestrictionsFailure Result
keyKey of information to addkey length ≤256, invalid if exceededCurrent setting invalid
valueValue of information to addvalue length ≤512, truncated if exceededCurrent setting invalid
isSaveLocalWhether to persist locally, true: common attributes will be persisted locally, will still carry common attributes when app opens next time. false: only effective during current usage periodCurrent setting invalid
  • Example
Bonree.addEventAttribute("onclick", 1, true);

Remove Event Common Attributes

  • Remove event common attributes
static void removeEventAttribute(java.lang.String[] keys)
ParameterDescriptionParameter RestrictionsFailure Result
keysArray of keys to deletekey length ≤256, invalid if exceededCurrent setting invalid
  • Example
String[] removeKeys = {"name", "age"};
Bonree.removeEventAttribute(removeKeys);

Remove All Event Common Attributes

  • Remove all event common attributes
static void removeAllEventAttributes()
  • Example
Bonree.removeAllEventAttributes();

Custom Exception

Call the interface with corresponding parameters to complete the statistics collection for custom exception data.

static void setCustomException(java.lang.Throwable throwable) // Recommended, directly pass Exception or Throwable object
ParameterDescriptionParameter RestrictionsFailure Result
throwableException objectSystem thrown exception object, non-nullCurrent setting invalid
  • Example
try {
String userName = null;
Log.w("TAG", "user name: " + userName.trim());
} catch(Exception e) {
e.printStackTrace();
// Recommended to use Throwable overload, directly pass the object
Bonree.setCustomException(e);
}
// This overload configuration is more flexible and can be used for business exception reporting. Relevant parameters can be filled with any content that meets parameter restrictions, and the platform will display them directly.
static void setCustomException(java.lang.String exceptionType, java.lang.String causeBy, java.lang.String errorDump)
ParameterDescriptionParameter RestrictionsFailure Result
exceptionTypeException type (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
causeByException causeCan be empty or null string
String length ≤512, truncated if exceeded
-
errorDumpException informationWill be truncated if exceeding 10000 charactersCan be empty or null string
String length ≤10000, truncated if exceeded
  • Example
try {
String userName = null;
Log.w("TAG", "user name: " + userName.trim());
} catch(Exception e) {
e.printStackTrace();
String errorDump = StringUtils.join(e.getStackTrace(), "\r\n");
Bonree.setCustomException(e.getClass().getName(), e.getMessage(), errorDump);
}

Custom View

Call the interface with corresponding parameters to complete the statistics collection for custom view data.

// Custom view - page start, must be called in pairs with page end, usually called at: onResume name view name is required field, if empty the call fails.
static void setCustomPageStart(java.lang.String pageName, java.lang.String param);

// Custom view - page end, must be called in pairs with page start, usually called at: onPause
static void setCustomPageEnd(java.lang.String pageName, java.lang.String param);
ParameterDescriptionParameter RestrictionsFailure Result
pageNameView name (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
paramAdditional information, can be set as view aliasCan be empty or null string
String length ≤256, truncated if exceeded
-
  • Example
@Override
protected void onResume() {
Bonree.setCustomPageStart(getClass().getName(), "Home Page");
super.onResume();
}

@Override
protected void onPause() {
Bonree.setCustomPageEnd(getClass().getName(), "Home Page");
super.onPause();
}

Custom Events (Full Version)

Call the start and end interfaces respectively with corresponding parameters to complete the statistics collection for custom event data and event duration.

static void setCustomEventStart(String eventID, String name);
static void setCustomEventStart(String eventID, String name, String label);
static void setCustomEventStart(String eventID, String name, String label, String param);
static void setCustomEventStart(String eventID, String name, String label, String param, Map<String, String> info);
static void setCustomEventEnd(String eventID, String name);
static void setCustomEventEnd(String eventID, String name, String label);
static void setCustomEventEnd(String eventID, String name, String label, String param);
static void setCustomEventEnd(String eventID, String name, String label, String param, Map<String, String> info);
ParameterDescriptionParameter RestrictionsFailure Result
eventIDEvent ID (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
nameEvent nameCan be empty or null string
String length ≤256, truncated if exceeded
-
labelEvent labelCan be empty or null string
String length ≤256, truncated if exceeded
-
paramEvent additional informationCan be empty or null string
String length ≤7000, truncated if exceeded
-
infoEvent business informationLength after converting to JSON must be within 7000 characters, otherwise interface call fails-
  • Example
Bonree.setCustomEventStart("vip-login", "Verification code sent", "Login");
Bonree.setCustomEventEnd("vip-login", "Verification code sent", "Login");

// Call with info field
HashMap<String, String> info = new HashMap<>(3);
info.put("eventNumber", "10001");
info.put("eventName", "bonree");
info.put("eventXX", "xx");
Bonree.setCustomEventStart("vip-login", "Login failed", "Login", null, info);
Bonree.setCustomEventEnd("vip-login", "Verification code sent", "Login", null, info);

Custom Events (Simplified Version)

Call the interface with corresponding parameters to complete the statistics collection for custom event data.

static void setCustomEvent(String eventID, String name);
static void setCustomEvent(String eventID, String name, String param, Map<String, String> info);
static void setCustomEventWithLabel(String eventID, String name, String label);
static void setCustomEventWithLabel(String eventID, String name, String label, String param, Map<String, String> info);
ParameterDescriptionParameter RestrictionsFailure Result
eventIDEvent ID (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
nameEvent nameCan be empty or null string
String length ≤256, truncated if exceeded
-
labelEvent labelCan be empty or null string
String length ≤256, truncated if exceeded
-
paramEvent additional informationCan be empty or null string
String length ≤7000, truncated if exceeded
-
infoEvent business informationLength after converting to JSON must be within 7000 characters, otherwise interface call fails-
  • Example
Bonree.setCustomEvent("001", "Register");
Bonree.setCustomEventWithLabel("vip-login", "Login failed", "Login");

HashMap<String, String> info = new HashMap<>(3);
info.put("eventNumber", "10001");
info.put("eventName", "bonree");
info.put("eventXX", "xx");
Bonree.setCustomEvent("vip-login", "Login failed", null, info);
Bonree.setCustomEventWithLabel("vip-login", "Login failed", "Login", null, info);

Custom Logs

Call the interface with corresponding parameters to complete the statistics collection for custom log data.

static void setCustomLog(java.lang.String logInfo)
ParameterDescriptionParameter RestrictionsFailure Result
logInfoLog information (required)String length must be >0, otherwise interface call fails
String length ≤10000, truncated if exceeded
Current setting invalid
  • Example
Bonree.setCustomLog("login successful...");

Custom Metrics

Call the interface with corresponding parameters to complete the statistics collection for custom metric data.

static void setCustomMetric(java.lang.String name, long value)
ParameterDescriptionParameter RestrictionsFailure Result
nameMetric name (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
valueMetric value (required)Long.MAX_VALUE-
  • Example
Bonree.setCustomMetric("Custom Metric", System.currentTimeMillis());

Custom Methods

Call the interface with corresponding parameters to complete the statistics collection for custom metric data. Custom method instrumentation is mostly used for manual instrumentation of business methods or asynchronous methods not within the SDK's automatic collection scope.

static void setCustomMethodStart(java.lang.String name);
static void setCustomMethodEnd(java.lang.String name);
ParameterDescriptionParameter RestrictionsFailure Result
nameMethod name (required)String length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
  • Example
public void onNetworkLoad() {
Bonree.setCustomMethodStart("onNetworkLoad");
// do something
SystemClock.sleep(5000);
Bonree.setCustomMethodEnd("onNetworkLoad");
}

Custom Network

Call the interface with corresponding parameters to complete the statistics collection for custom metric data. Custom method instrumentation is mostly used for manual instrumentation of business methods or asynchronous methods not within the SDK's automatic collection scope.

static void setCustomNetwork(NetworkCustomEventBean networkCustomEvent)
ParameterDescriptionParameter RestrictionsFailure Result
networkCustomEventEntity structure (required)Metric structure object. Required parameterCurrent setting invalid
@param java.lang.String requestUrl                        // Request URL
@param NetworkCustomEventBean.HttpMethod method // Request method
@param java.lang.String targetIp // Target IP
@param int targetPort // Target port
@param int dnsTimeUs // DNS query time
@param int connectTimeUs // TCP connection time
@param int sslTimeUs // SSL time
@param int requestTimeUs // Request time
@param int responseTimeUs // Response time
@param int downloadTimeUs // Download time
@param int downloadSizeByte // Response data size
@param NetworkCustomEventBean.ProtocolType protocolType // Protocol type
@param java.util.List cnameArray // CNAME collection
@param int errorCode // Error code
@param java.lang.String errorMessage // Error description
@param NetworkCustomEventBean.ErrorOccurrentProcess // Error occurrence process stage
@param int requestDataSize // Request size field
@param java.lang.String resourceType // Resource type
@param Map<String, String> requestHeader // Request header
@param Map<String, String> responseHeader; // Response header
  • Example
Bonree.setCustomNetwork(new NetworkCustomEventBean("https://www.baidu.com",
NetworkCustomEventBean.HttpMethod.GET,
443,
20000,
10000,
50000,
20000,
500000,
10000,
55,
NetworkCustomEventBean.ProtocolType.HTTP1S
));

Custom Cold Launch End

After configuring the withUseCustomLaunch interface in the startup configuration, calling this custom interface can set the current moment as the end point of the custom cold launch event.

static void recordCustomLaunchEnd()
  • Example
Bonree.recordCustomLaunchEnd();

Set Custom Request Information Interface

Call the interface with corresponding parameters to associate custom string information with matched network data.

static void setRequestExtraInfo(java.lang.String headerKey, java.lang.String headerValue, java.lang.String info)
  • Interface Description
ParameterDescriptionParameter RestrictionsFailure Result
headerKeyKey to matchString length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
valueRequest header Value to matchString length must be >0 and ≤256, otherwise interface call failsCurrent setting invalid
infoAssociated custom informationString length >0 and ≤256, if empty then clears information cached for corresponding key-valueExcess part will be truncated
  • Example

Before using this interface, ensure that the target request has a unique identifier in the request header. For example, a request header might be:

POST /upload HTTP/1.1
Host: sdkupload.bonree.com
Content-Type: application/json
Content-Length: 781
Connection: keep-alive
Br-Content-Encoding: gzip
Operation-Type: vip-login

Where Operation-Type is the unique identifier field for this request. To associate information with this request:

vip-id:8888

Then call before the request is sent:

Bonree.setRequestExtraInfo("Operation-Type", "vip-login", "vip-id:8888");

Custom Action End

Call this interface to end the operation matched based on the call stack. This method must be called directly or indirectly by the operation-related method, otherwise the interface call is invalid.

static void recordCustomActionEnd()
  • Usage Scenario

Take the login scenario as an example:

  1. Click the login button in LoginActivity, triggering the onClick(View view) callback;
  2. In the onClick callback, send a login request;
  3. After the login request succeeds, persist user information and jump to HomeActivity;
  4. Refresh the home page display data in HomeActivity;

If we define the end point of the login operation as when the Home page becomes visible to the user, then we can call the custom operation end interface in the onResume() function of HomeActivity to stop the event collection operation of the previous login button.

  • Example
@Override
protected void onResume() {
super.onResume();
Bonree.recordCustomActionEnd();
}

Set Crash Callback

Call this interface and pass in the crash listener object. The SDK can then call back to the business when processing crash exceptions, allowing the business to add custom logic during the callback.

static void setCrashCallback(CrashCallback callback)
public interface CrashCallback {
/**
* This interface is executed when the Crash processing callback occurs.
*
* @param isNativeCrashed Whether it is a Native Crash
* @param crashType Crash type
* @param crashMsg Crash message, e.g., "Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference"
* @param crashStack Crash stack trace
* @param crashUuid Unique identifier for this exception
*/
void onCrash(boolean isNativeCrashed, String crashType, String crashMsg, String crashStack, String crashUuid);
}
ParameterDescriptionParameter ConstraintsFailure Result
callbackCrash callbackCurrent setting is invalid
  • Example
CrashCallback crashCallback = new CrashCallback() {
@Override
public void onCrash(boolean isNativeCrashed, String crashType, String crashMsg, String crashStack, String crashUuid) {
Log.e(TAG, "onCrash isNativeCrashed: " + isNativeCrashed);
Log.e(TAG, "onCrash crashType: " + crashType);
Log.e(TAG, "onCrash crashMsg: " + crashMsg);
Log.e(TAG, "onCrash crashStack: " + crashStack);
Log.e(TAG, "onCrash crashUuid: " + crashUuid);
}
};
Bonree.setCrashCallback(crashCallback);

Start Session Replay Upload

Under the condition that the session replay function is enabled, the SDK by default only uploads replay data when an issue occurs. If the client actively calls this interface, it will immediately enable the continuous upload capability for session replays.

static void startSessionReplayUpload()
  • Example
public void onClick(View view) {
Log.e("User enters a critical business flow, operations need to be retained");
Bonree.startSessionReplayUpload();
}

4. OnlineTracking

Debug Authorization Interface

Debug authorization interface, used to authorize or cancel authorization for SDK's subsequent tracking debugging behavior at any time. Only effective for the current run, not persisted.

static void authorizeOnlineTracking(boolean isAuthorized)
  • Interface Description
ParameterDescriptionParameter RestrictionsFailure Result
isAuthorizedAuthorize/Cancel authorizationtrue/false-
  • Example
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// Can grant/revoke permissions early in app runtime
Bonree.authorizeOnlineTracking(true);
}
}

Authorization Callback Interface

Authorization callback interface for passive authorization. When the SDK client receives a debugging request from the server during the current run without actively calling the Bonree.authorizeOnlineTracking(boolean isAuthorized) interface to authorize/cancel authorization, the callback passed to this interface will be invoked.

static void setOnlineTrackingAuthenticationCallBack(com.bonree.sdk.agent.Bonree.AuthenticationCallBack callback)
  • Interface Description
ParameterDescriptionParameter RestrictionsFailure Result
callbackCallback instanceRequired non-nullCurrent setting invalid
  • Example
Bonree.setOnlineTrackingAuthenticationCallBack(() -> {
// Must call this authorization interface within 30 seconds of receiving the SDK's authorization request callback to inform the SDK whether debugging is allowed. Timeout will be considered as rejection of the current debugging.
if (DEBUG) {
// Can flexibly change verification conditions according to own business, such as popping up a dialog asking user for authorization in this callback (*this callback is in a child thread, directly updating UI is prohibited), let user decide whether to authorize and then call the authorizeOnlineTracking authorization interface.
Bonree.authorizeOnlineTracking(true);
}
});

5. Protocol Extension Interfaces

This chapter introduces the use and description of interfaces based on protocol extension.

Create Extension Protocol Instance

Call the creation interface to return an instance object that implements the Span protocol.

public static Span startSpan(java.lang.String name, java.lang.String type);
  • Interface Description
ParameterDescriptionParameter RestrictionsFailure Result
nameProtocol extension name (required)String length >0 and ≤256, truncated if exceeded, only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ allowed, empty or null strings invalidInterface call invalid
typeProtocol extension type (required)String length >0 and ≤256, truncated if exceeded, only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ allowed, empty or null strings invalidInterface call invalid
Return TypeDescription
SpanProtocol extension instance object
  • Example
//...
// Create Span
Span mSpan = Bonree.startSpan("name", "type");

Note: The creation interface startSpan must be called in pairs with the completion interface finish() or finish(Span.SpanStatus spanStatus).

Protocol Extension Completion

Complete this protocol extension data. Calling other instance methods after completion is invalid.

public void finish();

public void finish(Span.SpanStatus spanStatus);
  • Interface Description
ParameterDescriptionParameter RestrictionsFailure Result
spanStatusProtocol extension statusValues SPAN_STATUS_UNKNOWN, SPAN_STATUS_OK, SPAN_STATUS_ERROR-
  • Example
Span span = Bonree.startSpan("name", "type");
//...
// Complete this Span
span.finish();
// or
span.finish(Span.SpanStatus.SPAN_STATUS_OK);

Create Child Span Instance

Create a child span object on a protocol extension object, returning an instance that implements the Span protocol.

    public Span startChild(java.lang.String name, java.lang.String type);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
nameThe name of the protocol extension (required)String length greater than 0 and less than or equal to 256; longer strings will be truncated. Only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ are allowed. Empty or blank strings are invalid.Interface call is invalid
typeThe type of the protocol extension (required)String length greater than 0 and less than or equal to 256; longer strings will be truncated. Only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ are allowed. Empty or blank strings are invalid. (Should be consistent with the parent span type, otherwise the parent span type is used)Interface call is invalid
Return TypeDescription
SpanThe instance object of the protocol extension
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Create Child Span
Span childSpan = span.startChild("name", "type");

Note: When finishing the parent protocol extension object, all its child protocol extension objects will be automatically finished (if the status has not been set, it defaults to SPAN_STATUS_OK).

Currently, only single-level protocol extensions are supported, meaning top-level Spans can create child Spans, but child Spans cannot create further child Spans.

When the Span type is one of the reserved types socket or websocket, creating child Spans under it is temporarily not supported.

Set Data

Set the Data within the protocol extension.

    public void setData(java.lang.String key, java.lang.String value);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyThe key corresponding to the Data (required)String length greater than 0 and less than or equal to 200; case-insensitive. Allows letters, underscores, hyphens, periods, and must start and end with a letter.Interface call is invalid
valueThe value of the Data (required)String length greater than 0 and less than or equal to 7000; longer strings will be truncated.-
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Add Data
span.setData("key", "value");

Remove Data

Remove the Data within the protocol extension.

    public void removeData(java.lang.String key);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyRemove the corresponding Data based on the key value (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
span.setData("key", "value");
//...
// Delete Data
span.removeData("key");

Set Tag

Set the Tag within the protocol extension.

    public void setTag(java.lang.String key, java.lang.String value);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyThe key corresponding to the Tag (required)String length greater than 0 and less than or equal to 200; case-insensitive. Allows letters, underscores, hyphens, periods, and must start and end with a letter.Interface call is invalid
valueThe value of the Tag (required)String length greater than 0 and less than or equal to 7000; longer strings will be truncated.-
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Add Tag data
span.setTag("key", "value");

Remove Tag

Remove the Tag within the protocol extension.

    public void removeTag(java.lang.String key);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyRemove the corresponding Tag based on the key value (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
span.setTag("key", "value");
//...
// Delete Tag data
span.removeTag("key");

Set Metric

1. Set Metric data within the protocol extension (without unit)

    public void setMetric(java.lang.String key, java.lang.String value);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyThe key corresponding to the Metric (required)String length greater than 0 and less than or equal to 200; case-insensitive. Allows letters, underscores, hyphens, periods, and must start and end with a letter.Interface call is invalid
valueThe value of the Metric (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Add Metric data
span.setMetric("key", 1000);

2. Set Metric data within the protocol extension (with unit)

    public void setMetric(java.lang.String key, long value, java.lang.String unit);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyThe key corresponding to the Metric (required)String length greater than 0 and less than or equal to 200; case-insensitive. Allows letters, underscores, hyphens, periods, and must start and end with a letter.Interface call is invalid
valueThe value of the Metric (required)--
unitThe unit name of the Metric (required)String length greater than 0 and less than or equal to 256. Only numbers, letters, colons, spaces, slashes, underscores, hyphens, periods, @ are allowed. Predefined enum units (Span.SpanMetricUnit) can be used.Only the unit setting is invalid
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Add Metric data
span.setMetric("key", 1000, "tcp");
// or
span.setMetric("key", 1000, Span.SpanMetricUnit.Byte);

Note: The SDK has predefined unit types internally, see the Span.SpanMetricUnit enum class for predefined unit types. Custom units are supported.

Remove Metric

Remove the Metric within the protocol extension.

    public void removeMetric(java.lang.String key);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
keyRemove the corresponding Metric based on the key value (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
span.setMetric("key", 1000, "ms");
//...
// Delete Metric data
span.removeMetric("key");

Set Status

Set the status of the protocol extension.

    public void setStatus(Span.SpanStatus status);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
statusThe status of the protocol extension instance. Values: SPAN_STATUS_UNKNOWN, SPAN_STATUS_OK, SPAN_STATUS_ERROR (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Set Status
span.setStatus(Span.SpanStatus.SPAN_STATUS_OK);

Set StatusCode

Set the status code of the protocol extension.

    public void setStatusCode(java.lang.String code);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
statusCodeThe value of the status code (required)String length greater than 0 and less than or equal to 7000; longer strings will cause the interface call to be invalid.Interface call is invalid
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Set Status Code
span.setStatusCode("200");

Set Duration

Actively set the duration of the span. If this method is not actively called, the span duration is the time from start to finish.

    public void setDuration(long duration);
  • Interface Description
Parameter NameDescriptionParameter ConstraintsFailure Result
durationThe duration of the protocol extension, unit: microseconds (us) (required)--
  • Example
    Span span = Bonree.startSpan("name", "type");
//...
// Set Duration
span.setDuration(100);