0

試圖創建一個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,但無法找到任何東西。

任何幫助,非常感謝。

+0

當您啓動該寫入嘗試時,您是否正在進行的尚未完成的GATT操作? – Emil

+0

我確定沒有尚未完成的GATT操作。我最初的懷疑是android-studio運行源代碼與我的設備上的代碼不同。結果是這樣。我創建了一個新項目(使用api 22和android 5.1.1)將所有代碼複製到那裏。現在它工作正常。謝謝您的幫助。 – tharun

回答

0

我確定沒有尚未完成的GATT操作。我最初的懷疑是android-studio運行源代碼與我的設備上的代碼不同。因此,在調試模式下運行的代碼與僅在設備上運行的代碼不同。 原來這是事實。我創建了一個新項目(使用api 22和android 5.1.1)將所有代碼複製到那裏。現在它工作正常。

相關問題