Android Monitoring API

Instana Android agent API

The following section describes the usage of the Instana Android agent. Instana’s Android agent can be used via the Instana class methods explained below.

Setup

We recommend initializing Instana in your Application class’ onCreate(), right after super.onCreate():

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Instana.setup(
            this,
            InstanaConfig(
                reportingURL = "YOUR_REPORTING_URL",
                key = "YOUR_APP_KEY"
            )
        )
    }
}

Parameters

Parameter
Description
key (String) Instana monitoring configuration key
reportingURL (String) URL pointing to the Instana instance to which to the send monitoring data to
httpCaptureConfig (HTTPCaptureConfig, optional) HTTP requests and responses will be captured automatically by default. You can also disable automatic monitoring by setting it to HTTPCaptureConfig.MANUAL. To completely turn off http session monitoring you can set it to HTTPCaptureConfig.NONE
suspendReporting (SuspendReportingType, optional) Transmission of instana beacons wil always happen in the background and with low priority. Furthermore, the client can choose in which conditions transmission of beacons will be suspended (e.g. when battery is low, when the user only has a cellullar connection, never, … ))
initialBeaconDelayMs (Long, optional) In order to make sure the client has set up all additional parameters such as Session Identifiers before sending any beacon to the Instana server, the Agent will delay the transmission of the first beacons for the determined time. Note: only the transmission of the beacons will be delayed; monitoring and capturing will start as soon as the Agent is initialized, regardless of initialBeaconDelayMs

Current Configuration

To check the current Instana configuration, simply access the InstanaConfig instance:

val currentConfig = Instana.config

Session Identifier

Each Instana agent instance has an unique session identifier you could use for other purposes in your app.

Property
Description
sessionId (String, optional) The current session identifier. This session id will be created within the setup process.

Example

val sessionId = Instana.sessionId

Automatic HTTP monitoring

By default, HTTP sessions will be be captured automatically. Upon initializing Instana (after installing the Instana Android Plugin and Instana Android SDK), the Agent will take care of the rest.

The Instana Android agent will automatically weave code to provide monitoring of HTTP requests for the supported clients:

  • OkHttp3
  • HttpURLConnection
  • Retrofit

Automatic HTTP monitoring can be disabled in favor of manual HTTP monitoring, as explained in the following section.

Manual HTTP monitoring

Automatic monitoring can be disabled in favor of manual HTTP monitoring. To do so, provide HTTPCaptureConfig.MANUAL as you initialize Instana with an InstanaConfig instance, and use the following methods:

Start Capture

This function returns the HTTPMarker which you need later when the request has been completed.

Instana {
    fun startCapture(url: String, viewName: String? = view): HTTPMarker?
}
Parameters
Parameter
Description
url (String) The URL to capture.
viewName (String, optional) Optional name of the visible view related to this request

Returns: HTTP marker to set the response size, call the finish or error state when the request has been completed.

Finish Capture

Once the request has been completed you must call finish with the response on the HTTPMarker and an optional Error:

HTTPMarker {
    fun finish(response: okhttp3.Response)
    fun finish(request: okhttp3.Request, error: Throwable)
    fun finish(connection: java.net.HttpURLConnection)
    fun finish(connection: java.net.HttpURLConnection, error: Throwable)
}

Cancel Capture

Invoke this method on the HTTPMarker if the request has been canceled before completion. The state will be set to failed internally with an NSURLErrorCancelled when calling cancel.

func cancel()

Example

val request = yourMethodToCreateRequest()
val marker = Instana.startCapture(request, viewName: "User Details")
val response = OkHttpClient().newCall(request).execute()
marker?.finish(response)

Views

Instana can segment mobile app insights by logical views. To do so, set the view name via the Instana.setView(String) method. The view will then be associated to all monitored beacons until the view changes once setView is called again.

We recommend not to use technical or generic names like the Class (i.e. WebViewActivity) to define views. We recommend the usage of readable names for views, for example product detail page or payment selection. Focusing on what users are experience will allow team members without intimate knowledge of the codebase to understand the insights provided.

