uni-app Android广播扫码
将广播相关代码封装成class插件
// 广播动作
const scanAction = 'com.android.server.scannerservice.broadcast';
// 广播标签
const scanExtra = 'scannerdata';
class Broadcast {
constructor(obj) {
this.action = scanAction;
this.extra = scanExtra;
this.plus = obj.plus;
this.main = this.plus.android.runtimeMainActivity();
const IntentFilter = this.plus.android.importClass('android.content.IntentFilter');
this.filter = new IntentFilter();
this.receiver = null;
this.initScan();
}
// 初始化广播
initScan() {
const _this = this;
this.filter.addAction(this.action);
this.receiver = this.plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{
onReceive: function(context, intent) {
_this.plus.android.importClass(intent);
// 提交事件
uni.$emit('scan-result', intent.getStringExtra(_this.extra));
}});
}
// 开始扫码
startScan() {
if (!this.receiver) {
this.initScan();
}
this.main.registerReceiver(this.receiver, this.filter);
}
// 结束扫码
stopScan() {
this.main.unregisterReceiver(this.receiver);
}
// 清除事件
off() {
uni.$off('scan-result');
}
endScan() {
this.stopScan();
this.off();
}
}
export default Broadcast;
使用方法
methods: {
startScan() {
this.broadcast.startScan();
}
},
onLoad() {
let _this = this;
uni.$on('scan-result', function(code) {
consloe.log(code);
});
this.broadcast = new this.Broadcast({
plus
});
},
onUnload() {
this.broadcast.endScan();
}