2017-10-12 252 views
0

我正在開發一個Android應用程序,每天必須連接+/- 120個BLE GATT服務器,其中至少有3個服務器同時具有完全相同的服務和特點。儘管遵循所有標準和默認模式,但我一直在體驗Android BLE的各種問題。Android BLE onCharacteristic讀取錯誤的狀態導致藍牙已停止工作

每天發生的事情是,我必須至少一次將平板電腦重置爲默認設置,因爲'藍牙已停止工作',其中找不到原因。 這是非常令人沮喪的,我無法忍受這種類型的維護每一天(硬重置)。

起初,我嘗試了Android SDK 18的BLE,其中的行爲非常奇怪,只用了一天就顯示出糟糕的結果。 所以我開始使用操縱Android BLE的棒棒糖版本,它顯示了一些改進。

我幾天來都在遇到這些問題,因爲我得到了意想不到的結果,例如onCharacteristicRead返回但數據爲空。例如,我在帶有STATE_CONNECTED的onConnectionStateChanged之後調用discoverServices(),因此在一段時間之後onServicesDiscovered()被調用但getServices()返回null。 所有這些問題只發生在從第一臺服務器斷開連接之後。它連接的第一臺服務器正確讀寫所有內容,然後斷開連接()和onConnectionStateChanged(),然後關閉()。因此,我連接到下一個服務器,並且我開始遇到這些問題(所有GATT操作都在主線程中,所有連接都正確並妥善處理),因此我必須斷開連接,以便can應用程序可以讀取GATT屬性正確。

我有3個閱讀特徵,閱讀第三個特徵後,我開始寫3個特徵。

我已經通過藍牙日誌,我可以看到意外的事情發生。該日誌,當應用程序讀取一切正常(它總是隻有第一GATT服務器的應用程序連接到):

10-11 09:08:05.350 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.350 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.350 15989-15989/efp.android.sample D/BluetoothLeScanner: Start Scan 
10-11 09:08:05.351 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.352 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.353 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.354 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.362 15989-15994/efp.android.sample I/art: Do partial code cache collection, code=48KB, data=60KB 
10-11 09:08:05.362 15989-15994/efp.android.sample I/art: After code cache collection, code=48KB, data=60KB 
10-11 09:08:05.362 15989-15994/efp.android.sample I/art: Increasing code cache capacity to 256KB 
10-11 09:08:05.457 15989-16002/efp.android.sample D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=5 mClientIf=0 
10-11 09:08:05.513 15989-15989/efp.android.sample W/IInputConnectionWrapper: getCursorCapsMode on inactive InputConnection 
10-11 09:08:05.681 15989-16023/efp.android.sample D/ScanRecord: parseFromBytes 
10-11 09:08:05.681 15989-15989/efp.android.sample D/LAURASTAR_BLE: onScanResult 
10-11 09:08:05.682 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.683 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.684 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.685 15989-15989/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-11 09:08:05.685 15989-15989/efp.android.sample D/BluetoothLeScanner: Stop Scan 
10-11 09:08:05.692 15989-15989/efp.android.sample D/BluetoothGatt: connect() - device: F5:8E:C1:91:DC:CC, auto: false 
10-11 09:08:05.692 15989-15989/efp.android.sample D/BluetoothAdapter: isSecureModeEnabled 
10-11 09:08:05.699 15989-15989/efp.android.sample D/BluetoothGatt: registerApp() 
10-11 09:08:05.699 15989-15989/efp.android.sample D/BluetoothGatt: registerApp() - UUID=ebf41986-8aad-4796-a537-7319c00f0f46 
10-11 09:08:05.802 15989-16002/efp.android.sample D/BluetoothGatt: onClientRegistered() - status=0 clientIf=5 
10-11 09:08:06.332 15989-16001/efp.android.sample D/LAURASTAR_BLE: onConnectionStateChange: 
10-11 09:08:06.332 15989-16001/efp.android.sample D/BluetoothGatt: discoverServices() - device: F5:8E:C1:91:DC:CC 
10-11 09:08:06.343 15989-16002/efp.android.sample D/BluetoothGatt: onSearchComplete() = Device=F5:8E:C1:91:DC:CC Status=0 
10-11 09:08:06.343 15989-16002/efp.android.sample D/LAURASTAR_BLE: onServicesDiscovered: 
10-11 09:08:07.143 15989-16002/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=51 Status=0 
10-11 09:08:07.233 15989-16002/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=14 Status=0 
10-11 09:08:07.324 15989-16023/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=23 Status=0 
10-11 09:08:08.136 15989-16023/efp.android.sample D/BluetoothGatt: cancelOpen() - device: F5:8E:C1:91:DC:CC 
10-11 09:08:08.146 15989-16001/efp.android.sample D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=5 device=F5:8E:C1:91:DC:CC 
10-11 09:08:08.151 15989-16001/efp.android.sample D/LAURASTAR_BLE: onConnectionStateChange: 
10-11 09:08:08.265 15989-15989/efp.android.sample D/BluetoothGatt: close() 
10-11 09:08:08.266 15989-15989/efp.android.sample D/BluetoothGatt: unregisterApp() - mClientIf=5 

