最近遇到使用Android与BLE设备通信的开发项目,最开始感觉一头雾水,网上的资料不多,只能自己看谷歌提供的demo慢慢消化。
简单的来讲首先一个BLE设备包含多个service,而每个service又包含多个character,具体的数据就存储在character内。
1.获取BluethAdapter
private BluetoothAdapterbtAdapter;
finalBluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter =bluetoothManager.getAdapter();
2.启动扫描
得到btAdapter后,就可以使用btAdapter.startLeScan(mtemp);来启动扫描了,其中mtemp是 BluetoothAdapter.LeScanCallback回调函数。扫描到设备后,会回调onLeScan()
3.连接设备
在onLeScan()中可以启动连接
device.connectGatt(this, true, gattCallback);
4.获取UUID
在回调函数BluetoothGattCallback中实现
serviceList = gatt.getServices();和characterList =theService.getCharacteristics();返回的都是list
5.获取数据
最开始一直没搞懂怎么得到characteristics的值,自习分析才发现,通过
connectGatt连接设备后还需要对得到的某个characteristics使用gatt.readCharacteristic(characterList.get(0));才能在回调函数的onCharacteristicRead中得到value
关于UUID
通过以上方法得到的uuid是128bit,但是实际上在TI的开发板demo里都是16bit的uuid,这里需要用到uuid转换,这篇文章写的很好
http://blog.csdn.net/zhangjs0322/article/details/39048509