HarmonyOS Next鸿蒙扫一扫功能实现

直接使用的是华为官方提供的api,封装成一个工具类方便调用。

TypeScript 复制代码
import { common } from '@kit.AbilityKit';
import { scanBarcode, scanCore } from '@kit.ScanKit';


export namespace ScanUtil {
  export async function startScan(context: common.Context) : Promise<string> {
    if (canIUse('SystemCapability.Multimedia.Scan.Core')) {
      // 定义扫码参数options
      let options: scanBarcode.ScanOptions = {
        scanTypes: [scanCore.ScanType.ALL],
        enableMultiMode: true,
        enableAlbum: true
      };

      if (canIUse('SystemCapability.Multimedia.Scan.ScanBarcode')) {
        let result: scanBarcode.ScanResult = await scanBarcode.startScanForResult(context, options)
        return result.originalValue
      }
    }
    throw new Error('该设备不支持扫码功能')
  }
}

使用方法:

TypeScript 复制代码
Button('打开扫一扫')
    .onClick(()=>{
      ScanUtil.startScan(getContext())
        .then((result)=>{
          //成功识别到二维码内容
          promptAction.showToast({
            message: `result:${result}`,
            duration: 3000
          })
        })
        .catch((error:BusinessError)=>{
          //一般是模拟器会跑到这里报异常
          promptAction.showToast({
            message: `error:${error}`,
            duration: 3000
          })
        })
    })
相关推荐
弓.长.10 分钟前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-svg(CAPI) — 矢量图形组件
react native·react.js·harmonyos
不爱吃糖的程序媛11 分钟前
鸿蒙三方库适配HPKCHECK 文件执行流程详解
华为·harmonyos
见山是山-见水是水19 分钟前
Flutter 框架跨平台鸿蒙开发 - 电子发票智能管理
flutter·华为·harmonyos
HarmonyOS_SDK29 分钟前
化繁为简:顺丰速运App如何通过 HarmonyOS SDK实现专业级空间测量
harmonyos
不爱吃糖的程序媛1 小时前
鸿蒙三方库适配读懂 `HPKBUILD`:lycium 怎么知道「下载谁、怎么编、装到哪」?
服务器·华为·harmonyos
李游Leo1 小时前
别让压图拖垮首帧:系统 Picker + TaskPool + ImagePacker,把 HarmonyOS 图片整理链路做顺
harmonyos
2401_839633912 小时前
鸿蒙flutter第三方库适配 - 存储空间分析
flutter·华为·harmonyos
加农炮手Jinx2 小时前
Flutter 三方库 better_commit 的鸿蒙化适配指南 - 实现具备语义化提交规范与自动化交互的 Git 工作流插件、支持端侧版本工程的高效规范化审计实战
flutter·harmonyos·鸿蒙·openharmony·better_commit
麒麟ZHAO2 小时前
鸿蒙flutter第三方库适配 - 文件搜索工具
flutter·华为·harmonyos
云和数据.ChenGuang2 小时前
鸿蒙6的**星盾安全(StarShield)技术
安全·华为·harmonyos