ScanCodeUtil.ets 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. import { customScan, scanBarcode, scanCore } from '@kit.ScanKit';
  3. import { permissionController } from './PermissionControl';
  4. import { YTLog } from '../../../../Index';
  5. interface ScanCodeUtilInterface {
  6. viewControl: customScan.ViewControl
  7. scanOptions?: scanBarcode.ScanOptions
  8. }
  9. export class ScanCodeUtil {
  10. private viewControl: customScan.ViewControl
  11. private scanOptions: scanBarcode.ScanOptions
  12. private isAuthorization: boolean = false
  13. constructor(options: ScanCodeUtilInterface) {
  14. this.viewControl = options.viewControl
  15. if (options.scanOptions) {
  16. this.scanOptions = options.scanOptions
  17. } else {
  18. this.scanOptions = {
  19. scanTypes: [scanCore.ScanType.ALL],
  20. enableMultiMode: true,
  21. enableAlbum: true
  22. }
  23. }
  24. this.initCustomScan()
  25. }
  26. initCustomScan() {
  27. try {
  28. if (permissionController.checkPermission('ohos.permission.CAMERA')) {
  29. customScan.init(this.scanOptions);
  30. this.isAuthorization = true
  31. } else {
  32. permissionController.secondAskPermission((isAuthorization) => {
  33. this.isAuthorization = isAuthorization
  34. })
  35. }
  36. } catch (error) {
  37. YTLog.error(error);
  38. }
  39. }
  40. // customScan.ViewControl = {
  41. // width: this.cameraWidth,
  42. // height: this.cameraHeight,
  43. // surfaceId: surfaceId
  44. // };
  45. startCustomScan(result: (res?: Array<scanBarcode.ScanResult>, err?: Error) => void): boolean {
  46. if (this.isAuthorization) {
  47. try {
  48. customScan.start(this.viewControl).then((scanResult: Array<scanBarcode.ScanResult>) => {
  49. YTLog.info(scanResult)
  50. result(scanResult)
  51. }).catch((error: BusinessError) => {
  52. result(undefined, error)
  53. YTLog.error(`Code: ${error.code}, message: ${error.message}`)
  54. })
  55. } catch (error) {
  56. result(undefined, error)
  57. YTLog.error(`Code: ${error.code}, message: ${error.message}`)
  58. }
  59. } else {
  60. result(undefined, new Error('用户未授权相机权限'))
  61. YTLog.error('用户未授权相机权限')
  62. }
  63. return this.isAuthorization
  64. }
  65. //在不需要时需要及时释放相机资源
  66. stopAndReleaseCustomScan() {
  67. customScan.stop()
  68. .then(() => {
  69. customScan.release()
  70. })
  71. }
  72. }