前一文章里,研究了,Android,IOS各自的蓝牙实现方式,今天花了点时间研究蓝牙4.0,BLE协议下,Android与IOS两系统开发的APP实现用蓝牙的通信,
- IOS 6.0+
- Android 5.0+
我们这里把IOS做为外设,Android做为中央设备,IOS作为外设的代码,请参考上篇教程的源码,一模一样。这篇记录着重关系Android BLE的开发,下面是准备工作:
添加AndroidManifest.xml中的权限
记得要加uses-feature,参考源代码中的配置文件
添加一个Service负责蓝牙的通信
这里我就不给出代码了,请自行从参考网站中,下载,我只增加了一个写内容的方法
public boolean writeValueData(BluetoothGattCharacteristic characteristic, byte[] data) {
boolean ret = false;
if (data == null) {
return false;
}
int length = data.length;
if (length <= dataBufferSize) {
characteristic.setValue(data);
ret = mBluetoothGatt.writeCharacteristic(characteristic);
} else {
int count = 0;
int offset = 0;
while (offset < length) {
if ((length - offset) < dataBufferSize) {
count = length - offset;
} else {
count = dataBufferSize;
}
byte tempArray[] = new byte[count];
System.arraycopy(data, offset, tempArray, 0, count);
characteristic.setValue(data);
ret = mBluetoothGatt.writeCharacteristic(characteristic);
if (!ret) {
return ret;
}
offset = offset + count;
}
}
return ret;
}
修改直接相联蓝牙
教程中,各种数据,各种UI,我简化了。在拿到Service后直接相关,修改了其中的方法,代码如下:
private void displayGattServices(ListgattServices) {
if (gattServices == null) return;
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
String uuid = gattService.getUuid().toString();
if(BluetoothLeService.UUID_HEART_RATE_MEASUREMENT.equals(gattService.getUuid())){
Log.d(“gattService”, uuid);
if(BluetoothGattCharacteristic.PROPERTY_READ>0){
ListgattCharacteristics =gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
String charUDID = gattCharacteristic.getUuid().toString();
if(charUDID.equalsIgnoreCase(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG)){
Log.d(“charUDID”, charUDID);
for(BluetoothGattDescriptor descriptor:gattCharacteristic.getDescriptors()){
String desUDID = descriptor.getUuid().toString();
Log.d(“desUDID”, desUDID);
}
mCharacteristic = gattCharacteristic;
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
}
}
}
}
}
}
这里有个小问题。还没有弄明白,为什么,IOS跟Android的Descriptor的UDID不一样吗?我重新定义了下,相关的UDID,参考:SampleGattAttributes.
PS:在发送数据时,记得在IOS端输入Android端提示的Code,蓝牙连接密码
相关源码在:代码查看下载
入口为: BLEActivity
参考:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html