從第一GATT服務器斷開連接到第二GATT服務器後,我必須不斷斷開並重新連接以讀取特性,儘管它總是正確讀取第一個特性。

這裏的時候閱讀與問題發生的日誌......所以,如果讀數有錯誤,我需要斷開並重新連接(即使讀重新連接後有錯誤,它會關閉,掃描並再次嘗試)。

10-12 08:03:48.133 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.133 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.134 30409-30409/efp.android.sample D/BluetoothLeScanner: Start Scan 
10-12 08:03:48.134 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.137 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.260 30409-31121/efp.android.sample D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6 mClientIf=0 
10-12 08:03:48.391 30409-30422/efp.android.sample D/ScanRecord: parseFromBytes 
10-12 08:03:48.395 30409-30409/efp.android.sample D/LAURASTAR_BLE: onScanResult 
10-12 08:03:48.397 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.397 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.398 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.399 30409-30409/efp.android.sample D/BluetoothAdapter: STATE_ON 
10-12 08:03:48.399 30409-30409/efp.android.sample D/BluetoothLeScanner: Stop Scan 
10-12 08:03:48.410 30409-30409/efp.android.sample D/BluetoothGatt: connect() - device: F5:8E:C1:91:DC:CC, auto: false 
10-12 08:03:48.410 30409-30409/efp.android.sample D/BluetoothAdapter: isSecureModeEnabled 
10-12 08:03:48.411 30409-30409/efp.android.sample D/BluetoothGatt: registerApp() 
10-12 08:03:48.411 30409-30409/efp.android.sample D/BluetoothGatt: registerApp() - UUID=ce6919e5-e4f7-4180-a313-557e168a7c5a 
10-12 08:03:48.514 30409-30422/efp.android.sample D/BluetoothGatt: onClientRegistered() - status=0 clientIf=6 
10-12 08:03:48.745 30409-31121/efp.android.sample D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=F5:8E:C1:91:DC:CC 
10-12 08:03:48.755 30409-31121/efp.android.sample D/BluetoothGatt: discoverServices() - device: F5:8E:C1:91:DC:CC 
10-12 08:03:48.915 30409-30414/efp.android.sample I/art: Do partial code cache collection, code=19KB, data=28KB 
10-12 08:03:48.916 30409-30414/efp.android.sample I/art: After code cache collection, code=19KB, data=28KB 
10-12 08:03:48.916 30409-30414/efp.android.sample I/art: Increasing code cache capacity to 128KB 
10-12 08:03:48.982 30409-30422/efp.android.sample D/BluetoothGatt: onClientConnParamsChanged() - Device=F5:8E:C1:91:DC:CC interval=6 status=0 (I DONT THINK THIS SHOULD HAPPEN) 
10-12 08:03:49.688 30409-30421/efp.android.sample D/BluetoothGatt: onSearchComplete() = Device=F5:8E:C1:91:DC:CC Status=0 
10-12 08:03:49.689 30409-30421/efp.android.sample D/LAURASTAR_BLE: onServicesDiscovered: 
10-12 08:03:49.711 30409-30422/efp.android.sample D/BluetoothGatt: onClientConnParamsChanged() - Device=F5:8E:C1:91:DC:CC interval=36 status=0 
10-12 08:03:50.467 30409-31121/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=51 Status=0 
10-12 08:03:50.557 30409-30422/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=14 Status=5 (status NOT SUCCESS ...) 
10-12 08:03:50.830 30409-30422/efp.android.sample D/BluetoothGatt: onClientConnParamsChanged() - Device=F5:8E:C1:91:DC:CC interval=6 status=0 
10-12 08:03:51.533 30409-31121/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=14 Status=137 (status NOT SUCCESS ...) 
10-12 08:03:51.533 30409-31121/efp.android.sample D/LAURASTAR_BLE: Data is empty. (null) 
10-12 08:03:51.533 30409-31121/efp.android.sample D/BluetoothGatt: cancelOpen() - device: F5:8E:C1:91:DC:CC 
10-12 08:03:51.561 30409-30422/efp.android.sample D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=F5:8E:C1:91:DC:CC 
10-12 08:03:51.565 30409-30422/efp.android.sample D/LAURASTAR_BLE: onConnectionStateChange: 
10-12 08:03:51.565 30409-30422/efp.android.sample D/BluetoothAdapter: isSecureModeEnabled 
10-12 08:03:51.609 30409-31121/efp.android.sample D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=F5:8E:C1:91:DC:CC 
10-12 08:03:51.610 30409-31121/efp.android.sample D/LAURASTAR_BLE: onConnectionStateChange: 
10-12 08:03:51.610 30409-31121/efp.android.sample D/BluetoothGatt: discoverServices() - device: F5:8E:C1:91:DC:CC 
10-12 08:04:01.091 30409-31121/efp.android.sample D/BluetoothGatt: onSearchComplete() = Device=F5:8E:C1:91:DC:CC Status=0 
10-12 08:04:01.091 30409-31121/efp.android.sample D/LAURASTAR_BLE: onServicesDiscovered: 
10-12 08:04:02.048 30409-31121/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=51 Status=0 
10-12 08:04:02.438 30409-30421/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=14 Status=0 
10-12 08:04:02.829 30409-30421/efp.android.sample W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=23 Status=0 
10-12 08:04:02.898 30409-30414/efp.android.sample I/art: Do partial code cache collection, code=48KB, data=61KB 
10-12 08:04:02.899 30409-30414/efp.android.sample I/art: After code cache collection, code=48KB, data=61KB 
10-12 08:04:02.899 30409-30414/efp.android.sample I/art: Increasing code cache capacity to 256KB 
10-12 08:04:04.389 30409-30422/efp.android.sample D/BluetoothGatt: cancelOpen() - device: F5:8E:C1:91:DC:CC 
10-12 08:04:04.402 30409-30421/efp.android.sample D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=F5:8E:C1:91:DC:CC 
10-12 08:04:04.406 30409-30421/efp.android.sample D/LAURASTAR_BLE: onConnectionStateChange: 
10-12 08:04:04.502 30409-30409/efp.android.sample V/InputMethodManager: Starting input: [email protected] nm : efp.android.sample [email protected] 
10-12 08:04:04.502 30409-30409/efp.android.sample I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus 
10-12 08:04:04.503 30409-30409/efp.android.sample D/InputTransport: Input channel constructed: fd=70 
10-12 08:04:04.503 30409-30409/efp.android.sample D/InputTransport: Input channel destroyed: fd=73 
10-12 08:04:04.519 30409-30409/efp.android.sample D/BluetoothGatt: close() 
10-12 08:04:04.520 30409-30409/efp.android.sample D/BluetoothGatt: unregisterApp() - mClientIf=6 

