392a7efd创建于 2025年12月12日历史提交

Event Reporting

HiAppEvent provides APIs for reporting events.

Available APIs

For details about how to use the APIs, see Application Event Logging.

Data Processor APIs

API Description
addProcessor(processor: Processor): number Adds a data processor for reporting events.
removeProcessor(id: number): void Removes a data processor.

User ID APIs

API Description
setUserId(name: string, value: string): void Sets a user ID. The data processor can carry the user ID when reporting an event.
getUserId(name: string): string Obtains a user ID that has been set.

User Property APIs

API Description
setUserProperty(name: string, value: string): void Sets a user property. The data processor can carry user properties when reporting events.
getUserProperty(name: string): string Obtains a user property.

How to Develop

The following describes how to develop event logging and reporting for the button click behavior.

  1. In the entry/src/main/ets/ pages/Index.ets file, add the addprocessorTest button with Onclick() to add the data processor. analytics_demo is the data processor library preset in the device. For details, see HiAppEvent Data Processor Library. The sample code is as follows:

    import { BusinessError } from '@kit.BasicServicesKit';
    import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
    
    @Entry
    @Component
    struct Index {
      processorId: number = -1; // Initialize processorId to -1.
    
      build() {
        Row() {
          Column() {
            Button('addProcessorTest')
              .type(ButtonType.Capsule)
              .margin({
                top: 20
              })
              .backgroundColor('#0D9FFB')
              .width('50%')
              .height('5%')
              .onClick(() => {
                // In Onclick(), add a data processor.
                let eventConfig: hiAppEvent.AppEventReportConfig = {
                  domain: 'button',
                  name: 'click',
                  isRealTime: true
                };
                let processor: hiAppEvent.Processor = {
                  name: 'analytics_demo',
                  debugMode: true,
                  routeInfo: 'CN',
                  onStartReport: true,
                  onBackgroundReport: true,
                  periodReport: 10,
                  batchReport: 5,
                  userIds: ['testUserIdName'],
                  userProperties: ['testUserPropertyName'],
                  eventConfigs: [eventConfig]
                };
                this.processorId = hiAppEvent.addProcessor(processor);
              })
            // ...
          }
          .width('100%')
        }
        .height('100%')
      }
    }
    
  2. In the entry/src/main/ets/pages/index.ets file, add a button with onClick() to add and view the user ID. The sample code is as follows:

    Button('userIdTest')
      .type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .backgroundColor('#0D9FFB')
      .width('40%')
      .height('5%')
      .onClick(() => {
        // Set the user ID in onClick().
        hiAppEvent.setUserId('testUserIdName', '123456');
    
        // Obtain the user ID set in onClick().
        let userId = hiAppEvent.getUserId('testUserIdName');
        hilog.info(0x0000, 'testTag', `userId: ${userId}`)
      })
    
  3. In the entry/src/main/ets/pages/index.ets file, add a button with onClick() to add and view the user property. The sample code is as follows:

    Button('userPropertyTest')
      .type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .backgroundColor('#0D9FFB')
      .width('50%')
      .height('5%')
      .onClick(() => {
        // Set the user property in onClick().
        hiAppEvent.setUserProperty('testUserPropertyName', '123456');
    
        // Obtain the user property in onClick().
        let userProperty = hiAppEvent.getUserProperty('testUserPropertyName');
        hilog.info(0x0000, 'testTag', `userProperty: ${userProperty}`)
      })
    
  4. In the entry/src/main/ets/pages/index.ets file, add a button with onClick() to log the button click event. The sample code is as follows:

    Button('writeTest')
      .type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .backgroundColor('#0D9FFB')
      .width('40%')
      .height('5%')
      .onClick(() => {
        // In onClick(), use hiAppEvent.write() to log an event when the button is clicked.
        let eventParams: Record<string, number> = { 'click_time': 100 };
        let eventInfo: hiAppEvent.AppEventInfo = {
          // Define the event domain.
          domain: "button",
          // Define the event name.
          name: "click",
          // Define the event type.
          eventType: hiAppEvent.EventType.BEHAVIOR,
          // Define the event parameters.
          params: eventParams,
        };
        hiAppEvent.write(eventInfo).then(() => {
          hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`)
        }).catch((err: BusinessError) => {
          hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`)
        });
      })
    
  5. In the entry/src/main/ets/pages/index.ets file, add a button with onClick() to remove the data processor. The sample code is as follows:

    Button('removeProcessorTest')
      .type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .backgroundColor('#0D9FFB')
      .width('60%')
      .height('5%')
      .onClick(() => {
        // Remove the data processor in onClick().
        hiAppEvent.removeProcessor(this.processorId);
      })
    
  6. Click the Run button in DevEco Studio to run the project. Then, click the addProcessorTest, userIdTest, userPropertyTest, writeTest, and removeProcessorTest buttons one by one to trigger an event reporting.

    Once the event handler receives the event data, you can view the following information in the Log window:

    HiAppEvent success to write event