ke_junjie
2025-06-04 4bf0783db564f0d446c74d7b42242aff879b894c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<template>
    <view class="content"></view>
</template>
 
<script>
    var main, receiver, filter;
    var _codeQueryTag = false;
    export default {
        data() {
            return {
                scanCode: ''
            }
        },
        created: function(option) {
            this.initScan()
            this.startScan();
        },
        onHide: function() {
            this.stopScan();
        },
        destroyed: function() {
            this.stopScan();
        },
        methods: {
            initScan() {
                let _this = this;
                main = plus.android.runtimeMainActivity();
                var IntentFilter = plus.android.importClass('android.content.IntentFilter');
                filter = new IntentFilter();
                //下面的addAction内改为自己的广播动作
                filter.addAction("com.android.serial.BARCODEPORT_RECEIVEDDATA_ACTION");
                receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
                    onReceive: function(context, intent) {
                        plus.android.importClass(intent);
                        //下面的getStringExtra内改为自己的广播标签
                        let code = intent.getStringExtra("DATA");
                        _this.queryCode(code);
                    }
                });
            },
            startScan() {
                main.registerReceiver(receiver, filter);
            },
            stopScan() {
                main.unregisterReceiver(receiver);
            },
            queryCode: function(code) {
                if (_codeQueryTag) return false;
                _codeQueryTag = true;
                setTimeout(function() {
                    _codeQueryTag = false;
                }, 150);
                var id = code
                console.log('id:', id)
                uni.$emit('scan', {
                    code: id
                })
            }
        }
    }
</script>