scan-code.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <template>
  2. <view class="content">
  3. <keyboard-listener @keydown="keyDown" @keyup="keyUp"></keyboard-listener>
  4. </view>
  5. </template>
  6. <script>
  7. import keyboardListener from 'uniapp-keyboard-listener'
  8. export default {
  9. components: {
  10. keyboardListener
  11. },
  12. data() {
  13. return {
  14. activity: null,
  15. receiver: null,
  16. intentFilter: null,
  17. sPtime: 0,
  18. keys:{
  19. 'TVNetwork': 'leftKey',
  20. 'TVAntennaCable': 'rightKey',
  21. 'TVSatelliteToggle': 'midKey'
  22. }
  23. }
  24. },
  25. created: function(option) {
  26. this.initScan()
  27. this.startScan();
  28. },
  29. onHide: function() {
  30. this.stopScan();
  31. },
  32. destroyed: function() {
  33. //页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果/
  34. this.stopScan();
  35. this.sPtime = 0
  36. },
  37. methods: {
  38. keyDown(e){
  39. if(!this.sPtime){
  40. this.sPtime = e.timeStamp
  41. }
  42. this.$emit('onKeyDown',this.keys[e.key]||e.key,e)
  43. },
  44. keyUp(e){
  45. const len = e.timeStamp - this.sPtime
  46. this.sPtime = 0
  47. this.$emit('onKeyUp',this.keys[e.key]||e.key,e)
  48. },
  49. initScan() {
  50. let _this = this;
  51. /* #ifdef APP-PLUS */
  52. this.activity = plus.android.runtimeMainActivity(); //获取activity
  53. var context = plus.android.importClass('android.content.Context'); //上下文
  54. var IntentFilter = plus.android.importClass('android.content.IntentFilter');
  55. this.intentFilter = new IntentFilter();
  56. this.intentFilter.addAction('nlscan.action.SCANNER_RESULT') // 换你的广播动作
  57. this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
  58. onReceive: function(context, intent) {
  59. console.log("intent",intent)
  60. plus.android.importClass(intent);
  61. let content = intent.getStringExtra('SCAN_BARCODE1'); // 换你的广播标签
  62. uni.$emit('scancodedate', content)
  63. }
  64. });
  65. /* #endif */
  66. },
  67. startScan() {
  68. /* #ifdef APP-PLUS */
  69. this.activity.registerReceiver(this.receiver, this.intentFilter);
  70. /* #endif */
  71. },
  72. stopScan() {
  73. /* #ifdef APP-PLUS */
  74. this.activity.unregisterReceiver(this.receiver);
  75. /* #endif */
  76. }
  77. }
  78. }
  79. </script>
  80. <style>
  81. </style>