目录

Barcode Scan by Default UI

The capability of barcode scanning by default UI offers a consistent scanning UI at the system level, which includes a camera preview stream, a scanning entry for the photo gallery, and a prompt to turn on the flash light in dim light conditions. For the default UI of code scanning, the system-level camera permission has been pre-granted and the camera remains securely accessible when the UI is opened. It means that you do not need to request the camera permission again. This capability can help you develop various barcode scanning scenarios for your app.

By using the capability of barcode scanning by default UI, you can achieve the in-app code scanning function. To enhance user experience, you are also advised to integrate the scan-to-access capability so your users can directly go to a specified service page in your app by scanning a barcode via either the code scanning entry on Control Panel or the in-app code scanning entry.

Use Cases

This capability provides a default scanning UI that offers streamlined system-level barcode scanning experience and a scanning entry for the photo gallery to recognize one and multiple barcodes at a time. It can recognize multiple barcode types described in ScanType. Your app can use this capability to scan barcodes in various scenarios without needing to use a third-party library.

Default scanning UI:

  1. If it is the first time the default scanning UI is opened, your app shows a privacy banner notification to the user.

  2. The user can either tap Learn more for more instructions on securely accessing the camera or directly tap the button to close the notification. After the privacy banner notification is closed and the scanning page of the app is opened again, the privacy banner notification will not be displayed, but an access security tip is displayed, which will disappear in three seconds.

  3. Since API version 6.1.0(23), the title of barcode scanning by default UI can be dynamically displayed based on the setting of scanTypes of ScanOptions.

    • For API versions earlier than 6.1.0(23), the title is displayed as "Scan QR code or barcode".
    • For API version 6.1.0(23) and later:
      • If scanTypes is set to ALL, FORMAT_UNKNOWN, or contains both barcode and QR code types, the title is displayed as "Scan QR code or barcode".
      • If scanTypes is not set, the title is displayed as "Scan QR code or barcode".
      • If scanTypes contains only the barcode type, the title is displayed as "Scan barcode".
      • If scanTypes contains only the QR code type, the title is displayed as "Scan QR code".

Constraints

Flowchart

The flowchart for using this capability is as follows.

  1. A user sends a barcode scanning request to your app.

  2. Your app calls the startScanForResult API of Scan Kit to open the barcode scanning UI.

  3. If it is the first time the default scanning UI is opened, your app shows a privacy banner notification to the user.

  4. The user can tap the close button to close the notification. When the scanning page of the app is opened again, the privacy banner notification will not be displayed, but an access security tip is displayed, which will disappear in three seconds.

  5. Scan Kit returns the barcode scanning result using a callback or promise.

  6. If multiple barcodes are recognized, the user needs to select one barcode to obtain the barcode scanning result. If only one barcode is recognized, the barcode scanning result can be directly returned.

  7. The app shows the target service page based on the parsing result to the user.

API Description

The APIs use either a callback or promise to return the result. The table below lists the APIs using a callback and those using a promise. The APIs that use a callback provide the same functions as their counterparts that use a promise. The startScanForResult API is used to open the barcode scanning UI in your app. For details about the API, please refer to API Reference.

API Description
startScanForResult(context: common.Context, options?: ScanOptions): Promise<ScanResult> Opens the default scanning UI to scan barcodes. This API uses ScanOptions to set barcode scanning parameters and return the barcode scanning result. This API uses a promise to return the result asynchronously.
startScanForResult(context: common.Context, options: ScanOptions, callback: AsyncCallback<ScanResult>): void Opens the default scanning UI to scan barcodes. This API uses ScanOptions to set barcode scanning parameters and return the barcode scanning result. This API uses a callback to return the result asynchronously.
startScanForResult(context: common.Context, callback: AsyncCallback<ScanResult>): void Starts barcode scanning using the default UI and returns the scanning result. This API uses a callback to return the result asynchronously.

The startScanForResult API must be called in the lifecycles of the UI and component. To use the scanning UI in full screen or immersive mode, please refer to Immersive Effect Development.

