目录

scanBarcode (Barcode Scanning by Default UI)

Module Overview

The scanBarcode module 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 barcode 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.

To help you quickly get started, you are advised to refer to the official sample project.

Since: 4.0.0(10)

Modules to Import

import { scanBarcode } from '@kit.ScanKit';

ScanResult

Scanning result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.0.0(10)

Name Type Read-Only Optional Description
scanType scanCore.ScanType No No

Barcode type.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

originalValue string No No

Barcode recognition result.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

scanCodeRect ScanCodeRect No Yes

Barcode location information.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

Since: 4.1.0(11)

cornerPoints Array<Point> No Yes

Barcode corner location information, which contains the coordinates of the four corner points of the QR code. This parameter is returned only by the decodeImage API.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

Since: 5.0.0(12)

isGS1 boolean No Yes

Indicates whether the barcode image carries Global Standards 1 (GS1) data.

The options are true (yes) and false (no). The default value is false.

Atomic service API: This API can be used in atomic services since API version 6.0.2(22).

Since: 6.0.2(22)

source scanCore.ScanSource No Yes

Scanning result source. This parameter is returned only for the API called when barcodes are scanned using the default UI. This parameter is used to determine whether the scanning result comes from the camera preview stream or an album image, so that different service processing can be performed.

Atomic service API: This API can be used in atomic services since API version 6.0.2(22).

Since: 6.0.2(22)

ScanCodeRect

Barcode location information. When the default UI (startScan and startScanForResult) is used to scan barcodes, the barcode location is not returned.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.1.0(11)

Name Type Read-Only Optional Description
left number No No X coordinate of the upper left corner of the external rectangle of the barcode. The unit is px.
top number No No Y coordinate of the upper left corner of the external rectangle of the barcode. The unit is px.
right number No No X coordinate of the lower right corner of the external rectangle of the barcode. The unit is px.
bottom number No No Y coordinate of the lower right corner of the external rectangle of the barcode. The unit is px.

The unit of the coordinates returned by the custom UI is the same as that of width and height in the input parameter ViewControl.

Point

Point coordinates. The upper left corner of the coordinate system is {0, 0}. This coordinate system is based on the horizontal device direction with the device's charging port on the right.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 5.0.0(12)

Name Type Read-Only Optional Description
x number No No X coordinate, in pixels.
y number No No Y coordinate, in pixels.

ScanOptions

Scanning parameters.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Since: 4.0.0(10)

Name Type Read-Only Optional Description
scanTypes Array<scanCore.ScanType> No Yes

Scan type.

Default value: ALL (all barcode types)

Since API version 6.1.0(23), the title of barcode scanning by default UI can be dynamically displayed based on this parameter.

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 or 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".

enableMultiMode boolean No Yes

Indicates whether to enable multi-code scanning.

Default value: false

- true: yes

- false: no

enableAlbum boolean No Yes

Indicates whether to enable the album.

Default value: true

- true: yes

- false: no

This parameter controls only the album barcode scanning capability using the default UI, and the album barcode scanning capability supports only single barcode recognition.

Example:

import { scanBarcode, scanCore } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Define scanning parameters.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };

