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

# HarmonyOS SDK integration

> Integrate Flashduty RUM SDK into HarmonyOS NEXT applications to collect views, actions, network requests, errors, and crashes

The HarmonyOS SDK provides RUM, Trace, and Crash capabilities through ArkTS HAR modules. After initialization, the SDK reports views, user actions, network requests, errors, and crashes to Flashduty RUM, with `source: "harmony"` identifying the data source.

<Info>
  The current SDK module version is `0.1.3`. The examples use `@flashcatcloud/core`, `@flashcatcloud/rum`, `@flashcatcloud/trace`, and `@flashcatcloud/crash`.
</Info>

## Prerequisites

Before integrating the SDK, complete these steps:

* Create or select a RUM application in the Flashduty console, then obtain the **Application ID** and **Client Token**
* Make sure your application can reach `https://browser.flashcat.cloud/api/v2/rum`
* Declare the `ohos.permission.INTERNET` permission in the host application so the SDK can upload event batches
* Use a HarmonyOS NEXT / Stage model project and initialize the SDK early in application startup

## Install the SDK

Add the Flashduty modules you need to the application module's `oh-package.json5`. For RUM only, add at least `core` and `rum`; add the Trace and Crash modules when you need network trace correlation or crash reporting.

```json5 oh-package.json5 theme={null}
{
  dependencies: {
    "@flashcatcloud/core": "0.1.3",
    "@flashcatcloud/rum": "0.1.3",
    "@flashcatcloud/trace": "0.1.3",
    "@flashcatcloud/crash": "0.1.3"
  }
}
```

## Initialize the SDK

Initialize the SDK in `AbilityStage.onCreate` when possible. This registers the core instance, RUM, Trace, and Crash before pages, network requests, or exceptions happen.

```ts MyAbilityStage.ets theme={null}
import { AbilityStage } from '@kit.AbilityKit';
import {
  Flashcat,
  ConfigurationBuilder,
  FlashcatSite,
  TrackingConsent
} from '@flashcatcloud/core';
import {
  FlashcatRum,
  RumConfigurationBuilder
} from '@flashcatcloud/rum';
import {
  FlashcatTrace,
  TraceConfigurationBuilder
} from '@flashcatcloud/trace';
import {
  FlashcatCrash,
  CrashConfigurationBuilder
} from '@flashcatcloud/crash';

export default class MyAbilityStage extends AbilityStage {
  onCreate(): void {
    const coreConfig = new ConfigurationBuilder('<CLIENT_TOKEN>', 'production')
      .setService('shopping-app')
      .setVariant('default')
      .useSite(FlashcatSite.CN)
      .build();

    Flashcat.initialize(this.context, coreConfig, TrackingConsent.GRANTED);

    FlashcatRum.enable(
      new RumConfigurationBuilder('<APPLICATION_ID>')
        .setSessionSampleRate(100)
        .setTrackUserInteractions(true)
        .setTrackNavigation(true)
        .setTrackNetworkRequests(true)
        .build()
    );

    FlashcatTrace.enable(
      new TraceConfigurationBuilder()
        .setSampleRate(100)
        .setFirstPartyHosts(['api.example.com'])
        .build()
    );

    FlashcatCrash.enable(new CrashConfigurationBuilder().build());
  }
}
```

<Warning>
  Do not use server-side secrets in client code. `clientToken` is only for client-side RUM reporting, and `applicationId` assigns events to the RUM application.
</Warning>

## Track views

If your application uses ArkUI `router`, start automatic view tracking after you obtain a `UIContext`. This only takes effect when RUM is configured with `setTrackNavigation(true)`.

```ts pages/Index.ets theme={null}
import { FlashcatRum } from '@flashcatcloud/rum';

@Entry
@Component
struct Index {
  aboutToAppear(): void {
    FlashcatRum.startViewTracking(this.getUIContext());
  }
}
```

Automatic view tracking listens to `routerPageUpdate`:

| Page state     | SDK behavior                                                                                         |
| -------------- | ---------------------------------------------------------------------------------------------------- |
| `ON_PAGE_SHOW` | Generates `startView`; the view name prefers the route name and falls back to the final path segment |
| `ON_PAGE_HIDE` | Generates `stopView`; closes the current view and refreshes its duration                             |

If your page does not use `router`, use the manual API to manage views.

```ts theme={null}
import { GlobalRumMonitor } from '@flashcatcloud/rum';

const monitor = GlobalRumMonitor.get();

monitor.startView('checkout', 'Checkout');
monitor.stopView('checkout');
```

