我花了几天时间进行故障排除,但没有成功。问题是我无法确定哪个设备遇到错误,因此导致断开连接。在连接阶段或服务发现阶段,CBPeripheralManagerDelegate没有回调,因此我不知道出现错误的具体时间(如果错误出现在iOS侧)。在Android侧,调用一个方法来启动服务发现,但是他们的回调“onServicesDiscovered”没有被调用,这很困惑。是否有任何方法可以深入探究iOS侧的BTLE通信细节,以查看正在发生什么并确定发生了哪个错误?
我已经历了至少一周的相同问题。我已经在这里提出了问题,并且已经自己回答了。主要问题是安卓的一个BUG问题。它在固定的L2CAP通道上发送了一个不允许的命令。
但是当安卓与普通外围BLE设备通信时,它运行得非常好。实际上,BLE示例非常有效。问题出现在与iOS设备通信时:连接建立后,它们开始协商连接参数(这个阶段不会发生在普通的BLE外围设备中),这就是问题出现的时候。安卓向iOS发送错误的命令,iOS断开连接。基本上就是这样。
一些问题已经报告给谷歌,其中一个已经被接受,我希望他们很快开始解决这个问题。
不幸的是,你能做的就是等待下一个安卓版本发布。无论如何,我强烈建议您查看我的问题报告及所有测试文档,如果您想对这个问题有所了解。
这是链接:https://code.google.com/p/android/issues/detail?id=58725
我已经写了一个相对简单的工作示例,并在Github上以开源形式包含:https://github.com/GitGarage。目前,这个示例只经过了Android Nexus 9和iPhone 5s的测试,但我认为它也适用于Nexus 6和各种型号的iPhone。目前,它被明确设置为在一个Android和一个iPhone之间通信,但我认为它可以进行更多的调整。
以下是关键方法...
private void sendMessage() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
if (mBTAdapter == null) {
return;
}
if (mBTAdvertiser == null) {
mBTAdvertiser = mBTAdapter.getBluetoothLeAdvertiser();
}
// get the full message from the UI
String textMessage = mEditText.getText().toString();
if (textMessage.length() > 0)
{
// add 'Android' as the user name
String message = "Android: " + textMessage;
while (message.length() > 0) {
String subMessage;
if(message.length() > 8)
{ // add dash to unfinished messages
subMessage = message.substring(0,8) + "-";
message = message.substring(8);
for (int i = 0; i < 20; i++) // twenty times (better safe than sorry) send this part of the message. duplicate parts will be ignored
{
AdvertiseData ad = BleUtil.makeAdvertiseData(subMessage);
mBTAdvertiser.startAdvertising(BleUtil.createAdvSettings(true, 100), ad, mAdvCallback);
mBTAdvertiser.stopAdvertising(mAdvCallback);
}
}
else
{ // otherwise, send the last part
subMessage = message;
message = "";
for (int i = 0; i < 5; i++)
{
AdvertiseData ad = BleUtil.makeAdvertiseData(subMessage);
mBTAdvertiser.startAdvertising(
BleUtil.createAdvSettings(true, 40), ad,
mAdvCallback);
mBTAdvertiser.stopAdvertising(mAdvCallback);
}
}
}
threadHandler.post(updateRunnable);
}
}
});
thread.start();
}
@Override
public void onLeScan(final BluetoothDevice newDevice, final int newRssi,
final byte[] newScanRecord) {
int startByte = 0;
String hex = asHex(newScanRecord).substring(0,29);
// check five times, startByte was used for something else before
while (startByte <= 5) {
// check if this is a repeat message
if (!Arrays.asList(used).contains(hex)) {
used[ui] = hex;
String message = new String(newScanRecord);
String firstChar = message.substring(5, 6);
Pattern pattern = Pattern.compile("[ a-zA-Z0-9~!@#$%^&*()_+{}|:\"<>?`\\-=;',\\./\\[\\]\\\\]", Pattern.DOTALL);
// if the message is comprised of standard characters...
Matcher matcher = pattern.matcher(firstChar);
if (firstChar.equals("L"))
{
firstChar = message.substring(6, 7);
pattern = Pattern.compile("[ a-zA-Z0-9~!@#$%^&*()_+{}|:\"<>?`\\-=;',\\./\\[\\]\\\\]", Pattern.DOTALL);
matcher = pattern.matcher(firstChar);
}
if(matcher.matches())
{
TextView textViewToChange = (TextView) findViewById(R.id.textView);
String oldText = textViewToChange.getText().toString();
int len = 0;
String subMessage = "";
// add this portion to our final message
while (matcher.matches())
{
subMessage = message.substring(5, 6+len);
matcher = pattern.matcher(message.substring(5+len, 6+len));
len++;
}
subMessage = subMessage.substring(0,subMessage.length()-1);
Log.e("Address",newDevice.getAddress());
Log.e("Data",asHex(newScanRecord));
boolean enter = subMessage.length() == 16;
enter = enter && !subMessage.substring(15).equals("-");
enter = enter || subMessage.length() < 16;
textViewToChange.setText(oldText + subMessage.substring(0, subMessage.length() - 1) + (enter ? "\n" : ""));
ui = ui == 2 ? -1 : ui;
ui++;
Log.e("String", subMessage);
}
break;
}
startByte++;
}
}
func startAdvertisingToPeripheral() {
var allTime:UInt64 = 0;
if (dataToSend != nil)
{
datastring = NSString(data:dataToSend, encoding:NSUTF8StringEncoding) as String
datastring = "iPhone: " + datastring
if (datastring.length > 15)
{
for (var i:Double = 0; i < Double(datastring.length)/15.000; i++)
{
let delay = i/10.000 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
allTime = time
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in self.sendPart() });
}
}
else
{
var messageUUID = StringToUUID(datastring)
if !peripheralManager.isAdvertising {
peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [CBUUID(string: messageUUID)]])
}
}
}
}
func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {
delegate?.didDiscoverPeripheral(peripheral)
var splitUp = split("\(advertisementData)") {$0 == "\n"}
if (splitUp.count > 1)
{
var chop = splitUp[1]
chop = chop[0...chop.length-2]
var chopSplit = split("\(chop)") {$0 == "\""}
if !(chopSplit.count > 1 && chopSplit[1] == "Device Information")
{
var hexString = chop[4...7] + chop[12...19] + chop[21...26]
var datas = hexString.dataFromHexadecimalString()
var string = NSString(data: datas!, encoding: NSUTF8StringEncoding) as String
if (!contains(usedList,string))
{
usedList.append(string)
if (string.length == 9 && string[string.length-1...string.length-1] == "-")
{
finalString = finalString + string[0...string.length-2]
}
else
{
lastString = finalString + string + "\n"
println(lastString)
finalString = ""
usedList = newList
usedList.append(string)
}
}
}
}
}
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.v(TAG, "BluetoothAdapter not initialized");
return;
}
UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // UUID for client config desc
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
我想分享一下我的经验,因为我曾经处理过这个问题,但由于谷歌没有提供支持,所以我放弃了。上述代码,我非常感谢,但它不起作用。你可以在合理的时间内编写一个iOS到iOS或Android到Android的蓝牙低功耗应用程序,但当你尝试在iOS和Android之间通信时,问题就出现了。有一个被充分记录的谷歌问题(https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=58725),我参与了其中,但谷歌根本没有回应,而且似乎他们关闭了这个问题,Android M中也没有任何改变,因为我一直在查看代码,没有看到进一步的差异。问题出现在Android尝试连接时,特别是在“if else”语句中;这段代码基本上拒绝了传输并切断了通信,所以它不起作用。目前还没有解决方案。你可以使用WiFi直连解决方案,但这是一个限制,并且在执行此操作时会出现更多问题。如果你想使用外部硬件(树莓派、传感器等)实现BLE,那么这个问题就不存在了,但在iOS和Android之间不起作用。两个平台的技术基本相同,但在Android中没有很好地实现,或者是谷歌故意设置的陷阱,以防止打开在两个平台之间通信的大门。
我们一直在尝试跨平台BLE连接(iOS<-> Android),并发现仍然存在许多不兼容和连接问题。
如果您的用例是以功能为驱动的,并且只需要基本的数据交换,我建议您查看可以为您实现跨平台通信的框架和库,而无需从头开始构建。
例如http://p2pkit.io或Google Nearby
免责声明:我在Uepaa工作,开发Android和iOS的p2pkit.io。