连接已配对的蓝牙设备

问题描述 投票:3回答:1

最近我尝试以编程方式进行配对过程,然后我成功了。但我最近发现我的应用程序的用户可以连接到几个“有趣”的设备。所以我必须提示用户选择要连接的设备

所以我必须将用户连接到已经配对的蓝牙设备。但我的努力都没有奏效。我尝试使用以下命令再次运行配对过程:

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

以及以下内容:

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

这是我实施的那个,也是我的手机与嵌入式蓝牙设备配对的唯一工作方式

所以我的问题是:

  • 我可以断开配对设备然后连接到另一个嵌入式设备吗?我试过......只是连接到新设备,但我无法让它工作
android android-bluetooth pairing
1个回答
2
投票

我担心我不完全确定你的问题是什么。您是否无法为已配对的蓝牙设备创建套接字?

首先,如果设备已配对,则无需再次运行配对过程。您只需要创建用于通信的套接字,如果设备无法与之通信,则会失败。我最近一直在做一些事情,我使用了以下代码,这对我来说很好:

    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
    }

为了提示用户选择哪个设备,您可以在BluetoothAdapter中查询所有当前配对的设备,如下所示:

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

最后,可以同时创建与多个设备的连接 - 请看一下:Android Bluetooth API connect to multiple devices

© www.soinside.com 2019 - 2024. All rights reserved.