Problem
After a barcode is scanned and a code value is obtained on the custom scanning UI, how do I implement the function of continuously scanning barcodes?
Solution
Call rescan to trigger scanning again in start(viewControl, callback) using a callback instead of a promise.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { customScan, scanBarcode } from '@kit.ScanKit';
export function startCustomScan(viewControl: customScan.ViewControl) {
try {
customScan.start(viewControl, (err: BusinessError, data: Array<scanBarcode.ScanResult>) => {
if (err) {
hilog.error(0x0001, '[Scan Sample]',
`Failed to get ScanResult by callback. Code: ${err.code}, message: ${err.message}`);
return;
}
hilog.info(0x0001, '[Scan Sample]',
`Succeeded in getting ScanResult by callback, result length: ${data.length}`);
// Obtain the scanning result from data and process the service.
// ...
try {
// Trigger scanning again if needed. The call will cause the barcode image in the preview image to be detected again. If the recognition is successful, the callback passed to the start API is triggered to return the new barcode scanning result.
customScan.rescan();
} catch (err) {
hilog.error(0x0001, '[Scan Sample]', `Failed to rescan. Code: ${err.code}, message: ${err.message}`);
}
});
} catch (err) {
hilog.error(0x0001, '[Scan Sample]', `Failed to start customScan. Code: ${err.code}, message: ${err.message}`);
}
}