| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 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<scanBarcode.ScanResult>, err?: Error) => void): boolean {
- if (this.isAuthorization) {
- try {
- customScan.start(this.viewControl).then((scanResult: Array<scanBarcode.ScanResult>) => {
- 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()
- })
- }
- }
|