在此日誌,這是可見的,successfuly閱讀第一特徵後:

W/BluetoothGatt: onCharacteristicRead() - Device=F5:8E:C1:91:DC:CC handle=14 Status=5 

然後onClientConnParamsChanged被discoverServices後稱爲()被調用,onServicesDiscovered前()被調用。

所有我的代碼似乎是正確的...... 因此,邏輯如下:

開始通過接收用戶所需的服務器的MAC地址,這樣應用程序可以掃描並找到它。

我有一個的EditText實現的TextWatcher,所以當用戶將MAC地址,應用程序查找具有插入地址BLE設備。

String macToFind = ""; 
private class ScanIronFieldsTextWatcher implements TextWatcher { 

    View view; 
    public ScanIronFieldsTextWatcher(View view) { this.view = view; } 

    @Override 
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} 

    @Override 
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} 


    public void afterTextChanged(Editable editable) { 

     switch (view.getId()) { 
      case R.id.txt_mac_address: { 
       String originalText = txtMacAddress.getText().toString().toUpperCase(); 
       String macToFind = Tools.getValidMacAddress(originalText); 
       if(mConnectedGatt != null && mConnectedGatt.getDevice().getAddress().equals(macToFind)) { 
        mConnectedGatt.connect(); 
       } 
       else { 
        if(mConnectedGatt != null) { 
         mConnectedGatt.close(); 
         mConnectedGatt = null; 
        } 

        //Search mac address 
        writeToActivityLog("Looking for " + macToFind +"...", LogAdapter.MESSAGE_TYPE_NORMAL); 
        hideKeyboard(); 
        startScan(); 
       } 
      } 
     } 
    } 
} 

