1
hao
2025-03-27 e610e1c17f62b423a717fadaaa7b139d02857793
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<template>
  <view class="bluetooth-printer">
    <button @click="connectPrinter">连接蓝牙打印机</button>
    <button @click="printTest">打印测试页</button>
    <text>{{ connectionStatus }}</text>
  </view>
</template>
 
<script>
export default {
  props: ['printCmd'],  // 从父组件传入的打印命令
  data() {
    return {
      bluetoothSocket: null,
      connectionStatus: '未连接'
    };
  },
  methods: {
    initBluetooth() {
      try {
        this.bluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");
        plus.ui.toast("初始化蓝牙成功");
      } catch (e) {
        plus.ui.toast("初始化蓝牙失败:" + e);
      }
    },
    connectPrinter() {
      try {
        if (this.bluetoothSocket && !this.bluetoothSocket.isConnected()) {
          this.bluetoothSocket.connect();
          this.connectionStatus = "蓝牙打印机已连接";
          plus.ui.toast("打印机连接成功");
        } else {
          this.connectionStatus = "打印机已连接或连接中";
        }
      } catch (e) {
        this.connectionStatus = "连接失败";
        plus.ui.toast("连接失败:" + e);
      }
    },
    sendPrintCommand(cmd) {
      try {
        if (!this.bluetoothSocket || !this.bluetoothSocket.isConnected()) {
          plus.ui.toast("请先连接打印机");
          return;
        }
 
        const outputStream = this.bluetoothSocket.getOutputStream();
        plus.android.importClass(outputStream);
        const arrayBuffer = plus.android.invoke(cmd, "getBytes", "gbk");
        outputStream.write(arrayBuffer);
        outputStream.flush();
        plus.ui.toast("打印命令发送成功");
      } catch (e) {
        plus.ui.toast("打印命令发送失败:" + e);
      }
    },
    print() {
      if (this.printCmd) {
        this.sendPrintCommand(this.printCmd);
      }
    },
    printTest() {
      const testCmd = "! 0 203 203 490 1\r\nTEXT 24 0 100 100 测试打印\r\nPRINT\r\n";
      this.sendPrintCommand(testCmd);
    }
  },
  mounted() {
    this.initBluetooth();
    this.connectPrinter();
    this.print();  // 自动执行传入的打印命令
  }
};
</script>
 
<style>
  /* 样式省略 */
</style>