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
          })
        })
    })
相关推荐
承渊政道7 分钟前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端
忆凡_14 分钟前
Dyad 鸿蒙 PC 适配全记录:让本地 AI 应用构建器进入 HarmonyOS PC
electron·鸿蒙
网络豆33 分钟前
Apache Hive 鸿蒙 PC 适配全记录:以 Qt 客户端打通 HiveQL、监控与元数据访问
hive·apache·harmonyos
网络豆1 小时前
Apache HBase 鸿蒙 PC 适配全记录:用 Qt 原生客户端打通 REST 管理与数据读写
apache·hbase·harmonyos
hacker7072 小时前
bolt.diy 鸿蒙 PC 适配全记录:让 AI 全栈开发工作台在 HarmonyOS PC 上真正跑起来
人工智能·华为·harmonyos
●VON3 小时前
Flutter 鸿蒙插件适配实战:用 locale_plus 2.0.0 读取语言、地区与格式偏好
flutter·华为·harmonyos·鸿蒙
贾伟康12 小时前
【HarmonyOS 7新能力|008】互动卡片入门实战:从能力边界到最小可运行链路
harmonyos·arkts·arkui·harmonyos 7·互动卡片
●VON12 小时前
Flutter 鸿蒙插件适配实战:用 clipboard_watcher 0.3.0 监听剪贴板变化
flutter·华为·harmonyos
昇腾知识体系14 小时前
CANN 安装升级避坑:version.cfg 查版本、银河麒麟找不到驱动、nnrt --version 无输出排查
人工智能·华为·知识图谱