2017-03-08 152 views
0

在工作中,我们有一个设备每隔几秒更新自定义服务中的自定义特征并使用BLE。我只想监视那些更新。我的目标是编写最少量的代码,以便连接到该设备,然后连接到该服务,然后监控其特性。但是我无法连接到设备。Android,非常简单的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); 
    } 
}; 

这两个功能在同一类中实现这是唯一的活动。

据我了解,在某些时候,onConnectionStateChange函数必须由Android调用,指示连接到设备。然而这从来没有发生过该应用程序打印“试图连接到目标设备”,而不会发生其他情况

任何想法?

+0

这应该确实有效。查看HCI snoop log或logcat,看看有没有什么有趣的地方。另一件事是,bleAdapter.stopScan的参数必须是对startScan中使用的同一个回调对象的引用。 – Emil

+0

请发布日志,代码似乎很好。 – 7383

+0

正确!日志非常清晰。蓝牙没有问题。问题是记录器行(logger.append(“ - >连接到GATT服务器。启动服务发现。结果:”+ gattRes.toString()+“\ n”);)事实证明,这不是在用户界面串。通过创建一个只更新文本视图并从runOnUiThread调用它的runnable来解决问题。谢谢。有人应该为此写一个答案。 PD:感谢关于stopLeScan的回电说明! – aarelovich

回答

0

大多数蓝牙gatt回调在后台线程中运行,因此您不应该在回调中执行任何UI操作。您需要根据Android UI准则在UI线程上运行所有操作。