[英]Android: How do I connect to a hidden Bluetooth device?
我有一个隐藏的蓝牙设备,但是我知道它的蓝牙MAC地址。
如何使用Android连接到该设备?
从这里的文档中: http : //developer.android.com/reference/android/bluetooth/BluetoothDevice.html
要获取BluetoothDevice,请使用BluetoothAdapter.getRemoteDevice(String)创建一个代表已知MAC地址的设备。
连接到它之后,就好像您是通过设备发现来检索它一样。
我这样做是这样的:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("Some_MAC");
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
mBluetoothAdapter.cancelDiscovery();
Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int sdk = Integer.parseInt(Build.VERSION.SDK);
if(sdk >= 10){
//sdk 2.3?? java.io.IOException: Connection refused
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
}else {
tmp = device.createRfcommSocketToServiceRecord(uuid);
}
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
tmp.connect();
} catch (IOException e) {
Log.e(TAG, "failed: ", e);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.