用戶插入mac地址後,啓動startScan()。

startScan()

private void startScan() { 
     if (!mBluetoothAdapter.isEnabled()) { 
      writeToActivityLog("Bluetooth is off!", LogAdapter.MESSAGE_TYPE_ERROR); 
      return; 
     } 
     try { 
      ScanFilter scanFilter = new ScanFilter.Builder().setDeviceAddress(macToFind).build(); 
      ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>(); 
      filters.add(scanFilter); 

      ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(); 
      mBluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, mScanCallback); 


      retryingHandler = new Handler(); 
      retryingHandler.postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        showProgress(false); 
        stopScan(); 

        if (mDevices.size() == 0) { 
         writeToActivityLog("Server not found.", LogAdapter.MESSAGE_TYPE_ERROR); 
        } else { 
         mDevices.clear(); 
        } 
       } 
      }, SCAN_TIME); 
     } catch (IllegalArgumentException e) { 
      writeToActivityLog("Invalid Address!", LogAdapter.MESSAGE_TYPE_ERROR); 
     } 
    } 

mScanCallback:

private ScanCallback mScanCallback = new ScanCallback() { 
     @Override 
     public void onScanResult(int callbackType, ScanResult result) { 
      Log.d(TAG, "onScanResult"); 
      processResult(result); 
     } 

     @Override 
     public void onBatchScanResults(List<ScanResult> results) { 
      Log.d(TAG, "onBatchScanResults: "+results.size()+" results"); 
      for (ScanResult result : results) { 
       processResult(result); 
      } 
     } 

     @Override 
     public void onScanFailed(int errorCode) { Log.w(TAG, "LE Scan Failed: "+errorCode); } 

     private void processResult(final ScanResult result) { 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        if(mConnectedGatt == null) { 
         stopScan(); 
         final BluetoothDevice device = result.getDevice(); 
         mDevices.put(device.hashCode(), device); 

         writeToActivityLog("Server found!", LogAdapter.MESSAGE_TYPE_NORMAL); 
         writeToActivityLog("Connecting to " + macToFind + "...", LogAdapter.MESSAGE_TYPE_NORMAL); 

         mConnectedGatt = device.connectGatt(NewDeviceControlActivity.this, false, mGattCallback); 
         retryingHandler.removeCallbacksAndMessages(null); 
        } 
       } 
      }); 
     } 
    }; 

mGattCallback

