// @/scan.js
|
const timeout = 5 * 1000; //扫码超时时间
|
|
const main = plus.android.runtimeMainActivity();
|
|
// 全局只允许一个地方获取,存储最新的回调函数,获取完立即销毁
|
let scanCallback = null;
|
//存储订阅,每个页面可以单独订阅,优先级低于scanCallback
|
const subscriptions = [];
|
|
export const byteArrayToString = (array) => {
|
return String.fromCharCode.apply(String, array);
|
};
|
|
const sleep = (ms) => {
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
};
|
|
export const registerReceiver = () => {
|
//获取Android意图过滤类
|
const IntentFilter = plus.android.importClass("android.content.IntentFilter");
|
//实例化意图过滤
|
const filter = new IntentFilter();
|
//获取扫码成功的意图广播,
|
filter.addAction("com.rfid.SCAN");
|
const receiver = plus.android.implements(
|
"io.dcloud.feature.internal.reflect.BroadcastReceiver",
|
{
|
onReceive: function (context, intent) {
|
plus.android.importClass(intent);
|
// key 为 厂商提供,需要自己联系厂商获取 ,有的厂商使用getStringExtra就直接可以
|
const dataByte = intent.getByteArrayExtra("data");
|
const code = byteArrayToString(dataByte);
|
console.log("receiver:" + code);
|
if (scanCallback) {
|
scanCallback(code);
|
} else {
|
subscriptions.forEach((cb) => cb(code));
|
}
|
},
|
}
|
);
|
main.registerReceiver(receiver, filter);
|
};
|
|
export const openScan = () => {
|
//获取Android意图类
|
let Intent = plus.android.importClass("android.content.Intent");
|
//实例化意图
|
let intent = new Intent();
|
//定义意图,由厂商提供
|
intent.setAction("com.rfid.SCAN_CMD");
|
//广播这个意图
|
main.sendBroadcast(intent);
|
};
|
|
export const scanCode = async () => {
|
uni.showLoading({ title: "扫描中", mask: true });
|
const getCode = () => {
|
return new Promise((resolve) => {
|
scanCallback = (code) => {
|
resolve(code);
|
};
|
});
|
};
|
openScan();
|
const res = await Promise.race([getCode(), sleep(timeout)]);
|
scanCallback = null;
|
uni.hideLoading();
|
if (!res) {
|
uni.showToast({
|
icon: "none",
|
title: "扫描失败",
|
});
|
throw new Error("扫描失败");
|
}
|
return res;
|
};
|
|
export const addSubscription = (callback) => {
|
if (callback) {
|
subscriptions.push(callback);
|
}
|
};
|
|
export const removeSubscription = (callback) => {
|
const index = subscriptions.findIndex((v) => v === callback);
|
if (index > -1) {
|
subscriptions.splice(index, 1);
|
}
|
};
|