试图创建一个BLE中央应用程序来与外设通信。android BLE writeCharacteristic在设备上运行时返回false,但在调试模式下工作。
我使用这里给出https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
的BluetoothLeService应用创建一个外围我使用的是Android应用https://play.google.com/store/apps/details?id=com.macdom.ble.blescanner。
我能够阅读并获得有关特性更改的通知,我修改了BluetoothLeService以使用BluetoothGatt的writeCharacteristic更新特性。使用
设备:
外设:红米手机注4(启用了所有的权限(读,写,通知))作为切牙
设备:
LG电子的Nexus 5X( Android 7.1.2,API 25)
LGE Nexus 4(Android 5.1.1,API 22)
Android的工作室: 版本2.3.3 gradle这个文件: 的Android { compileSdkVersion 25 buildToolsVersion “25.0.3”
defaultConfig {
minSdkVersion 18
targetSdkVersion 25
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
sourceSets {
main {
dirs.each { dir ->
java.srcDirs "src/${dir}/java"
res.srcDirs "src/${dir}/res"
}
}
androidTest.setRoot('tests')
androidTest.java.srcDirs = ['tests/src']
}
}
代码:
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
Log.w("Tharun", "onServicesDiscovered received: " + status);
setStatus(status);
broadcastUpdate(WRITE_DATA);
}
};
public void writeCharacteristic(BluetoothGattCharacteristic characteristic, String
writeString) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
characteristic.setValue(writeString);
boolean result = mBluetoothGatt.writeCharacteristic(characteristic);
Log.w(TAG, "writeCharacteristic result : " + result);
}
问题:
当我在上述设备上执行代码时,writeCharacteristic返回false。即使onCharacteristicWrite也不会被调用。
但是,当我将android studio以调试模式附加到应用程序并添加一个断点(只有存在某个断点的地方,如果没有断点,它不起作用)写入成功并且onCharacteristicWrite正在跑。
我无法弄清楚问题所在。
我试图通过该函数的代码,看看为什么它返回false,但无法找到任何东西。
任何帮助,非常感谢。
当您启动该写入尝试时,您是否正在进行的尚未完成的GATT操作? – Emil
我确定没有尚未完成的GATT操作。我最初的怀疑是android-studio运行源代码与我的设备上的代码不同。结果是这样。我创建了一个新项目(使用api 22和android 5.1.1)将所有代码复制到那里。现在它工作正常。谢谢您的帮助。 – tharun