直接在onload执行下列代码
javascript
var main = plus.android.runtimeMainActivity(); //获取activity
var context = plus.android.importClass('android.content.Context'); //上下文
var receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: doReceive
});
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
var Intent = plus.android.importClass('android.content.Intent');
var filter = new IntentFilter();
filter.addAction('com.action.SCAN_RESULT'); // 添加广播动作名称 注意(这里要更换为你自己的需要问厂商)
main.registerReceiver(receiver, filter); //注册监听
function doReceive(context, intent) {
//通过intent实例引入intent类,方便以后的'.'操作
plus.android.importClass(intent);
// =======================注意:这里要更换为你自己的 下文scanContext 和 length要更换为自己的 需要问厂商
//条码内容
var barcodeBytes = intent.getByteArrayExtra('scanContext');
var barcode = byteToString(barcodeBytes);
//条码长度
var barcodeLength = intent.getIntExtra('length', 0);
console.log('length', barcodeLength);
//条码类型
var barcodeTypeBytes = intent.getByteExtra('barcodeType', 0 | 0);
var barcodeType = byteToString(barcodeTypeBytes);
console.log('结果:', barcode);
// 结果:, Amb:25.91ᄀ₩,Object:23.71ᄀ₩,Body:35.00ᄀ₩
// main.unregisterReceiver(receiver); //取消监听 在合适的时机调用
}
function byteToString(arr) {
if (typeof arr === 'string') {
return arr;
}
var str = '',
_arr = arr;
for (var i = 0; i < _arr.length; i++) {
var one = _arr[i].toString(2),
v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var bytesLength = v[0].length;
var store = _arr[i].toString(2).slice(7 - bytesLength);
for (var st = 1; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2);
}
str += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
} else {
str += String.fromCharCode(_arr[i]);
}
}
return str;
}