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
          })
        })
    })
相关推荐
Hstar_chen7 小时前
开源一款 HarmonyOS 服务器监控客户端:星辰云巡 1.0.3
服务器·华为·harmonyos
2501_9197490314 小时前
华为鸿蒙免费视频播放器APP—小羊免费播放器
华为·harmonyos·鸿蒙
2501_9197490316 小时前
华为鸿蒙免费背书背课文背稿子APP—小羊背诵
华为·harmonyos·鸿蒙
OH_TPC16 小时前
HarmonyOS APP开发---"随手画"白板涂鸦App,需要用到这个库
harmonyos
lilian23317 小时前
HarmonyOS 7 新特性(二十六)|LazyLayoutAlgorithm 自定义懒布局
华为·harmonyos
lilian23318 小时前
HarmonyOS 7 新特性(二十九)|游戏伴随服务:悬浮协作与质量降级
游戏·语音识别·harmonyos
王二蛋与他的张大花19 小时前
让小艺替我回答“还有多久下班“——摸鱼鸭的 HarmonyOS 7 Skill 接入实战
harmonyos
hunterandroid19 小时前
[鸿蒙从零到一] HarmonyOS 冷启动瀑布图分析与关键路径裁剪实战
前端·华为
用户09340777351419 小时前
HarmonyOS WPS Open SDK 实践:把水印与修订收成打开策略层
android·typescript·harmonyos
Veer Han21 小时前
DevEco CLI 实战:鸿蒙 App「宝贝日程表」从 0 开发到正式上架
华为·harmonyos