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
          })
        })
    })
相关推荐
爱笑的眼睛118 小时前
HarmonyOS 应用开发深入浅出:基于 Stage 模型与声明式 UI 的现代化状态管理实践
华为·harmonyos
爱笑的眼睛119 小时前
HarmonyOS 应用开发深度解析:掌握 ArkTS 声明式 UI 与现代化状态管理
华为·harmonyos
爱笑的眼睛119 小时前
HarmonyOS 应用开发深度解析:基于 ArkTS 的跨组件状态管理最佳实践
华为·harmonyos
前端世界9 小时前
鸿蒙系统下的智能设备故障检测实战:从监控到自愈的全流程实现
华为·harmonyos
2501_919749039 小时前
flutter鸿蒙:使用flutter_local_notifications实现本地通知
flutter·华为·harmonyos
Georgewu19 小时前
【HarmonyOS 6】 The target can not be empty. check the build.profile,json5 file of
harmonyos
Georgewu19 小时前
【HarmonyOS 6】Install Failed: error: failed to install bundle.code:9568322
harmonyos
爱笑的眼睛1121 小时前
HarmonyOS 应用开发新范式:深入剖析 Stage 模型与 ArkTS 状态管理
华为·harmonyos
爱笑的眼睛111 天前
深入浅出 HarmonyOS ArkUI 3.0:基于声明式开发范式与高级状态管理构建高性能应用
华为·harmonyos
电手1 天前
时隔4年麒麟重新登场!华为这8.8英寸新「手机」给我看麻了
华为·智能手机