Connecting to a already paired Bluetooth device

*爱你&永不变心* 提交于 2019-11-30 13:10:20

问题


Recently I tried to get a pairing process to work programatically and I succeded. But I recently found out that the users of my application can be connected to several of "interesting" devices. So I have to prompt the user to choose a device to connect to

So I have to connect the user to a already paired bluetooth device. But none of my efforts work. I tried running the pairing process again using the:

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

and also the following:

Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);

which is the one I've implemented and the only working way to pair my phone with my embedded bluetooth device

So my question is:

  • Is it possible for me to disconnect a paired device and then connect to another embedded device? I tried.. to simply connect to the new device but I can't get that to work

回答1:


I'm afraid I'm not entirely sure what your problem is. Is it that you are unable to create a socket to an already paired bluetooth device?

First of all, if the device is already paired, you don't need to run the pairing process again. You just need to create the socket for communication, which will fail if the device is not available to communicate with. I've been doing some stuff around this lately and I've used the following code, which has worked fine for me:

    try {
        Method m = device.getClass().getMethod("createRfcommSocket",
                new Class[] { int.class });
        BluetoothSocket mySocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));

    } catch (<VARIOUS EXCEPTIONS>) {
        //Do stuff
    }

For prompting the user to select which device, you can query the BluetoothAdapter for all the currently paired devices as follows:

Set<BluetoothDevice> bondedDevices = BluetoothAdapter
            .getDefaultAdapter().getBondedDevices();

Finally, it is possible to create connections to multiple devices at the same time - have a look here: Android Bluetooth API connect to multiple devices



来源:https://stackoverflow.com/questions/6760102/connecting-to-a-already-paired-bluetooth-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!