我正在嘗試檢測藍牙設備當前是否連接到使用API 14或更高版本的Android設備。看起來我應該可以使用BluetoothSocket.isConnected()方法,但無論我做了什麼,到目前爲止,我只是爲了任何東西,連接或不連接而返回假。Android BluetoothSocket.isConnected總是返回false
AndroidManifest包括這些行:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- Locale 4.x supports API 14 or greater. -->
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />
<uses-feature android:name="android.hardware.bluetooth" />
,問題中的代碼:
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
Log.i(Constants.LOG_TAG, String.format(Locale.US, "Device: %s connected: %b", device.getName(), isConnected(device))); //$NON-NLS-1$z
}
}
private boolean isConnected(BluetoothDevice device) {
BluetoothSocket socket = null;
// Get a BluetoothSocket for a connection with the given BluetoothDevice
UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
Log.e(Constants.LOG_TAG, e.getMessage()); //$NON-NLS-1$z
return false;
}
Log.i(Constants.LOG_TAG, socket.toString()); //$NON-NLS-1$z
return socket.isConnected();
}
不會引發任何錯誤,它只是返回 「假」 的時間100%。有沒有我不擅長的事情?
反射部分來自這個問題的接受答案:http://stackoverflow.com/questions/3397071/service-discovery-failed-exception-using-bluetooth-on-android。我對反思的想法並不感到激動,但我想我記得在別的地方讀過,你不應該依賴原始問題中的UUID。 話雖如此,對我來說重要的問題是你的答案的第二部分 - 我試圖找到任何連接的BT設備,而不是試圖連接任何我自己。這不可能嗎?我試圖避免必須創建一個服務來監視BT狀態的變化。 – jkane001 2013-02-10 00:05:25
Ameen說得對,經過對SO答案和Android文檔的更仔細的閱讀後,我意識到在這裏沒有必要進行反思。我用一個更好的「isConnected」方法更新了我的原始問題,但我的問題仍然存在:有沒有辦法檢測BT設備是否連接而不連接它? – jkane001 2013-02-10 00:17:22