在工作中,我们有一个设备可以每隔几秒更新自定义服务中的自定义特性并使用BLE。我想做的就是监控这些更新。我的目标是编写最少的代码,以便连接到该设备,然后连接到服务,然后监视其特性。但是我无法连接到设备。
每次通过扫描此功能找到蓝牙设备时都会调用:
void checkDevice(BluetoothDevice device){
if (targetFound) return;
if (device.getAddress().equals(DEVICE_ADDRESS)){
logger.append("-> Target device found with name: " + device.getName() + "\n");
targetFound = true;
targetDevice = device;
bleAdapter.stopLeScan(new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
logger.append("-> Scan has stopped\n");
}
});
logger.append("-> Attempting to connect to target device\n");
gattConnection = targetDevice.connectGatt(this,false,gattCallBackFuntion);
}
}
这是我对gattCallBackFunction的实现:
private BluetoothGattCallback gattCallBackFuntion = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Boolean gattRes = gattConnection.discoverServices();
logger.append("-> Connected to GATT Server. Starting service discovery. Result: " + gattRes.toString() + "\n");
}
else{
logger.append("-> Connection state has changed but is " + newState);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
List<BluetoothGattService> services = gatt.getServices();
String list = "";
String tab = " ";
for (int i = 0; i < services.size(); i++){
BluetoothGattService service = services.get(i);
list = list + tab + service.toString() + "\n";
}
logger.append("-> Services Discovered: \n");
logger.append(list);
}
};
这两个函数都是在同一个类中实现的,这是唯一的活动。
据我所知,某些时候必须由Android调用onConnectionStateChange函数,指示与Device的连接。然而,这从未发生过。该应用程序打印&#34;尝试连接到目标设备&#34;并且没有其他事情发生
有什么想法吗?
答案 0 :(得分:0)
大多数蓝牙gatt回调都在后台线程中运行,因此您不应在回调中执行任何UI操作。您需要根据Android UI准则
在UI线程上运行所有操作