Note: Instana.setView(String) should be called when a screen is presented to the user, rather than when a screen is created (as in a Fragment which could be created once but shown multiple times). Setting the view name will also enable Instana to track page transitions in addition to page loads.

Example

class WebViewActivity : AppCompatActivity() {

    override fun onResume() {
        super.onResume()
        Instana.view = "Webview: FitBit authorization"
    }
}

Identifying Users

User-specific information can optionally be sent with data transmitted to Instana. This information can then be used to unlock additional capabilities such as:

  • calculate the number of users affected by errors,
  • to filter data for specific users and
  • to see which user initiated a view change or HTTP request.

By default, Instana will not associate any user-identifiable information to beacons. Please be aware of the respective data protection laws when choosing to do so. We generally recommend identification of users via a user ID. For Instana this is a completely transparent String that is only used to calculate certain metrics. userName and userEmail can also be used to have access to more filters and a more pleasant presentation of user information.

In cases in which you are handling anonymous users and thus don’t have access to user IDs you could alternatively use session IDs. Session IDs are not as helpful as user IDs when filtering data but they are a good indicator to calculate affected/unique user metrics. We recommend setting a user name such as Anonymous to have a clear differentiation between authenticated and unauthenticated users. Session IDs can be sensitive data (depending on the framework/platform used). Please consider hashing session IDs to avoid transmitting data to Instana that can grant access.

It is important to note that data already transmitted to Instana’s server cannot be retroactively updated. For this reason it is important to call this API as early as possible in the app launch process.

Instana {
    void setUserId(@Nullable String)
    @Nullable String getUserId()
    void setUserName(@Nullable String)
    @Nullable String getUserName()
    void setUserEmail(@Nullable String)
    @Nullable String getUserEmail()
}

Example

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        Instana.setup(
            this,
            InstanaConfig(
                reportingURL = BuildConfig.INSTANA_REPORTING_URL,
                key = BuildConfig.INSTANA_KEY
            )
        )
        Instana.userId = "1234567890"
        Instana.userEmail = "instana@example.com"
        Instana.userName = "instana android agent demo"
    }
}

Meta data

Arbitrary meta data can optionally be attached to all data transmitted to Instana. Consider using this to track UI configuration values, settings, feature flags… any additional context that might be useful for analysis.

Note: we currently support up to 50 meta key/value pairs.

Instana {
     val meta = MaxCapacityMap<String, String>(50)
}

Properties

Parameter
Description
meta (MaxCapacityMap) The object which will hold all meta key/value pairs. It’s interface resembles that of a common Map; you can add and remove elements as usual, as long as you don’t go over it’s maximum capacity

Example

class UserProfileActivity : AppCompatActivity() {

    override fun onResume() {
        super.onResume()
        Instana.meta.put("user authenticated", "true")
        Instana.meta.put("user type", "editor")
    }
}

Excluding URLs from Monitoring

URLs can be ignored by providing regular expressions, by adding them to the ignoreURLs list. A good scenario for usage of this function would be to ignore all HTTP requests that contain any sensitive data like a password.

Instana {
    val ignoreURLs = mutableListOf<Regex>()
}
Instana {
    List<Pattern> getIgnoreURLs()
}

Example

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        Instana.setup(
            this,
            InstanaConfig(
                reportingURL = BuildConfig.INSTANA_REPORTING_URL,
                key = BuildConfig.INSTANA_KEY
            )
        )
        Instana.ignoreURLs.add("/.*([&?])password=.*/i".toRegex())
    }
}

The example ignores all URLs that contain a password in the query.

Google Play Services

You can explicitly tell Instana whether Google Play Services are available for a given user & session.

Instana {
    val googlePlayServicesMissing: Boolean?
}

Example

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        Instana.setup(
            this,
            InstanaConfig(
                reportingURL = BuildConfig.INSTANA_REPORTING_URL,
                key = BuildConfig.INSTANA_KEY
            )
        )
        Instana.googlePlayServicesMissing = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS
    }
}
//app/build.gradle
dependencies {
    implementation 'com.google.android.gms:play-services-basement:17.1.1'
    implementation 'com.google.android.gms:play-services-base:17.1.0'
}