function loadPage(uiContext: UIContext) {
  try {
    scanBarcode.startScanForResult(uiContext.getHostContext(), options).then((data: scanBarcode.ScanResult) => {
      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 startScanForResult. Code: ${err.code}, message: ${err.message}`);
  }
}

startScanForResult

startScanForResult(context: common.Context, options?: ScanOptions): Promise<ScanResult>

Calls the barcode scanning using the default UI by setting parameters and obtains the scanning result. This API must be called within the lifecycle of a page or component. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
context common.Context Yes App context.
options ScanOptions No

Scanning parameters.

Default value: Refer to the default value of ScanOptions.

Returns:

Type Description
Promise<ScanResult> Promise used to return the scanning result.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.
1000500002

The user canceled the barcode scanning.

Applicable versions: 5.0.0(12)+

Example:

import { scanBarcode, scanCore } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Define scanning parameters.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };

function loadPage(uiContext: UIContext) {
  try {
    scanBarcode.startScanForResult(uiContext.getHostContext(), options).then((data: scanBarcode.ScanResult) => {
      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 startScanForResult. Code: ${err.code}, message: ${err.message}`);
  }
}

startScanForResult

startScanForResult(context: common.Context, callback: AsyncCallback<ScanResult>): void

Starts barcode scanning using the default UI and returns the scanning result. This API must be called within the lifecycle of a page or component. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
context common.Context Yes App context.
callback AsyncCallback<ScanResult> Yes Callback function. If the scanning is successful, err is undefined and data is the obtained scanning result object ScanResult. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.
1000500002

The user canceled the barcode scanning.

Applicable versions: 5.0.0(12)+

Example:

import { scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Open the barcode scanning UI.
function loadPage(uiContext: UIContext) {
  try {
    scanBarcode.startScanForResult(uiContext.getHostContext(),
      (err: BusinessError, data: scanBarcode.ScanResult) => {
        if (err) {
          hilog.error(0x0001, '[Scan Sample]',
            `Failed to get ScanResult by callback. Code: ${err.code}, message: ${err.message}`);
          return;
        }
        hilog.info(0x0001, '[Scan Sample]',
          `Succeeded in getting ScanResult by callback, scanType: ${data.scanType}`);
      });
  } catch (err) {
    hilog.error(0x0001, '[Scan Sample]',
      `Failed to startScanForResult. Code: ${err.code}, message: ${err.message}`);
  }
}

startScanForResult

startScanForResult(context: common.Context, options: ScanOptions, callback: AsyncCallback<ScanResult>): void

Calls the barcode scanning using the default UI by setting parameters and obtains the scanning result. This API must be called within the lifecycle of a page or component. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 4.1.0(11).

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
context common.Context Yes App context.
options ScanOptions Yes Scanning parameters.
callback AsyncCallback<ScanResult> Yes Callback function. If the scanning is successful, err is undefined and data is the obtained scanning result object ScanResult. Otherwise, err is an error object.

Error Codes

For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1000500001 Internal error.
1000500002

The user canceled the barcode scanning.

Applicable versions: 5.0.0(12)+

Example:

import { scanCore, scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Define scanning parameters.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };

// Open the barcode scanning UI.
function loadPage(uiContext: UIContext) {
  try {
    scanBarcode.startScanForResult(uiContext.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;
        }
        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 startScanForResult. Code: ${err.code}, message: ${err.message}`);
  }
}

startScan(deprecated)

startScan(options?: ScanOptions): Promise<ScanResult>

Calls the barcode scanning using the default UI by setting parameters and obtains the scanning result. This API uses a promise to return the result.

Deprecation notice: This API is deprecated since API version 4.1.0(11). You are advised to use startScanForResult instead.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.0.0(10)

Parameters:

Parameter Type Mandatory Description
options ScanOptions No

Parameters for starting barcode scanning.

Default value: Refer to the default value of ScanOptions.

Returns:

Type Description
Promise<ScanResult> Promise used to return the scanning result.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed.

Example:

import { scanCore, scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Set input parameters for starting barcode scanning.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };
try {
  scanBarcode.startScan(options).then((data: scanBarcode.ScanResult) => {
    hilog.info(0x0001, '[Scan Sample]',
      `Succeeded in getting ScanResult by promise with options, scanType: ${data.scanType}`);
  }).catch((err: BusinessError) => {
    // If an error occurs during barcode scanning, print and return the error.
    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 startScan. Code: ${err.code}, message: ${err.message}`);
}

startScan(deprecated)

startScan(callback: AsyncCallback<ScanResult>): void

Starts barcode scanning using the default UI and returns the scanning result. This API uses an asynchronous callback to return the result.

Deprecation notice: This API is deprecated since API version 4.1.0(11). You are advised to use startScanForResult instead.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.0.0(10)

Parameters:

Parameter Type Mandatory Description
callback AsyncCallback<ScanResult> Yes Callback function. If the scanning is successful, err is undefined and data is the obtained scanning result object ScanResult. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example:

import { scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  scanBarcode.startScan((err: BusinessError, data: scanBarcode.ScanResult) => {
    // Callback for errors. If an error occurs during barcode scanning, print and return the error.
    if (err) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to get ScanResult by callback. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    hilog.info(0x0001, '[Scan Sample]',
      `Succeeded in getting ScanResult by callback, scanType: ${data.scanType}`);
  });
} catch (err) {
  hilog.error(0x0001, '[Scan Sample]', `Failed to startScan. Code: ${err.code}, message: ${err.message}`);
}

startScan(deprecated)

startScan(options: ScanOptions, callback: AsyncCallback<ScanResult>): void

Calls the barcode scanning using the default UI by setting parameters and obtains the scanning result. This API uses an asynchronous callback to return the result.

Deprecation notice: This API is deprecated since API version 4.1.0(11). You are advised to use startScanForResult instead.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Multimedia.Scan.ScanBarcode

Device behavior differences: For API version 6.0.2(22) and earlier versions, this API is supported on phones and tablets. For API version 6.1.0(23) and later versions, this API is supported on phones, tablets, and wearables with rear cameras. No response is returned on wearables without rear cameras. You can call the getSupportedCameras API to check whether a wearable has a rear camera.

Since: 4.0.0(10)

Parameters:

Parameter Type Mandatory Description
options ScanOptions Yes Scanning parameters.
callback AsyncCallback<ScanResult> Yes Callback function. If the scanning is successful, err is undefined and data is the obtained scanning result object ScanResult. Otherwise, err is an error object.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example:

import { scanCore, scanBarcode } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

// Set input parameters for starting barcode scanning.
let options: scanBarcode.ScanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true };
try {
  scanBarcode.startScan(options, (err: BusinessError, data: scanBarcode.ScanResult) => {
    // Callback for errors. If an error occurs during barcode scanning, print and return the error.
    if (err) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to get ScanResult by callback with options. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    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 startScan. Code: ${err.code}, message: ${err.message}`);
}