private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { 
     @Override 
     public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 
      super.onConnectionStateChange(gatt, status, newState); 

      if (newState == BluetoothProfile.STATE_CONNECTED) { 
       writeToActivityLog("Connected.", LogAdapter.MESSAGE_TYPE_SUCCESS); 
       mConnected = true; 

       if(!gatt.discoverServices()) { 
        writeToActivityLog("Impossible discoverServices().", LogAdapter.MESSAGE_TYPE_ERROR); 
        if(!retrying) 
         retrying = true; 
        mConnectedGatt.disconnect(); 
       } 
      } 
      else if(newState == BluetoothProfile.STATE_DISCONNECTED) { 

       writeToActivityLog("Disconnected.", LogAdapter.MESSAGE_TYPE_NORMAL); 
       if(!currentIron.hasCompletedSetup()) { 
        showProgress(true); 

        if(retrying) { 
         writeToActivityLog("Trying again...", LogAdapter.MESSAGE_TYPE_NORMAL); 
         if(mConnectedGatt != null) 
          mConnectedGatt.connect(); 
        } 
        else { 
         writeToActivityLog("Trying again but also scanning again... (r)", LogAdapter.MESSAGE_TYPE_NORMAL); 
         retrying = false; 
         if(mConnectedGatt != null) 
          mConnectedGatt.close(); 
         mHandler.postDelayed(new Runnable() { 
          @Override 
          public void run() { 
           startScan(); 
          } 
         }, 2000); 
        } 
       } 
      } 
     } 

     @Override 
     public void onServicesDiscovered(final BluetoothGatt gatt, int status) { 
      super.onServicesDiscovered(gatt, status); 
      Log.d(TAG, "onServicesDiscovered:"); 

      mHandler.postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        startObtainingIronData(gatt); 
       } 
      }, 700); 
     } 

     @Override 
     public void onCharacteristicRead(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) { 
      super.onCharacteristicRead(gatt, characteristic, status); 


      byte[] data = characteristic.getValue(); 
      if(status != BluetoothGatt.GATT_SUCCESS) { 
       runOnUiThread(new Runnable() { @Override public void run() {Toast.makeText(NewDeviceControlActivity.this, ("BluetoothGatt: Response != GATT_SUCCESS ("+status+")."), Toast.LENGTH_SHORT).show();}}); 
      } 

      if (characteristic.getUuid().toString().contains(Iron.IRON_CODES[4])) { 
       //First characteristic read succesfully 
       final String version = new String(data); 
       runOnUiThread(new Runnable() { @Override public void run() {Toast.makeText(NewDeviceControlActivity.this, ("Version "+version), Toast.LENGTH_SHORT).show();}}); 

       //Request to read second characteristic 
       BluetoothGattCharacteristic characteristic2 = getCharacteristic(gatt, Iron.IRON_CODES[0]); 
       gatt.readCharacteristic(characteristic2); 
      } 
      else if (characteristic.getUuid().toString().contains(Iron.IRON_CODES[0])) { 
       //Read second characteristic 
       if(data == null || data.length == 0) { //returns with status=137 
        Log.d(TAG, "Data is empty " + (data == null ? "(null)" : data));//This ALWAYS happens except the first server the app connects too 
        writeToActivityLog("Data is empty. "+ (data == null ? "(null)" : data), LogAdapter.MESSAGE_TYPE_ERROR); 
        if(!retrying) 
         retrying = true; 
        mConnectedGatt.disconnect(); 
        return; 
       } 
       else { 
        if (data[2] == 4) { 
         //Request to read third characteristic 
         BluetoothGattCharacteristic characteristic2 = getCharacteristic(gatt, Iron.IRON_CODES[1]); 
         if(characteristic2 != null) 
          gatt.readCharacteristic(characteristic2); 
         else { 
          writeToActivityLog("Impossible readCharacteristic Machine Type" , LogAdapter.MESSAGE_TYPE_ERROR); 
          if(!retrying) 
           retrying = true; 

          mConnectedGatt.disconnect(); 
         } 
        } 
       } 
      } 
      else if (characteristic.getUuid().toString().contains(Iron.IRON_CODES[1])) { 
       //Read third characteristic 
       if(data[0] == 0) { 
        BluetoothGattCharacteristic characteristic2 = getCharacteristic(gatt, Iron.IRON_CODES[2]); 
        long now = System.currentTimeMillis(); 
        byte[] nowBytes = new byte[]{(byte) ((int) (now & 255L)), (byte) ((int) (now >> 8)), (byte) ((int) (now >> 16)), (byte) ((int) (now >> 24))}; 
        characteristic2.setValue(nowBytes); 

        writeToActivityLog("Read all information succesfully.", LogAdapter.MESSAGE_TYPE_NORMAL); 

        //Request to write first characteristic 
        if (!gatt.writeCharacteristic(characteristic2)){ 
         writeToActivityLog("Impossible to write timestamp.", LogAdapter.MESSAGE_TYPE_ERROR); 
         if(!retrying) 
          retrying = true; 
         mConnectedGatt.disconnect(); 
        } 

       } 
      } 
     } 

     @Override 
     public void onCharacteristicWrite(final BluetoothGatt gatt, BluetoothGattCharacteristic characteristic2, int status) { 
      super.onCharacteristicWrite(gatt, characteristic2, status); 

      if(status == BluetoothGatt.GATT_SUCCESS) { 
       showProgress(false); 

       if(characteristic2.getUuid().toString().contains(Iron.IRON_CODES[2])) { 

        //Wrote first characteristic 
        String intToWrite = "0x01"; 
        BluetoothGattCharacteristic characteristic = getCharacteristic(gatt, Iron.IRON_CODES[1]); 
        characteristic.setValue(Integer.decode(intToWrite), BluetoothGattCharacteristic.FORMAT_UINT8, 0); 

        //Request to write second characteristic 
        if (!gatt.writeCharacteristic(characteristic)) { 
         writeToActivityLog("Impossible to write first characteristic!.", LogAdapter.MESSAGE_TYPE_ERROR); 
         if(!retrying) 
          retrying = true; 
         mConnectedGatt.disconnect(); 
        } 
       } 
       else if(characteristic2.getUuid().toString().contains(Iron.IRON_CODES[1])) { 

         //Wrote second characteristic 
         service.sendData(), new Callback<String>() { 
            @Override 
            public void onResponse(Call<String> call, Response<String> response) { 

              //Write third characteristic 
              BluetoothGattCharacteristic characteristic = getCharacteristic(gatt, Iron.IRON_CODES[3]); 
              characteristic.setValue(0x40, android.bluetooth.BluetoothGattCharacteristic.FORMAT_UINT8, 0); 
              gatt.writeCharacteristic(characteristic); 


            } 
            @Override 
            public void onFailure(Call<String> call, Throwable t) { 

             if(mConnectedGatt != null) 
              mConnectedGatt.disconnect(); 
            } 
           }); 
         } 
       } 
       else if(characteristic2.getUuid().toString().contains(Iron.IRON_CODES[3])) { 
        //Wrote third characteristic 
        writeToActivityLog("Data written successfully.", LogAdapter.MESSAGE_TYPE_SUCCESS); 

        if(mConnectedGatt != null) 
         mConnectedGatt.disconnect(); 
       } 

      } 
     } 
    }; 

