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
          })
        })
    })
相关推荐
HarmonyOS_SDK1 小时前
HarmonyOS免密认证方案 助力应用登录安全升级
harmonyos
zhanshuo3 小时前
鸿蒙操作系统核心特性解析:从分布式架构到高效开发的全景技术图谱
harmonyos
塞尔维亚大汉3 小时前
鸿蒙内核源码分析(编译过程篇) | 简单案例窥视编译全过程
源码·harmonyos
别说我什么都不会3 小时前
【OpenHarmony】鸿蒙开发之ohos_beacon_library
harmonyos
瑶光守护者4 小时前
【卫星通信】超低比特率语音编解码器(ULBC)的信道特性评估
深度学习·华为·卫星通信·3gpp·ulbc
不凡的凡10 小时前
鸿蒙图片相似性对比
华为·harmonyos
Georgewu11 小时前
【HarmonyOS】HAR和HSP循环依赖和依赖传递问题详解
harmonyos
Georgewu9 天前
【HarmonyOS 5】鸿蒙跨平台开发方案详解(一)
flutter·harmonyos
yenggd10 天前
动态ds-vnp之normal和shortcut两种方式配置案例
网络·华为
Jackilina_Stone10 天前
【网工】华为配置专题进阶篇⑤
网络·华为·网工