ScanCode.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <view class="content"></view>
  3. </template>
  4. <script>
  5. var main, receiver, filter
  6. export default {
  7. props: ['model'],
  8. data () {
  9. return {
  10. scanCode: '',
  11. _codeQueryTag: false
  12. }
  13. },
  14. created: function (option) {
  15. console.log('created')
  16. if (uni.getSystemInfoSync().platform == 'android') {
  17. this.initScan()
  18. this.startScan()
  19. }
  20. },
  21. activated () {
  22. if (uni.getSystemInfoSync().platform == 'android') {
  23. this.initScan()
  24. this.startScan()
  25. }
  26. },
  27. onHide: function () {
  28. if (uni.getSystemInfoSync().platform == 'android') {
  29. this.stopScan()
  30. }
  31. },
  32. onUnload: function () {
  33. if (uni.getSystemInfoSync().platform == 'android') {
  34. this.stopScan()
  35. }
  36. },
  37. deactivated: function () {
  38. console.log('组件卸载')
  39. /*页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果*/
  40. if (uni.getSystemInfoSync().platform == 'android') {
  41. this.stopScan()
  42. }
  43. },
  44. methods: {
  45. initScan () {
  46. console.log('---------------------initScan---------')
  47. let _this = this
  48. main = plus.android.runtimeMainActivity() //获取activity
  49. var IntentFilter = plus.android.importClass(
  50. 'android.content.IntentFilter'
  51. )
  52. filter = new IntentFilter()
  53. filter.addAction('com.android.serial.BARCODEPORT_RECEIVEDDATA_ACTION') // 换你的广播动作
  54. receiver = plus.android.implements(
  55. 'io.dcloud.feature.internal.reflect.BroadcastReceiver',
  56. {
  57. onReceive: function (context, intent) {
  58. plus.android.importClass(intent)
  59. let code = intent.getStringExtra('DATA') // 换你的广播标签
  60. _this.queryCode(code)
  61. }
  62. }
  63. )
  64. },
  65. startScan () {
  66. main.registerReceiver(receiver, filter)
  67. },
  68. stopScan () {
  69. main.unregisterReceiver(receiver)
  70. },
  71. queryCode: function (code) {
  72. //防重复
  73. const _this = this
  74. if (_this._codeQueryTag) return false
  75. _this._codeQueryTag = true
  76. setTimeout(function () {
  77. _this._codeQueryTag = false
  78. }, 150)
  79. var id = code
  80. let par = {
  81. code: id
  82. }
  83. if (this.model == 'uni') {
  84. uni.$emit('scancodedate', par)
  85. } else {
  86. _this.$emit('scancodedate', par)
  87. }
  88. }
  89. }
  90. }
  91. </script>