HarmonyOS开发拉取摄像头扫码功能组件封装

7 阅读1分钟

1.组件自定义(默认界面扫码)


import { scanCore, scanBarcode } from '@kit.ScanKit';
// 导入默认界面需要的日志模块和错误码模块
import Logger from './Logger';
import { BusinessError } from '@kit.BasicServicesKit';
import promptAction from '@ohos.promptAction'
import common from '@ohos.app.ability.common';
let context: common.Context;
const TAG = '[Scan]';

export  class  Scan{

   // 获取扫码结果
  public  static  getScanResult(callBack:Function){
    // 定义扫码参数options
    let options: scanBarcode.ScanOptions = {
      scanTypes: [scanCore.ScanType.ALL],
      enableMultiMode: true,
      enableAlbum: true
    };
    try {
      scanBarcode.startScanForResult(getContext(context), options).then((result: scanBarcode.ScanResult) => {
        // 收到扫码结果后返回
        Logger.info(TAG,JSON.stringify(result));
        callBack(result.originalValue)
      }).catch((error: BusinessError) => {
        promptAction.showToast({
          message: '未扫描到二维码',
          duration: 2000,
          bottom:400
        });
        Logger.info(TAG,JSON.stringify(error));
      });
    } catch (error) {
         promptAction.showToast({
              message: '未扫描到二维码',
           duration: 2000,
           bottom:400
         });
         Logger.info(TAG,JSON.stringify(error));
    }
  }


}

2.组件使用

引入组件

import { Scan } from "@ohos/utils" ;


/* 接收二维码信息,调用自定义方法处理二维码后续逻辑*/
Scan.getScanResult(handleQRCode);



handleQRCode(scanInfo: String) {
  对二维码进行判断处理
if(scanInfo.indexOf('域名')!=-1){
  let codeTemp = scanInfo.trim().replace('\n', '').split('/')
  后续逻辑处理
}else{
  promptAction.showToast({
    message:   `不是公司设备
    当前二维码内容为:`+scanInfo,
    duration: 2000,
    bottom:400
  });
}
}