scanBarcode (默认界面扫码)

扫描二维码/条形码是许多应用中的常见功能。在 HarmonyOS 中,可以通过 scanBarcode 模块提供的 API 来实现。

步骤

  1. 编写 options 配置参数
  2. scanBarcode.startScanForResult(context,options)打开扫码界面

开启默认界面扫码可以省略 options 参数,直接调用 startScanForResult 方法即可。

// 扫码的配置项
const options: scanBarcode.ScanOptions = {
  scanTypes: [scanCore.ScanType.ALL], //识别的类型 一般识别所有类型
  enableMultiMode: true, //是否支持多图识别
  enableAlbum: false, //是否支持图库
};

// 调用startScanForResult方法开始扫码
scanBarcode
  .startScanForResult(this.context, options)
  .then((result: scanBarcode.ScanResult) => {
    hilog.info(0x0001, "[scan simple]", "success");
    const context: common.UIAbilityContext =
      this.getUIContext().getHostContext() as common.UIAbilityContext;

    // result.originalValue为二维码的内容
    context.openLink(result.originalValue);
  })
  .catch((error: BusinessError) => {
    hilog.error(0x0001, "[scan simple]", `err errcode${error.code}`);
  });

真实案例

import { scanBarcode, scanCore } from '@kit.ScanKit'
import { common } from '@kit.AbilityKit'
import hilog from '@ohos.hilog'

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button("scan code")
        .onClick((event: ClickEvent) => {
          const option:scanBarcode.ScanOptions = {
            scanTypes:[scanCore.ScanType.ALL],
            enableMultiMode:true,
            enableAlbum:true
          }
          const context:common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext
          scanBarcode.startScanForResult(context,option)
            .then((result:scanBarcode.ScanResult)=>{
              context.openLink(result.originalValue)
            })
            .catch((error:BusinessError)=>{
              hilog.error(0x0000,'[scan code err]',`errorcode:${error.code} errorMessage:${error.message}`)
            })
        })
    }
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