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 分钟前
HarmonyOS 7 空间重建实战:3DGS 端侧重建从建模到商品展示
harmonyos·arkts
jiao0000130 分钟前
【鸿蒙实战】从零撸一个「华为商城」App
华为·harmonyos·arkts
梦想不只是梦与想1 小时前
鸿蒙 AppTest邀请测试
鸿蒙·邀请测试·apptest 邀请测试
李游Leo9 小时前
HarmonyOS 7 端侧 AI 视觉能力实战 04:给图片增加人脸检测能力
harmonyos
ChinaDragon10 小时前
HarmonyOS:应用程序包管理模块(获取当前应用信息)
harmonyos
Latte Moments开发11 小时前
Harmony鸿蒙实战开发-事件提醒app「事件名称/描述、提醒日期、提醒时长、延迟提醒次数、延迟提醒事件间隔」➕⏰声音【源码在文末】
华为·harmonyos
星栖与芯11 小时前
LiteOS-M 切换汇编逐行图解(2):指令·异常机制·全景表
stm32·单片机·嵌入式硬件·harmonyos·鸿蒙系统
OH_TPC12 小时前
【鸿蒙优选三方库】@react-native-ohos/react-native-svg:SVG 矢量图形渲染组件
华为·harmonyos·鸿蒙
李游Leo14 小时前
HarmonyOS 7 实战开发 01:搭建内容工作台基础框架
harmonyos