## Track user actions

After enabling `setTrackUserInteractions(true)`, call `FlashcatRum.trackTap()` from your button handler or shared click wrapper. The SDK does not automatically traverse all components.

```ts theme={null}
import { FlashcatRum } from '@flashcatcloud/rum';

Button('Pay')
  .onClick(() => {
    FlashcatRum.trackTap('pay_button');
    // Run your business logic
  });
```

You can also use `GlobalRumMonitor` to record instantaneous or timed actions.

```ts theme={null}
import {
  GlobalRumMonitor,
  RumActionType
} from '@flashcatcloud/rum';

const monitor = GlobalRumMonitor.get();

monitor.addAction(RumActionType.TAP, 'checkout_button');

monitor.startAction(RumActionType.SCROLL, 'product_feed');
monitor.stopAction(RumActionType.SCROLL, 'product_feed');
```

## Track network requests and Trace

The HarmonyOS SDK supports two network integration paths.

### rcp interceptor

If your application uses `rcp` from `@kit.RemoteCommunicationKit`, add `FlashcatTrace.interceptor()` to the session. The interceptor injects W3C `traceparent` and `tracestate`, and sends request lifecycle events to RUM so they become resource events.

```ts theme={null}
import { rcp } from '@kit.RemoteCommunicationKit';
import { FlashcatTrace } from '@flashcatcloud/trace';

const session = rcp.createSession({
  interceptors: [FlashcatTrace.interceptor()]
});

const response = await session.get('https://api.example.com/orders');
session.close();
```

### FlashcatHttp wrapper

If your application uses `@kit.NetworkKit`, use `FlashcatHttp.request()` instead of `http.createHttp().request(...)`. The wrapper generates a RUM resource or network error when the request completes or fails.

```ts theme={null}
import { http } from '@kit.NetworkKit';
import { FlashcatHttp } from '@flashcatcloud/trace';

const response = await FlashcatHttp.request('https://api.example.com/orders', {
  method: http.RequestMethod.GET
});
```

<Note>
  `traceparent` and `tracestate` are injected only when tracking consent is `TrackingConsent.GRANTED`. `FlashcatHttp` also honors `setFirstPartyHosts()`; when no first-party host is configured, it injects into all hosts. If a request already has `traceparent`, the SDK does not overwrite the existing Trace context.
</Note>

For other network stacks, use `FlashcatTrace.getHeaders()` to get `traceparent` and `tracestate` headers for manual injection.

```ts theme={null}
const headers = FlashcatTrace.getHeaders();
// Merge headers into your custom network request
```

## Identify users

After sign-in, set the current user. The SDK writes these fields to the `usr` object on subsequent RUM events.

```ts theme={null}
import { Flashcat } from '@flashcatcloud/core';

Flashcat.getInstance().setUserInfo({
  id: 'user-1001',
  name: 'Alice',
  email: 'alice@example.com'
});
```

<Warning>
  `setUserInfo()` currently sets only `id`, `name`, and `email`. The server does not accept other user fields; use RUM global attributes or per-event attributes to write business dimensions to `context`.
</Warning>

Clear user information after sign-out.

```ts theme={null}
Flashcat.getInstance().clearUserInfo();
```

## Verify the integration

After integration, verify it with these steps:

1. Temporarily enable `setVerbose(true)` and inspect HiLog entries with the `Flashcat` tag
2. Open the application and trigger page navigation, button taps, network requests, or a manual error
3. In the Flashduty RUM application, filter for `source:harmony` and confirm view, action, resource, or error events
4. For network requests, confirm your backend Trace receives `traceparent`
5. After triggering Crash, restart the application; HarmonyOS replays crash events on the next launch

## Next steps

<CardGroup cols={3}>
  <Card title="Advanced configuration" icon="sliders" href="/en/rum/sdk/harmony/advanced-config">
    Configure sampling, tracking consent, event mapping, Trace, and crash symbol upload.
  </Card>

  <Card title="Compatibility" icon="shield-check" href="/en/rum/sdk/harmony/compatible">
    Review supported HarmonyOS projects, Kits, permissions, and current limits.
  </Card>

  <Card title="Data collection" icon="database" href="/en/rum/sdk/harmony/data-collection">
    Review event types, fields, and upload behavior collected automatically or manually by the SDK.
  </Card>
</CardGroup>
