scan-code.vue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. },
  43. keyUp(e){
  44. const len = e.timeStamp - this.sPtime
  45. this.sPtime = 0
  46. this.$emit('onKey',this.keys[e.key],e)
  47. },
  48. initScan() {
  49. let _this = this;
  50. /* #ifdef APP-PLUS */
  51. this.activity = plus.android.runtimeMainActivity(); //获取activity
  52. var context = plus.android.importClass('android.content.Context'); //上下文
  53. var IntentFilter = plus.android.importClass('android.content.IntentFilter');
  54. this.intentFilter = new IntentFilter();
  55. this.intentFilter.addAction('nlscan.action.SCANNER_RESULT') // 换你的广播动作
  56. this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
  57. onReceive: function(context, intent) {
  58. console.log("intent",intent)
  59. plus.android.importClass(intent);
  60. let content = intent.getStringExtra('SCAN_BARCODE1'); // 换你的广播标签
  61. uni.$emit('scancodedate', content)
  62. }
  63. });
  64. /* #endif */
  65. },
  66. startScan() {
  67. /* #ifdef APP-PLUS */
  68. this.activity.registerReceiver(this.receiver, this.intentFilter);
  69. /* #endif */
  70. },
  71. stopScan() {
  72. /* #ifdef APP-PLUS */
  73. this.activity.unregisterReceiver(this.receiver);
  74. /* #endif */
  75. }
  76. }
  77. }
  78. </script>
  79. <style>
  80. </style>