import { BusinessError } from '@kit.BasicServicesKit'; import { customScan, scanBarcode, scanCore } from '@kit.ScanKit'; import { permissionController } from './PermissionControl'; import { YTLog } from '../../../../Index'; interface ScanCodeUtilInterface { viewControl: customScan.ViewControl scanOptions?: scanBarcode.ScanOptions } export class ScanCodeUtil { private viewControl: customScan.ViewControl private scanOptions: scanBarcode.ScanOptions private isAuthorization: boolean = false constructor(options: ScanCodeUtilInterface) { this.viewControl = options.viewControl if (options.scanOptions) { this.scanOptions = options.scanOptions } else { this.scanOptions = { scanTypes: [scanCore.ScanType.ALL], enableMultiMode: true, enableAlbum: true } } this.initCustomScan() } initCustomScan() { try { if (permissionController.checkPermission('ohos.permission.CAMERA')) { customScan.init(this.scanOptions); this.isAuthorization = true } else { permissionController.secondAskPermission((isAuthorization) => { this.isAuthorization = isAuthorization }) } } catch (error) { YTLog.error(error); } } // customScan.ViewControl = { // width: this.cameraWidth, // height: this.cameraHeight, // surfaceId: surfaceId // }; startCustomScan(result: (res?: Array, err?: Error) => void): boolean { if (this.isAuthorization) { try { customScan.start(this.viewControl).then((scanResult: Array) => { YTLog.info(scanResult) result(scanResult) }).catch((error: BusinessError) => { result(undefined, error) YTLog.error(`Code: ${error.code}, message: ${error.message}`) }) } catch (error) { result(undefined, error) YTLog.error(`Code: ${error.code}, message: ${error.message}`) } } else { result(undefined, new Error('用户未授权相机权限')) YTLog.error('用户未授权相机权限') } return this.isAuthorization } //在不需要时需要及时释放相机资源 stopAndReleaseCustomScan() { customScan.stop() .then(() => { customScan.release() }) } }