我使用的uni-app
<template>
<view class="bluetooth">
<!-- 发送数据 -->
<view class="send" v-if="send_data_onoff">
<view class="uni-textarea">
<textarea placeholder-style="color:#F76260" v-model="send_data_list" placeholder="请输入发送数据"/>
<view @tap="send_data" class="fasong">发送</view>
</view>
</view>
<!-- 没有匹配的蓝牙设备 -->
<view class="no_match_bluetooth_list" v-if="no_match_list.length!=0">
<view class="h1">已搜索的蓝牙:</view>
<block v-for="(item,index) in no_match_list" :key="index">
<view class="uni-list" @tap="search_bluetooth(item.SN)">
<view class="uni-list-cell" hover-class="uni-list-cell-hover">
<view class="uni-list-cell-navigate uni-navigate-right uni-media-list ">
<view class="uni-media-list-body">
<view>蓝牙名称:{{item.name}}</view>
<view>SN:{{item.SN}}</view>
</view>
</view>
</view>
</view>
</block>
</view> <!-- 已匹配的蓝牙设备 -->
<view class="no_match_bluetooth_list" v-if="match_list.length!=0">
<view class="h1">已匹配的蓝牙:</view>
<block v-for="(item,index) in match_list" :key="index">
<view class="uni-list" @tap="print(item.SN)">
<view class="uni-list-cell" hover-class="uni-list-cell-hover">
<view class="uni-list-cell-navigate uni-navigate-right uni-media-list ">
<view class="uni-media-list-body">
<view>蓝牙名称:{{item.name}}</view>
<view>SN:{{item.SN}}</view>
</view>
</view>
</view>
</view>
</block>
</view> <view class="btn">
<view class="btn_1" @tap="open_bluetooth">打开蓝牙</view>
<view class="btn_2" @tap="close_bluetooth">关闭蓝牙</view>
<view class="btn_3" @tap="search_bluetooth">搜索蓝牙</view>
</view>
</view>
</template> <script>
var main, Context, BluetoothManager, BluetoothAdapter, BManager, BAdapter,BluetoothDevice,IntentFilter,bluetoothSocket,device;
export default {
data() {
return {
bArray:[],//用于搜索蓝牙去重用的
no_match_list:[],//没有配对的蓝牙列表
match_list:[],//已配对的蓝牙列表
send_data_onoff:false,
send_data_list:'',//要发送的数据
};
},
onShow() {
//获取android应用Activity对象
main = plus.android.runtimeMainActivity();
Context = plus.android.importClass("android.content.Context");
BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
//蓝牙适配器
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
//蓝牙本地适配器
BAdapter = BluetoothAdapter.getDefaultAdapter();
//蓝牙设备
BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice');
//过滤器
IntentFilter = plus.android.importClass('android.content.IntentFilter');
},
methods:{
/**
* 根据蓝牙地址,连接设备
* @param {Object} address
* @return {Boolean}
*/
print(address){
console.log(address)
let that=this
uni.showModal({
title: '提示',
content: '是连接此蓝牙?',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
uni.showLoading({
title: '蓝牙连接中...'
});
that.print_bluetooth(address) }
}
});
},
//连接蓝牙
print_bluetooth(mac_address){
let that=this
uni.hideLoading()
let UUID = plus.android.importClass("java.util.UUID");
let uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
device = BAdapter.getRemoteDevice(mac_address);
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(bluetoothSocket);
if (!bluetoothSocket.isConnected()) {
console.log('检测到设备未连接,尝试连接....');
bluetoothSocket.connect();
}
console.log('设备已连接');
// 打开输入发送数据
that.send_data_onoff=true; },
//发送蓝牙数据
send_data(){
let that=this
console.log()
if (bluetoothSocket.isConnected()) {
console.log()
var outputStream = bluetoothSocket.getOutputStream();
plus.android.importClass(outputStream);
var string = that.send_data_list
var bytes = plus.android.invoke(string, 'getBytes', 'gbk');//创建输出流失败
outputStream.write(bytes);
// outputStream.flush();
// device = null //这里关键
// bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
}
},
open_bluetooth(){
if(!BAdapter.isEnabled()) {
BAdapter.enable();//启动蓝牙
uni.showToast({
title: '蓝牙已启动',
duration:
})
}
},
//关闭蓝牙
close_bluetooth(){
let that =this
//关闭蓝牙都把之前的清空
that.no_match_list=[];
that.match_list=[]
if (BAdapter.isEnabled()) {
BAdapter.disable();//关闭蓝牙
uni.showToast({
title: '蓝牙已关闭',
duration:
})
}
},
//获取已匹配蓝牙设备
bluetooth_list(){
let that=this
//先清空
that.match_list=[] var lists = BAdapter.getBondedDevices();
plus.android.importClass(lists);
var iterator = lists.iterator();
plus.android.importClass(iterator);
while (iterator.hasNext()) {
var d = iterator.next();
plus.android.importClass(d);
let arr={
"name": d.getName(),
"SN": d.getAddress()
}
that.match_list.push(arr)
}
},
//搜索没匹配的蓝牙设备
search_bluetooth(address){
let that=this
//判断蓝牙是否开启
if (!BAdapter.isEnabled()) {
uni.showToast({
title: '请先打开蓝牙',
duration:
});
return
}
if(address.length!=undefined){
uni.showModal({
title: '提示',
content: '是否配对此蓝牙?',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
uni.showLoading({
title: '蓝牙匹配中...'
});
that.search_pipei(address)
}
}
});
}else{
uni.showLoading({
title: '蓝牙搜索中...'
});
that.search_pipei()
}
},
//搜索和匹配蓝牙
search_pipei(address){
let that=this
//获取已匹配的蓝牙
that.bluetooth_list()
//每次搜索都把之前的清空
that.bArray=[];
that.no_match_list=[]; var filter = new IntentFilter();
var BDevice = new BluetoothDevice();
BAdapter.startDiscovery(); //开启搜索
var receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: function(context, intent) { //回调
try {
plus.android.importClass(intent); //通过intent实例引入intent类
if(intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
uni.hideLoading()
main.unregisterReceiver(receiver); //取消监听
} else {
//从Intent中获取设备对象
BDevice= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//配对蓝牙
if (address == BDevice.getAddress()) {
if (BDevice.createBond()) { //配对命令.createBond()
console.log("配对成功");
uni.hideLoading()
} }
if(BDevice == null) {
main.unregisterReceiver(receiver); //取消监听
uni.hideLoading()
//获取已匹配的蓝牙
that.bluetooth_list()
return;
}
var name=BDevice.getAddress()+BDevice.getName();
if(that.bArray.indexOf(name) == -){ //去重
that.bArray.push(name);//用于去重的
let arr={
"name": BDevice.getName(),
"SN": BDevice.getAddress()
}
that.no_match_list.push(arr)
console.log(JSON.stringify(that.no_match_list))
} }
} catch(e) {
console.error(e);
}
}
});
filter.addAction(BDevice.ACTION_FOUND);
filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BAdapter.ACTION_STATE_CHANGED);
main.registerReceiver(receiver, filter); //注册监听
},
}
}
</script> <style scoped="scoped" lang="scss">
@import "./Bluetooth.scss";
</style>

