设备通过蓝牙连接并相互通信问题

之前做了个项目是手机通过蓝牙连接其他蓝牙设备,并实现相互通信。研究了一段时间,现在将研究中的心得分享出来。

通常蓝牙连接的基本流程是:
先得到BluetoothAdapter, 之后通过BluetoothAdapter得到BluetoothDevice:

BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();

//判断本机是否有蓝牙设备
if(blueAdapter == null){
    ToastUtils.setShortToast(this, "本机没有蓝牙设备!");
    return;
}
//判断蓝牙设备是否可用
if(!blueAdapter.isEnabled()){
    //如果蓝牙设备不可用的话,开启蓝牙
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 10001);
    return ;
}

//所有匹配过的蓝牙设备信息都在  blueAdapter.getBondedDevices() 里面
blueAdapter.getBondedDevices()得到的是set集合,里面装的就是 BluetoothDevice

再通过BluetoothDevice获取到BluetoothSocket,这其中BluetoothDevice获取到BluetoothSocket就是俩个设备蓝牙连接的过程,连接基本有俩种方法,如下:

//蓝牙连接 (此过程全部方法返回为void,执行后没有进入catch则说明连接成功!)
//方法一:指定uuid连接
bluetoothSocket = device.createRfcommSocketToServiceRecord(Constant.uuId);
bluetoothSocket.connect();


//方法2:通过反射机制获取uuid去连接
Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
bluetoothSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
bluetoothSocket.connect();

方法一种的uuid随便在网上都能收到:
//android规定好的蓝牙串口服务唯一标识
public static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

但有的时候我门发现通过uuid进行蓝牙连接对一些设备是不管用的,这时候不妨试试方法二。

最后通过BluetoothSocket得到输入输出流,进行通信:

InputStream in = bluetoothSocket.getInputStream();
OutputStream out = bluetoothSocket.getOutputStream();

对于输入流,就在while里处理:

/**
* 此方法用于解析蓝牙输出流
*/
private void getINputInfo(){
   try {
      while (enable) {
         byte[] buffer = new byte[512];
         int size = inputStream.read(buffer);
         if (size > 0) {
            输入的信息就在buffer里
         }
      }
   } catch (Exception e) {
   }
}

对于输出流,需要输出的时候调用:
synchronized (outputStream) {
   outputStream.write(buffer);
   outputStream.flush();
}

这里的输入输出通信都是通过 byte[] 来的,记得要转码一下。

最后提醒一下,蓝牙通信数据都是通过16进制数据传输的,而且大部分通过蓝牙收到的数据都是有格式的,通过格式解析才能正确解析出内容。


这里的东西在网上基本都能收到,这里只是做了一个总结,希望能帮助你,




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值