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
          })
        })
    })
相关推荐
funnycoffee1231 小时前
Cisco ,H3C,华为配置端口聚合命令(lacp mode)
网络·华为·聚合
ITUnicorn2 小时前
【HarmonyOS 6】进度组件实战:打造精美的数据可视化
华为·harmonyos·arkts·鸿蒙·harmonyos6
小叮当⇔3 小时前
计算机网络实验——华为eNSP模拟器常用命令总结
服务器·计算机网络·华为
松叶似针4 小时前
Flutter三方库适配OpenHarmony【secure_application】— 五平台隐私保护机制横向对比
flutter·harmonyos
平安的平安5 小时前
【OpenHarmony】React Native鸿蒙实战:SegmentControl 分段控件详解
react native·react.js·harmonyos
平安的平安6 小时前
【OpenHarmony】React Native鸿蒙实战:ProgressRing 环形进度详解
react native·react.js·harmonyos
平安的平安6 小时前
【OpenHarmony】React Native鸿蒙实战:ProgressBar 进度条详解
react native·react.js·harmonyos
前端不太难6 小时前
未来的鸿蒙 App,还需要“首页”吗?
华为·状态模式·harmonyos
平安的平安6 小时前
【OpenHarmony】React Native鸿蒙实战:SearchBar 搜索栏详解
react native·react.js·harmonyos
HwJack2015 小时前
HarmonyOS APP UI单位适配深度实践:vp/fp/px的工程化解决方案分享
ui·华为·harmonyos