css

.bluetooth{
padding: 20upx 20upx 120upx;
.h1{
padding: 20upx ;color: #1482D1;border-top: 1upx solid #EFEFF4;
} .btn{
display:flex;position:fixed;bottom:0upx;padding:20upx 10upx;justify-content:space-around;width: %;color:#fff;border-top:1px solid #f2f2f2;background-color: #fff;
view{
width: 200upx;height: 80upx;line-height:80upx;text-align: center;border-radius:10upx;
}
.btn_1{
background-color: #009BDE;
}
.btn_2{
background-color: red;
}
.btn_3{
background-color: #3CB371;
}
}
.uni-textarea{
textarea{
border: 1px solid #EFEFF4;border-radius: 10px;width: %;padding: 10upx;box-sizing: border-box;
}
.fasong{
width: %;padding:15upx 10upx;box-sizing: border-box;border-radius: 10px;background: #1482D1;text-align: center;color: white;margin: 10px ;
}
}
}

如果报错你可能需要下载一个蓝牙开发助手当服务端

vue app混合开发蓝牙串口连接(报错java.io.IOException: read failed, socket might closed or timeout, read ret: -1;at android.bluetooth.BluetoothSocket.connect at js/BluetoothTool.js:329)的更多相关文章

  1. github提交失败并报错java.io.IOException: Authentication failed:

    一.概述 我最近在写一个android的项目. 软件:android studio.Android studio VCS integration(插件) Android studio VCS inte ...

  2. Kafka 启动报错java.io.IOException: Can't resolve address.

    阿里云上 部署Kafka 启动报错java.io.IOException: Can't resolve address. 本地调试的,报错 需要在本地添加阿里云主机的 host 映射   linux ...

  3. Spark报错java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.

    Spark 读取 JSON 文件时运行报错 java.io.IOException: Could not locate executable null\bin\winutils.exe in the ...

  4. React Natived打包报错java.io.IOException: Could not delete path '...\android\support\v7'解决

    问题详情 React Native打包apk时在第二次编译时候报错: java.io.IOException: Could not delete path 'D:\mycode\reactnative ...

  5. hadoop报错java.io.IOException: Bad connect ack with firstBadLink as 192.168.1.218:50010

    [root@linuxmain hadoop]# bin/hadoop jar hdfs3.jar com.dragon.test.CopyToHDFS Java HotSpot(TM) Client ...

  6. hadoop报错java.io.IOException: Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-address is not configured

    不多说,直接上干货! 问题详情 问题排查 spark@master:~/app/hadoop$ sbin/start-all.sh This script is Deprecated. Instead ...

  7. java get请求带参数报错 java.io.IOException: Server returned HTTP response code: 400 for URL

    解决方案 在使用JAVA发起http请求的时候,经常会遇到这个错误,我们copy请求地址在浏览器中运行的时候又是正常运行的,造成这个错误的原因主要是因为请求的URL中包含空格,这个时候我们要使用URL ...

  8. jsp报错java.io.IOException: Stream closed

    在使用jsp的时候莫名其妙的抛出了这个异常,经过反复检查 去掉了网友们说的jsp使用流未关闭,以及tomcat版本冲突等原因,最后发现是书写格式的原因. 当时使用的代码如下 <jsp:inclu ...

  9. 关于SpringMVC项目报错:java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/xxxx.xml]

    关于SpringMVC项目报错:java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/xxxx ...

