> ## Documentation Index
> Fetch the complete documentation index at: https://mw-docs.middleware.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Mobile RUM - Android SDK

> Android RUM - Setup & Installation Docs | Middleware

The Mobile RUM SDK provides a customizable suite of tools to analyze and optimize the performance of Android applications. Isolate ANR and network changes, quickly detect application crashes, identify slow or frozen frames and more.

<Note> To see an example of how to deploy the Mobile RUM Android SDK, navigate to our GitHub repository [here](https://github.com/middleware-labs/middleware-android/#middleware-android-sdk). </Note>

# Prerequisites

`Android SDK Version 21` or above. Check your Android SDK version with the following command:

```shell Shell theme={null}
./sdkmanager --list
```

# Install & Instrument Your Android Application

### Step 1: Install Middleware Android SDK

```Java Java theme={null}
implementation 'io.middleware.android:sdk:+'
```

### Step 2: Add Application Instrumentation Config

<Note> To modify your configuration methods, navigate to the [Configuration Methods]() section </Note>

```Java Java theme={null}
class MyApplication extends Application {
  private final String targetUrl = "<target-url>";
  private final String rumAccessToken = "<your-access-token>";

  @Override
  public void onCreate() {
      super.onCreate();

    Middleware.builder()
        .setTarget(targetUrl)
        .setServiceName("sample-android-app-1")
        .setProjectName("Mobile-SDK-Android")
        .setRumAccessToken(rumAccessToken)
        .setSlowRenderingDetectionPollInterval(Duration.ofMillis(1000))
        .setDeploymentEnvironment("PROD")
        .build(this);
  }
}
```

### Step 2a: Configuration Methods \[Optional]

Understand the behavior of your RUM Android application with the following methods and set particular attributes related to telemetry ingestion, monitoring, and instrumentation.

| Method                                            | Description                                                                                               |
| :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------- |
| `setRumAccessToken(String)`                       | Authorizes client to send telemetry to Middleware                                                         |
| `setTarget(String)`                               | Sets target URL to recieve telemetry                                                                      |
| `setService(String)`                              | Sets service name of your application                                                                     |
| `setDeploymentEnvironment(String)`                | Sets environment attribute on spans generated by instrumentation. Example: `PROD`, `DEV`                  |
| `disableCrashReporting()`                         | Disables crash reporting which is enabled by default                                                      |
| `disableAnrDetection()`                           | Disables Application Not Responding (ANR) detection which is enabled by default                           |
| `disableNetworkMonitor()`                         | Disables network change detection which is enabled by default                                             |
| `disableSlowRenderingDetection()`                 | Disables slow or frozen frame render detection which is enabled by default                                |
| `setSlowRenderingDetectionPollInterval(Duration)` | Sets default polling for slow or frozen render detection. Default detection interval is 1000 milliseconds |

### Step 3: HTTP Instrumentation Config \[Optional]

Integrate with OkHTTP3 to monitor HTTP events across user devices.

```java OkHTTP3 theme={null}
private Call.Factory buildOkHttpClient(Middleware middleware) {
  return middleware.createRumOkHttpCallFactory(new OkHttpClient());
}
```

# Custom Configurations

### Set Global Attributes

Global attributes serve as metadata or contextual information that can be attached to telemetry, traces, or logs collected by the instrumentation framework or SDK. They are key-value pairs that provide additional details about the application, device, user session, or environment.

Set the following Global Attributes to instrument your application:

```javascript Java theme={null}
Middleware.builder()
        .setGlobalAttributes(
            Attributes.builder()
                    .put("key", "value")
                    .put(StandardAttributes.APP_VERSION, BuildConfig.VERSION_NAME)
                    .build());
```

### Events

#### Step 1: Setup Your Custom Event

Send custom events and workflows using `addEvent`

```java Java theme={null}
Middleware.getInstance().addEvent("You clicked on Button", BUTTON_ATTRIBUES);
```

#### Step 2: Start Custom Event Workflow

Start custom events and workflows using `startWorkflow`

```java Java theme={null}
Span loginWorkflow = Middleware.getInstance().startWorkflow("User Login Flow");
```

#### Step 3: End Custom Event Workflow

End custom events and workflows using `end`

```java Java theme={null}
loginWorkflow.end();
```

### Error Reporting

Use `addException(Throwable)` to report exceptions, errors, and display messages on the Middleware dashboard

```java Java theme={null}
Middleware.getInstance().addException(new RuntimeException("Something went wrong!"), Attributes.empty())
```

### Logs

Add custom logs to display on your Middleware dashboard such as debug, error, warning, and info

```java Java theme={null}
Middleware logInstance = Middleware.getInstance();
logInstance.d("TAG", "I am debug");
logInstance.e("TAG", "I am error");
logInstance.i("TAG", "I am info");
logInstance.w("TAG", "I am warning");
```

### Session Replay

Control how you capture and replay your users' browsing experience. To start and stop session replay, override the `onResume` and `onPause` methods.

<Note> This feature is only available for `Android Version 8.0 (Android Oreo)` or higher </Note>

```java Java theme={null}
  final MiddlewareRecorder recorder = Middleware.getInstance().getRecorder();

  @RequiresApi(api = Build.VERSION_CODES.N)
  @Override
  protected void onResume() {
      super.onResume();
      recorder.startRecording(this);
  }

  @RequiresApi(api = Build.VERSION_CODES.N)
  @Override
  protected void onPause() {
      super.onPause();
      recorder.stopRecording();
  }
```

### Session Recording

The maximum session recording duration is four hours. If users are inactive for more than 15 minutes at a time, session recordings will be stopped. If users exceed more than four hours in a single session or become active again after the 15-minute inactivity timeout, a new session will be automatically created.

Session recording is enabled by default. Disable this feature with the following function:

```javascript Java theme={null}
.disableSessionRecording()
```

### Privacy

Blur sensitive information in session recordings by embedding the following method:

<Note> User passwords are automatically masked by default. Other sensitive information like credit card data and API keys must be masked manually. </Note>

```javascript Java theme={null}
final Middleware instance = Middleware.getInstance();
final TextView someTextView = findViewById(R.id.some_text_view);
instance.addSanitizedElement(someTextView);
```

# Default Attributes

The following Attributes are provided by the Android SDK by default:

|        **Name**        | **Type** | **Description**                                         |
| :--------------------: | :------: | :------------------------------------------------------ |
| `project.name` , `app` |  String  | Defines the project name, used as `projectName(String)` |
|     `service.name`     |  String  | Defines the service name, used as `serviceName(String)` |
|      `session.id`      |  String  | Random session identifier generated by Middleware SDK   |
|    `rum.sdk.version`   |  String  | Middleware SDK version                                  |

# Resource Attributes

The following Resource Attributes are applied to all spans by default:

|          **Name**         | **Type** | **Description**                                                                                  |
| :-----------------------: | :------: | :----------------------------------------------------------------------------------------------- |
|  `deployment.environment` |  String  | Name of deployment environment. Example: `DEV`, `PROD`                                           |
| `device.model.identifier` |  String  | Device model identifier. Example: `Moto-G30`                                                     |
|    `device.model.name`    |  String  | Name of device. Example: `ONEPLUS A600`                                                          |
|   `device.manufacturer`   |  String  | Name of device manufacturer. Example: `OnePlus`                                                  |
|         `os.name`         |  String  | Name of operating system. Sets to `Android`                                                      |
|      `os.description`     |  String  | Operating System description. Example: `Android Version 11 (Build RKQ1.201217.002 API level 30)` |
|         `os.type`         |  String  | Operating System type. Sets to `Linux`                                                           |
|        `os.version`       |  String  | Operating System version. Example: Android version `11`                                          |

# Instrumentation Attributes

The following Instrumentation Attributes are additional properties the Android SDK provides:

<Accordion title="Crash Reporting">
  Crash Reporting is enabled by default and adds the following Crash Reporting attributes to spans that represent uncaught exceptions:

  |        **Name**        | **Type** | **Description**                                                                |
  | :--------------------: | :------: | :----------------------------------------------------------------------------- |
  |       `thread.id`      |  Integer | ID of the current managed thread, as opposed to the operating system thread ID |
  |      `thread.name`     |  String  | Name of the thread                                                             |
  |   `exception.message`  |  String  | Message of the exception                                                       |
  |    `exception.type`    |  String  | Type of exception                                                              |
  | `exception.stacktrace` |  String  | Stack trace for the exception                                                  |
  |   `exception.escaped`  |  String  | Sets `true`, denoting the uncaught exception, such as a crash occurring        |
  |       `component`      |  String  | Sets `crash`                                                                   |
  |      `event.type`      |  String  | Sets `error`                                                                   |
</Accordion>

<Accordion title="Network Monitoring">
  Network Monitoring is enabled by default and produce spans with the name `network.change` and the following attributes:

  |          **Name**         | **Type** | **Description**                                                    |
  | :-----------------------: | :------: | :----------------------------------------------------------------- |
  |      `network.status`     |  String  | Network status set to `lost` or `available`                        |
  | `network.connection.type` |  String  | Connection type set to `wifi`, `cell`, `unavailable`, or `unknown` |
  |   `network.carrier.name`  |  String  | Name of network carrier used                                       |
</Accordion>

<Accordion title="Application Not Responding (ANR)">
  Application Not Responding (ANR) event detection creates spans whenever the primary application thread remains unresponsive for over 5 seconds. ANR is enabled by default.

  ANR include the following attributes:

  |        **Name**        | **Type** | **Description**               |
  | :--------------------: | :------: | :---------------------------- |
  | `exception.stacktrace` |  String  | Stack trace for the exception |
  |       `component`      |  String  | Sets `error`                  |
  |      `event.type`      |  String  | Sets `error`                  |
</Accordion>

<Accordion title="Slow Rendering Detection">
  Slow Rendering Detection produces spans whenever it identifies a slow or frozen frame render. Rendering is considered slow if its duration surpasses 16 milliseconds and frozen if it exceeds 700 milliseconds.

  During each interval, slow rendering detection generates up to two spans: one named `slowRenders` for tallying slow frames, and another named `frozenRenders` for tallying frozen frames. Slow Render Detection is enabled by default.

  Spans generated by Slow Rendering Detection include the following attribute:

  | **Name** | **Type** | **Description**                                                                                                                                                                                    |
  | :------: | :------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  |  `count` |  Integer | Number of slow or frozen frames on a 1 second interval. Change the interval duration by passing a positive integer (in milliseconds) to the `slowRenderingDetectionPollInterval(Duration)` setting |
</Accordion>

<Accordion title="HTTP Client Attributes">
  The Android RUM agent includes instrumentation for OkHttp. To activate this functionality, see Step 3 from the above installation [here](/rum/rum-android-mobile#install-and-instrument-your-android-application).

  OKHttp includes the following attributes:

  |            **Name**            | **Type** | **Description**                        |
  | :----------------------------: | :------: | :------------------------------------- |
  |          `http.method`         |  String  | `GET`, `POST`, `HEAD`                  |
  |           `http.url`           |  String  | `https://foo.bar/address?q=value#hash` |
  |          `http.flavor`         |  String  | `1.0`                                  |
  |       `http.status_code`       |  Integer | `200`, `404`, `418`                    |
  | `http.response_content_length` |  Integer | `3495`(bytes)                          |
  |        `http.user_agent`       |  String  | `CERN-LineMode/2.15 libwww/2.17b3`     |
  |         `net.transport`        |  String  | `IP.TCP`                               |
  |         `net.peer.name`        |  String  | `example.com`                          |
  |         `net.peer.port`        |  Integer | `80`, `8080`, `443`                    |
  |           `component`          |  String  | Sets `http`                            |
</Accordion>

<Accordion title="Activity Lifecycle Monitoring">
  By default, Activity lifecycle Monitoring is enabled. It generates spans whenever an activity undergoes a state change. The name of an activity lifecycle span can vary based on its state. Below is a list of all possible states:

  |             **Name**            | **Type** | **Description**                                     |
  | :-----------------------------: | :------: | :-------------------------------------------------- |
  |           `component`           |  String  | Sets `ui`                                           |
  | `activityName`, `activity.name` |  String  | Name of the activity class. Example: `MainActivity` |
</Accordion>

<Accordion title="Fragment Lifecycle Monitoring">
  Fragment lifecycle monitoring involves generating spans whenever an fragment undergoes a state change. The name of a fragment lifecycle span can vary based on its state::

  * `Created`: Activity starts for the first time.

  * `Restarted`:Activity restarts after being stopped.

  * `Resumed`: Activity resumes after a pause.

  * `Paused`: Activity is paused.

  * `Stopped`: Activity stops.

  * `Destroyed`: Activity is destroyed.

  |    **Name**    | **Type** | **Description**                                    |
  | :------------: | :------: | :------------------------------------------------- |
  |   `component`  |  String  | Sets `ui`                                          |
  | `fragmentName` |  String  | Name of the fragment class Example: `MainFragment` |
</Accordion>

<Accordion title="App Start Monitoring">
  The app start monitoring feature creates spans each time the app undergoes a cold, warm, or hot start.

  * `Cold Starts`: Occurs when users open the app for the first time after booting their phone or terminating the app.

  * `Warm Starts`: Occurs when some operations from a cold start are still in progress. Warm starts are quicker than cold starts but slower than hot starts.

  * `Hot Starts`: Occurs when the system brings an app to the foreground. They are faster than cold starts as the app is already loaded.

  App start monitoring generates spans named AppStart with associated attributes:

  |   **Name**   | **Type** | **Description**                               |
  | :----------: | :------: | :-------------------------------------------- |
  |  `component` |  String  | Sets `appstart`                               |
  | `start.type` |  String  | Type of start. Value `cold`, `warm`, or `hot` |
</Accordion>

<Note> Need assistance or want to learn more about Middleware? Contact us at support\[at]middleware.io. </Note>
