?先创建一个组件 代码复制可用(需要替换广播动作和广播标签)
<template>
<view>
<view class="content"></view>
</view>
</template>
<script>
var main, receiver, filter;
var codeQueryTag = false;
export default {
data() {
return {
scanCode: ''
}
},
created() {
this.initScan()
this.startScan();
},
onHide() {
this.stopScan();
},
destroyed() {
this.stopScan();
},
methods: {
initScan() {
// #ifdef APP
console.log('initScan');
let that = this;
main = plus.android.runtimeMainActivity(); //获取activity
//var context = plus.android.importClass('android.content.Context'); //上下文
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
filter = new IntentFilter();
//下面的addAction内改为自己的广播动作
filter.addAction("com.seuic.idcard");
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: (context, intent)=> {
console.log('onReceive');
plus.android.importClass(intent);
//下面的getStringExtra内改为自己的广播标签--有误
let code = intent.getStringExtra("data");
that.queryCode(code);
}
});
// #endif
},
startScan() {
// #ifdef APP
console.log('startScan');
main.registerReceiver(receiver, filter);
// #endif
},
stopScan() {
// #ifdef APP
console.log('stopScan');
main.unregisterReceiver(receiver);
// #endif
},
queryCode: function(code) {
// #ifdef APP
console.log('queryCode');
if (codeQueryTag) return false;
codeQueryTag = true;
setTimeout(function() {
codeQueryTag = false;
}, 150);
var id = code
uni.$emit('xwscan', {
code: id
})
// #endif
}
}
}
</script>
<style>
</style>
在页面中使用 可根据自己实际场景向第三方app传值
<template>
<view class="content">
扫描结果:{{input}}
<button type="default" @click="scanCode()">扫描</button>
<xw-scan></xw-scan>
</view>
</template>
<script>
import xwScan from '../../components/xw-scan.vue'
export default {
components: {
xwScan
},
data() {
return {
input: ''
}
},
onLoad() {
},
onUnload() {
// 移除监听事件
uni.$off('xwscan')
},
onShow() {
let that = this
uni.$off('xwscan') // 每次进来先 移除全局自定义事件监听器
uni.$on('xwscan', (res) => {
console.log('扫码结果:', res.code);
this.input = res.code
})
},
methods: {
scanCode() {
if (plus.runtime.isApplicationExist({
pname: 'com.seuic.idcard'
})) {
console.log("该app已安装")
//调用第三方app
plus.runtime.launchApplication({
pname: "com.seuic.idcard",
action: "com.seuic.idcard",
extra: {
"hideWindow": true,
} //传递的参数
},
function(e) {
console.log("e", e)
uni.showToast({
title: "打开失败",
icon: "none"
})
},
);
} else {
uni.showToast({
title: "app未安装",
icon: "none"
})
}
},
}
}
</script>
<style>
</style>
|