zkcPDA手持终端机5502型号打印功能实现
记录一下uniapp开发安卓终端设备遇到的坑,也给和我同样经历着前端开发安卓设备的工友提供一点点帮助
<div id="btnPrint" type="button" value="打印" @click="print('00:11:22:33:44:55')">打印</div>
print(mac_address) {if (!mac_address) {mui.toast('请选择蓝牙打印机');return;}var main = plus.android.runtimeMainActivity();var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");var UUID = plus.android.importClass("java.util.UUID");var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");var BAdapter = BluetoothAdapter.getDefaultAdapter();var device = BAdapter.getRemoteDevice(mac_address);plus.android.importClass(device);var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);plus.android.importClass(bluetoothSocket);if (!bluetoothSocket.isConnected()) {console.log('检测到设备未连接,尝试连接....');bluetoothSocket.connect(); //连接蓝牙}console.log('设备已连接');if (bluetoothSocket.isConnected()) { //判断是否连接设备蓝牙var outputStream = bluetoothSocket.getOutputStream(); //返回一个指向服务器端的数据plus.android.importClass(outputStream); //importClass导入Java类对象var OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')var writer = new OutputStreamWriter(outputStream, 'GBK')plus.android.importClass(writer)var byteStr = '101013Q73898'var moduleSize = 15var bytes = plus.android.invoke(byteStr, 'getBytes', 'gbk')var length = bytes.length// 缓存二维码数据writer.write(0x1D) // initwriter.write('(k') // adjust height of barcodewriter.write(length + 3) // plwriter.write(0) // phwriter.write(49) // cnwriter.write(80) // fnwriter.write(48) //writer.write(byteStr)// 二维码纠错等级// writer.write(0x1D)// writer.write('(k')// writer.write(3)// writer.write(0)// writer.write(49)// writer.write(69)// writer.write(90)// // 设置二维码块大小writer.write(0x1D)writer.write('(k')writer.write(3)writer.write(0)writer.write(49)writer.write(67)writer.write(moduleSize)// 打印已缓存的数据二维码writer.write(0x1D)writer.write('(k')writer.write(3) // plwriter.write(0) // phwriter.write(49) // cnwriter.write(81) // fnwriter.write(75) // mwriter.flush()// device = null //这里关键// bluetoothSocket.close();var string = "打印测试\r\n";var bytes = plus.android.invoke(string, 'getBytes', 'gbk'); //invoke调用对象(类对象/实例对象)的方法outputStream.write(bytes);outputStream.flush();// 换行outputStream.write('\n')outputStream.flush()device = null //这里关键bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误}},