2017-03-08 76 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線程上運行所有操作。