蓝牙搜索用的uni-app的低功耗蓝牙的方法,连接和打印用的安卓原生的方法,连接蓝牙会出现连接不成功的问题(或者连接成功但是连接状态是false)需要额外处理

<!-- 蓝牙打印页面 -->  
<template>  
  <view style="height: 100vh; display: flex; flex-direction: column">  
    <view style="flex: 1; overflow-y: auto; padding-bottom: 20rpx">  
      <button  
        class="button"  
        hover-class="hover"  
        @click="startSearch"  
        :loading="isScanning"  
      >  
        搜索蓝牙设备  
      </button>  
      <text class="td">(Android8.0+系统需开启定位)</text>  
      <view v-if="list.length > 0" style="text-align: center">  
        <view style="font-size: 18px">蓝牙设备列表</view>  
        <view style="color: #666; font-size: 10px">点击连接蓝牙设备</view>  
      </view>  
      <view v-if="deviceinfo.deviceId" class="linkcss"  
        >蓝牙设备已连接:{{ deviceinfo.name }}</view  
      >  
      <scroll-view class="device_list" scroll-y scroll-with-animation>  
        <view  
          :class="item.deviceId === deviceinfo.deviceId ? 'sign_step' : ''"  
          v-for="item in list"  
          :data-title="item.deviceId"  
          :data-name="item.name"  
          :data-advertisData="item.advertisServiceUUIDs"  
          :key="item.deviceId"  
          @click="bindViewTap(item)"  
          class="item"  
          hover-class="item_hover"  
        >  
          <view>  
            <view style="font-size: 16px">{{ item.name }}</view>  
            <view style="font-size: 12px">{{ item.deviceId }}</view>  
            <view style="font-size: 10px; color: #666"  
              >信号强度: {{ item.RSSI }}dBm  
            </view>  
          </view>  
        </view>  
      </scroll-view>  
    </view>  
    <view class="btncss">  
      <u-button  
        :disabled="!deviceinfo.deviceId"  
        :custom-style="{ width: '200rpx' }"  
        type="primary"  
        @click="submitPrinte"  
        >打 印</u-button  
      >  
    </view>  
  </view>  
</template>  

<script>  
function printAlignment(writer, align) {  
  // 对齐方式,0:左,1:中,2:右  
  writer.write(0x1b);  
  writer.write(0x61);  
  writer.write(align);  
  writer.write(0x1b);  
  writer.write(0x45);  
  writer.write(0x00);  
}  
function printFontsize(writer, size) {  
  // 字体大小  
  writer.write(0x1b);  
  writer.write(0x21);  
  writer.write(size);  
  writer.write(0x1b);  
  writer.write(0x45);  
  writer.write(0x00);  
}  
export default {  
  data() {  
    return {  
      list: [],  
      isScanning: false,  
      BLEInformation: {},  
    };  
  },  
  computed: {  
    deviceinfo() {  
      return this.BLEInformation;  
    },  
  },  
  methods: {  
    submitPrinte() {  
      console.log("进入打印方法中");  
      const that = this;  
      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(that.BLEInformation.deviceId);  
      plus.android.importClass(device);  
      var bluetoothSocket =  
        device.createInsecureRfcommSocketToServiceRecord(uuid);  
      plus.android.importClass(bluetoothSocket);  
      if (!bluetoothSocket.isConnected()) {  
        console.log("检测到设备未连接,尝试连接....");  
        bluetoothSocket.connect();  
      }  
      console.log(bluetoothSocket.isConnected());  
      var outputStream = bluetoothSocket.getOutputStream();  
      plus.android.importClass(outputStream);  
      const OutputStreamWriter = plus.android.importClass(  
        "java.io.OutputStreamWriter"  
      );  
      const writer = new OutputStreamWriter(outputStream, "GBK");  
      plus.android.importClass(writer);  

      writer.write("\r\n"); //打印空行并换行  
      writer.write("\r\n"); //打印空行并换行  
      //标题  
      writer.write("标题:打印测试\r\n");  
      printFontsize(writer, 14); // 设置字体14  
      printAlignment(writer, 1); // 设置居中  
      writer.write("打印居中14号字体\r\n");  

      printFontsize(writer, 16); // 设置字体14  
      printAlignment(writer, 0); // 设置居中  
      writer.write("打印居左16号字体\r\n");  

      printAlignment(writer, 2); // 设置居中  
      writer.write("打印居右16号字体\r\n");  
      writer.write("\r\n"); //打印空行并换行  
      // 二维码打印——start  
      const qrcode = "二维码内容放在这里了";  
      var moduleSize = 8;  
      var qrcodebytes = plus.android.invoke(qrcode, "getBytes", "gbk");  
      var length = qrcodebytes.length;  
      writer.write(0x1b);  
      writer.write(0x40);  
      writer.flush();  
      printAlignment(writer, 1);  
      // 缓存二维码数据  
      writer.write(0x1d); // init  
      writer.write("(k"); // adjust height of barcode  
      writer.write(length + 3); // pl  
      writer.write(0); // ph  
      writer.write(49); // cn  
      writer.write(80); // fn  
      writer.write(48); //  
      writer.write(qrcode);  
      // 二维码纠错等级  
      writer.write(0x1d);  
      writer.write("(k");  
      writer.write(3);  
      writer.write(0);  
      writer.write(49);  
      writer.write(69);  
      writer.write(48);  
      // 设置二维码块大小  
      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); // pl  
      writer.write(0); // ph  
      writer.write(49); // cn  
      writer.write(81); // fn  
      writer.write(48); // m  

      writer.flush();  
      writer.write(0x1b);  
      writer.write(0x64);  
      writer.write(2); // 行数  
      writer.flush();  
      // 二维码打印——end  
      writer.flush();  
      // device = null; //这里关键  
      // bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误  
    },  
    startSearch() {  
      var that = this;  
      uni.openBluetoothAdapter({  
        success: function (res) {  
          uni.getBluetoothAdapterState({  
            success: function (res) {  
              console.log("openBluetoothAdapter success", res);  
              if (res.available) {  
                if (res.discovering) {  
                } else {  
                  that.getBluetoothDevices();  
                }  
              } else {  
                uni.showModal({  
                  title: "提示",  
                  content: "本机蓝牙不可用",  
                  showCancel: false,  
                });  
              }  
            },  
          });  
        },  
        fail: function (res) {  
          console.log(res);  
          uni.showModal({  
            title: "提示",  
            content: "蓝牙初始化失败,请到设置打开蓝牙",  
            showCancel: false,  
          });  
        },  
      });  
    },  
    getBluetoothDevices() {  
      var that = this;  
      uni.showLoading({  
        title: "正在搜索",  
        icon: "loading",  
      });  
      that.isScanning = true;  
      uni.startBluetoothDevicesDiscovery({  
        success: function (res) {  
          console.log(res);  
          setTimeout(function () {  
            // 不设置延迟获取的servers为空数组  
            uni.getBluetoothDevices({  
              success: function (res) {  
                var devices = [];  
                var num = 0;  
                for (var i = 0; i < res.devices.length; ++i) {  
                  if (  
                    res.devices[i].name != "未知设备"  
                  ) {  
                    devices[num] = res.devices[i];  
                    num++;  
                  }  
                }  
                that.list = devices;  
                that.isScanning = false;  
                uni.hideLoading();  
                uni.stopPullDownRefresh();  
                uni.stopBluetoothDevicesDiscovery({  
                  success: function (res) {  
                    console.log("停止搜索蓝牙");  
                    that.isScanning = false;  
                    uni.hideLoading();  
                  },  
                });  
              },  
            });  
          }, 5000);  
        },  
      });  
    },  
    bindViewTap(item) {  
      var that = this;  
      uni.showLoading({  
        title: "正在连接",  
      });  

      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(item.deviceId);  
      plus.android.importClass(device);  
      var bluetoothSocket =  
        device.createInsecureRfcommSocketToServiceRecord(uuid);  
      plus.android.importClass(bluetoothSocket);  
      bluetoothSocket.connect();  
      console.log("连接:", bluetoothSocket.isConnected());  
      if (bluetoothSocket.isConnected()) {  
        that.openControl();  
        that.BLEInformation.deviceId = item.deviceId;  
        that.BLEInformation.name = item.name;  
        that.$forceUpdate();  
        console.log("that.BLEInformation:", that.BLEInformation);  
      }  
    },  
    openControl() {  
      // 连接成功后打印  
      uni.hideLoading();  
      const that = this;  
      uni.showModal({  
        title: "提示",  
        content: "蓝牙设备连接成功,是否确认打印",  
        success(res) {  
          if (res.confirm) {  
            that.submitPrinte();  
          }  
        },  
      });  
    },  
  },  
};  
</script>  

<style scoped lang="scss">  
.btncss {  
  background-color: white;  
  padding-inline: 20rpx;  
  width: 100%;  
  padding-top: 30rpx;  
  padding-bottom: 50rpx;  
  box-shadow: 2px 2px 4px 4px rgba(223, 223, 223, 0.5);  
  z-index: 9999;  
}  

.linkcss {  
  border: 2px solid #54bec2;  
  padding: 10px;  
  margin: 10px;  
}  

.button {  
  margin-top: 20px;  
  margin-bottom: 20px;  
  width: 70%;  
  background-color: #54bec2;  
  color: white;  
  border-radius: 98rpx;  
  background: bg_red;  
}  

/* 按下变颜色 */  
.hover {  
  background: #dcdcdc;  
}  

.device_list {  
  height: auto;  
  margin-left: 20rpx;  
  margin-right: 20rpx;  
  margin-top: 10px;  
  margin-bottom: 20px;  
  /* border: 1px solid #EEE; */  
  width: auto;  
}  

.td {  
  display: flex;  
  align-items: center;  
  justify-content: center;  
  margin-top: 10px;  
}  
.item {  
  display: block;  
  background-color: white;  
  border-radius: 18rpx;  
  margin-bottom: 16rpx;  
  padding: 8px;  
}  

.item_hover {  
  background-color: rgba(0, 0, 0, 0.1);  
}  

.block {  
  display: block;  
  color: #ffffff;  
  padding: 5px;  
}  

.button::after {  
  border-width: 0px;  
}  

.sign_step > view::after {  
  // 对钩的三角行底色  
  position: absolute;  
  right: 0;  
  top: 0;  
  width: 0;  
  height: 0;  
  content: "";  
  border: 16px solid;  
  border-color: #70cad3 #70cad3 transparent transparent;  
  border-bottom-right-radius: 2px;  
}  

.sign_step {  
  position: relative;  
  border: 2px solid #54bec2;  
}  

.sign_step > view::before {  
  // 对钩样式  
  position: absolute;  
  right: 2px;  
  top: 4px;  
  z-index: 1;  
  width: 10px;  
  height: 5px;  
  content: "";  
  background: transparent;  
  border: 2px solid white;  
  border-top: none;  
  border-right: none;  
  -webkit-transform: rotate(-55deg);  
  -ms-transform: rotate(-55deg);  
  transform: rotate(-55deg);  
}  
</style>  

在这里插入图片描述

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