最近进行Android ble的开发,遇到最大的问题就是在往characteristic中写入数据的时候,会有一个成功率抖动的问题,常会出现第一次写入失败,必须再写一次才成功的情况。
每次往characteristic中写入数据的时候,应该要回调onCharacteristicWrite这个方法的,如果失败了,根本就不回调这个方法,导致我甚至无出判断成功还是失败,无法再逻辑代码中去重写,只能在交互界面重复操作。
下面我贴出我大致代码。
private void connectDevice() { mDevice.connectGatt(this, false, new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { Log.d("MainActivity", "连接成功"); mGatt = gatt; mGatt.connect(); gatt.discoverServices(); } } @Override public void onServicesDiscovered(final BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Listservices = gatt.getServices(); mGattService = services.get(4); BluetoothGattCharacteristic notificationCharacteristic = mGattService.getCharacteristics().get(0); mWriteCharacteristic = services.get(4).getCharacteristics().get(1); mSimpleIO.setString("notificationUUID", notificationCharacteristic.getUuid().toString()); gatt.setCharacteristicNotification(notificationCharacteristic, true); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { switch (mCurrState) { case ConstantContainer.VERIFY_DEFAULT_KEY: alterNewKey(gatt, characteristic); break; case ConstantContainer.ALTER_KEY: bondSuccess(); break; case ConstantContainer.REMOVE_BOND: mGatt.disconnect(); try { if (removeBond(mDevice)) { mSimpleIO.remove("deviceAddress"); mSimpleIO.remove("notificationUUID"); runOnUiThread(new Runnable() { @Override public void run() { showFindLayout(); } }); } } catch (Exception e) { e.printStackTrace(); } break; } } else { switch (mCurrState) { case ConstantContainer.VERIFY_DEFAULT_KEY: Log.d("BluetoothActivity", "验证初始密码失败"); break; case ConstantContainer.ALTER_KEY: Log.d("BluetoothActivity", "修改密码失败"); break; case ConstantContainer.REMOVE_BOND: Log.d("BluetoothActivity", "删除配对失败"); break; } } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { } });
上面的代码是BluetoothGattCallback的几个主要回调,可以看到我在onCharacteristicWrite中对他的status做了判断,想要定位写入是否成功,但结果是失败的情况下,并不回调这个方法。
private void alterNewKey(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { mWriteCharacteristic.setValue("BBTM=" + mBlueKey); mCurrState = ConstantContainer.ALTER_KEY; Log.d("BluetoothActivity", "gatt.writeCharacteristic(characteristic) alterNewKey:" + gatt.writeCharacteristic(characteristic)); } private void writeDefaultKey(BluetoothGatt gatt, BluetoothGattCharacteristic mWriteCharacteristic) { mCurrState = ConstantContainer.VERIFY_DEFAULT_KEY; mWriteCharacteristic.setValue(ConstantContainer.DEFAULT_KEY); Log.d("BluetoothActivity", "gatt.writeCharacteristic(mWriteCharacteristic) writeDefaultKey:" + gatt.writeCharacteristic(mWriteCharacteristic)); }
这两个方法是我写入的部分,我把它们的返回值打印出来可发现,无论成功失败,返回的都是true。
救命啊,要疯了,球大神解答。