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
          })
        })
    })
相关推荐
Lanren的编程日记1 天前
Flutter鸿蒙应用开发:生物识别(指纹/面容)功能集成实战
flutter·华为·harmonyos
Lanren的编程日记1 天前
Flutter鸿蒙应用开发:基础UI组件库设计与实现实战
flutter·ui·harmonyos
chenbin___1 天前
鸿蒙(HarmonyOS)支持 useNativeDriver的详细说明(转自千问)
前端·javascript·react native·react.js·harmonyos
Georgewu1 天前
【鸿蒙基础入门】概念理解和学习方法论说明
harmonyos
Georgewu1 天前
【鸿蒙基础入门】HarmonyOS开发环境IDE和AI编程助手安装配置和默认项目讲解
harmonyos
木斯佳1 天前
HarmonyOS 6实战:从视频编解码到渲染过程,一文了解鸿蒙音视频数据流向
harmonyos
一条咸鱼¥¥¥1 天前
【运维笔记】华为防火墙远程接入用户开通与禁用方法
运维·网络·华为·远程用户
云_杰1 天前
手把手教你玩转HDS沉浸光感效果
华为·harmonyos·ui kit
HwJack201 天前
HarmonyOS 开发终结“盲盒式”调试:用 hiAppEvent 的 Watcher 接口拿捏应用行为监控
华为·harmonyos