scan.vue 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <view class="content"></view>
  3. </template>
  4. <script>
  5. export default {
  6. data() {
  7. return {
  8. activity: null,
  9. receiver: null,
  10. intentFilter: null
  11. }
  12. },
  13. created: function(option) {
  14. this.initScan()
  15. this.startScan();
  16. },
  17. onHide: function() {
  18. this.stopScan();
  19. },
  20. destroyed: function() {
  21. //页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果/
  22. this.stopScan();
  23. },
  24. methods: {
  25. initScan() {
  26. // 非app不执行
  27. if (process.env.UNI_PLATFORM != 'app-plus') {
  28. return true
  29. }
  30. let _this = this;
  31. this.activity = plus.android.runtimeMainActivity(); //获取activity
  32. var IntentFilter = plus.android.importClass('android.content.IntentFilter');
  33. this.intentFilter = new IntentFilter();
  34. this.intentFilter.addAction('android.intent.ACTION_DECODE_DATA') // 换你的广播动作
  35. this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
  36. onReceive: function(context, intent) {
  37. plus.android.importClass(intent);
  38. let content = intent.getStringExtra('barcode_string'); // 换你的广播标签
  39. uni.$emit('scancode', content)
  40. }
  41. });
  42. },
  43. startScan() {
  44. // 非app不执行
  45. if (process.env.UNI_PLATFORM != 'app-plus') {
  46. return true
  47. }
  48. this.activity.registerReceiver(this.receiver, this.intentFilter);
  49. },
  50. stopScan() {
  51. // 非app不执行
  52. if (process.env.UNI_PLATFORM != 'app-plus') {
  53. return true
  54. }
  55. this.activity.unregisterReceiver(this.receiver);
  56. }
  57. }
  58. }
  59. </script>
  60. <style>
  61. </style>