我有三編輯運行runOnUIThread中的所有mConnectedGatt操作,但具有相同的結果。所有特徵UUID都是正確的,並且正在寫入的特徵不是正在讀取的特徵。

我沒有GATT服務器遠離應用程序的問題,也沒有太多的問題。 我在三個三星Galaxy Tab A 10.1 2016上運行軟件,其中 都返回相同的結果。

所以我的成績基本上都是這些:

預計(只與第一服務器發生在應用程序連接到):

  • 尋找MAC
  • 服務器找到了!
  • 連接到MAC
  • 連接。
  • (讀出的第一特徵)版本:
  • (讀取第二特徵)
  • (讀第三特徵)
  • (寫第一特性)
  • (寫入第二特性)
  • (寫入第三特性)
  • 斷開連接。

會發生什麼(試圖連接到另一臺服務器):

  • 尋找MAC
  • 服務器找到了!
  • 連接到MAC
  • 連接。
  • (已讀第一個特徵)版本:
  • 數據爲空! (null)
  • 斷開連接。
  • 再試一次...
  • 連接。
  • (讀出的第一特徵)版本:
  • (讀取第二特徵)
  • (讀第三特徵)
  • (寫第一特性)
  • (寫入第二特性)
  • (寫入第三特性)
  • 斷開連接。

而我猜很多重新連接是什麼導致'藍牙已停止工作'。 我不明白爲什麼會發生這種情況!

請,如果有人可以花一些時間來幫助我弄清楚發生了什麼,我會如此感激... 謝謝

+1

您是否在項目中添加了一些新的ble服務?如果是可能的話,你可以嘗試清除藍牙緩存。進入設置 - >應用程序點擊右上角的更多圖標。點擊系統應用。從列表中選擇藍牙。清除存儲。 (有時它不會在第一時間清除緩存,點擊兩次到這個按鈕) 我希望它能夠解決問題 – hasbi

+0

@hasbi你是什麼意思的新ble服務? – Firecat

+0

我的意思是添加新的特徵 – hasbi

回答