[英]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.