随机推荐

  1. 控制结构(11): Continuation passing style(CPS)

    // 上一篇:控制结构(10)指令序列(opcode) [注释]: 这个笔记系列需要告一个段落了,收尾部分整理下几个时髦(The New Old Things)结构. 后面打算开一个算法方面的,重新学 ...

  2. mysql varchar integer

    MySQL 中将 varchar 字段转换成数字进行排序 - MySQL - 大象笔记 https://www.sunzhongwei.com/order-by-varchar-field-which ...

  3. jmeter学习记录--08--第三方测试组件

    我们安装的JMeter版本,功能仍然有欠缺,插件是一种补充,官方提供了很多插件. 官网地址:http://www.jmeter-plugins.org/, 里面有很多可以安装到JMeter的插件,基本 ...

  4. 前后端不分离的springboot项目问题:页面框架问题

    前言:最近自己想搞一个以springboot开发的web项目,由于页面布局问题,在前期开发的时候没有太注意,每天写一点现在开发到一半出现了一个大问题. 1.先说说整个网站框架搭建问题:(整个项目前后端 ...

  5. Pyspark-SQL 官方 API 的一些梳理(上)

    在 Pyspark 操纵 spark-SQL 的世界里借助 session 这个客户端来对内容进行操作和计算.里面涉及到非常多常见常用的方法,本篇文章回来梳理一下这些方法和操作. class pysp ...

  6. 使用Spring表达式语言进行装备--SpEL

    本文主要想记录最近的两个使用spring框架实现通过配置文件装备Bean,以及使用SpEL装备Bean. 1.使用配置文件装备Bean: 当我们写某些Bean的时候是希望这个Bean当中的属性是可以通 ...

  7. angular 4 router传递数据三种方法

    1.在查询参数中传递数据 <a  [routerLink]="['/product']" [queryParams]="{id:1,name:'dongian'}& ...

  8. Python——Flask框架——程序的结构

    一.项目结构 |-flasky |-app Flask程序一般都保存在这里 |-templates/ |-static/ |main/ |-__init__.py |-errors.py |-form ...

  9. [BZOJ 2242] [SDOI 2011] 计算器

    Description 你被要求设计一个计算器完成以下三项任务: 给定 \(y,z,p\),计算 \(y^z \bmod p\) 的值: 给定 \(y,z,p\),计算满足 \(xy≡ z \pmod ...

  10. tomcat配置详解

    Tomcat Server的结构图如下: 该文件描述了如何启动Tomcat Server <Server>    <Listener />    <GlobaNaming ...