之前做了个项目是手机通过蓝牙连接其他蓝牙设备,并实现相互通信。研究了一段时间,现在将研究中的心得分享出来。
通常蓝牙连接的基本流程是:
先得到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进制数据传输的,而且大部分通过蓝牙收到的数据都是有格式的,通过格式解析才能正确解析出内容。
这里的东西在网上基本都能收到,这里只是做了一个总结,希望能帮助你,