我正在尝试检测蓝牙设备当前是否连接到使用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