Development Procedure

Scan Kit provides the function of scanning barcodes using the default UI. The barcode scanning API directly controls the camera for optimal zoom control, automatic exposure adjustment, and auto-focus, creating a smooth barcode scanning experience and lowering workload for you.

To make it easier for you to integrate the capability, a detailed sample project is provided for your reference.

The following describes how to call the startScanForResult API of Scan Kit to open the barcode scanning UI:

  1. Import the module for scanning barcodes using the default UI. In the code, scanCore provides definition of scanning types and scanBarcode provides methods and parameters for opening the default scanning UI.

    import { scanCore, scanBarcode } from '@kit.ScanKit';
    // Import the required log and error code modules.
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Call the startScanForResult method to open the default UI for scanning.

    • Obtain the scanning result using a promise.
      @Entry
      @Component
      struct ScanBarCodePage {
        build() {
          Column() {
            Row() {
              Button('Promise with options')
                .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
                .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
                .align(Alignment.Center)
                .type(ButtonType.Capsule)
                .width('90%')
                .margin({ bottom: 12 })
                .onClick(() => {
                  // Define scanning parameters.
                  const options: scanBarcode.ScanOptions = {
                    scanTypes: [scanCore.ScanType.ALL],
                    enableMultiMode: true,
                    enableAlbum: true
                  };
                  try {
                    // Call the **getHostContext** API to obtain the context associated with the current page.
                    scanBarcode.startScanForResult(this.getUIContext().getHostContext(), options)
                      .then((data: scanBarcode.ScanResult) => {
                        // Parse the code value and open the specified app service page.
                        hilog.info(0x0001, '[Scan Sample]',
                          `Succeeded in getting ScanResult by promise with options, scanType: ${data.scanType}`);
                      }).catch((err: BusinessError) => {
                      hilog.error(0x0001, '[Scan Sample]',
                        `Failed to get ScanResult by promise with options. Code:${err.code}, message: ${err.message}`);
                    });
                  } catch (err) {
                    hilog.error(0x0001, '[Scan Sample]',
                      `Failed to start the scanning service. Code:${err.code}, message: ${err.message}`);
                  }
                })
            }
            .height('100%')
          }
          .width('100%')
        }
      }
    • Obtain the scanning result using a callback.
      @Entry
      @Component
      struct ScanBarCodePage {
        build() {
          Column() {
            Row() {
              Button('Callback with options')
                .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
                .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
                .align(Alignment.Center)
                .type(ButtonType.Capsule)
                .width('90%')
                .margin({ bottom: 12 })
                .onClick(() => {
                  // Define scanning parameters.
                  const options: scanBarcode.ScanOptions = {
                    scanTypes: [scanCore.ScanType.ALL],
                    enableMultiMode: true,
                    enableAlbum: true
                  };
                  try {
                    // Call the **getHostContext** API to obtain the context associated with the current page.
                    scanBarcode.startScanForResult(this.getUIContext().getHostContext(), options,
                      (err: BusinessError, data: scanBarcode.ScanResult) => {
                        if (err) {
                          hilog.error(0x0001, '[Scan Sample]',
                            `Failed to get ScanResult by callback with options. Code: ${err.code}, message: ${err.message}`);
                          return;
                        }
                        // Parse the code value and open the specified app service page.
                        hilog.info(0x0001, '[Scan Sample]',
                          `Succeeded in getting ScanResult by callback with options, scanType: ${data.scanType}`);
                      });
                  } catch (err) {
                    hilog.error(0x0001, '[Scan Sample]',
                      `Failed to start the scanning service. Code:${err.code}, message: ${err.message}`);
                  }
                })
            }
            .height('100%')
          }
          .width('100%')
        }
      }

Emulator-based Development

Since API version 6.0.0(20), using the Emulator for developing the function of barcode scanning on the default UI is supported. For details, please refer to Running Your App on the Emulator.

On the Emulator, the camera stream on the default scanning UI is flipped horizontally, and black borders will appear at the top and bottom of the scanning UI due to the fixed resolution of the camera stream.