简体   繁体   中英

Android: How do I connect to a hidden Bluetooth device?

I have a hidden bluetooth device, but I know the Bluetooth MAC address of it.

How can I use Android to connect to that device?

From the doc here : http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html

To get a BluetoothDevice, use BluetoothAdapter.getRemoteDevice(String) to create one representing a device of a known MAC address

After you just connect to it as if you had retrieved it through a device discovery.

I did it like this:

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();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM