繁体   English   中英

Android蓝牙:配对设备列表

[英]Android bluetooth: Paired devices list

我有一个带SPP配置文件和蓝牙版本2.1的蓝牙设备。
我有一个连接到该设备并与之通信的应用程序。 该设备使用“Just Works”配对技术。

我在某些手机上遇到问题,如三星Galaxy平板电脑,Galaxy S.

问题是在用户退出应用程序后,我正在关闭套接字并断开与设备的连接。 成功断开连接后,会发现设备的条目已从配对设备列表中删除。

我没有使用平板电脑,但我确实编写了一个使用SPP for Android手机的应用程序。 我发现,为了使蓝牙稳定,我必须手动绑定我想要与之通信的设备。 我们使用下面的代码从应用程序中启动绑定,它应该保留绑定,就像您通过设置菜单手动配对一样。

以下是一般流程:1)注册BroadcastReceiver以监听BluetoothDevice.ACTION_BOND_STATE_CHANGED
2)设备发现后,您应该有一个BluetoothDevice对象。
3)使用反射在BluetoothDeviceObject上调用'createBond'方法
3a)在打开插座之前等待粘合状态改变事件

BluetoothDevice device = {obtained from device discovery};
Method m = device.getClass().getMethod("createBond", (Class[])null);
m.invoke(device, (Object[])null);

int bondState = device.getBondState();
if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDING)
{
    waitingForBonding = true; // Class variable used later in the broadcast receiver

    // Also...I have the whole bluetooth session running on a thread.  This was a key point for me.  If the bond state is not BOND_BONDED, I wait here.  Then see the snippets below
    synchronized(this)
    {
        wait();
    }
}

4)等待债券状态从BOND_BONDING变为BOND_BONDED

在BroadcastReciever中:

public void onReceive(Context context, Intent intent)
{
    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction()))
    {
        int prevBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
        int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);

        if (waitingForBonding)
        {
            if (prevBondState == BluetoothDevice.BOND_BONDING)
            {
                // check for both BONDED and NONE here because in some error cases the bonding fails and we need to fail gracefully.
                if (bondState == BluetoothDevice.BOND_BONDED || bondState == BluetoothDevice.BOND_NONE)
                {
                    // safely notify your thread to continue
                }
            }
        }
    }
}

5)打开插座并进行通信

你也可以通过反射'removeBond'方法从配对列表中删除你的设备。

希望这可以帮助!

如果由于您的应用程序连接而发生配对,我猜测某些设备会将其视为临时配对,并且在断开连接后不会将设备保留在配对列表中。 要将设备保留在配对列表中,您应手动配对蓝牙设置菜单。 配对后,您的程序可以连接/断开连接,设备将保留在配对列表中。

我也遇到了与索尼Xperia X10相同的问题。 我设法通过改变蓝牙设备端的安全级别设置来“记住”配对(因为我也正在开发设备)。

我不确定“临时配对”的解释,这将取决于制造商,不同的是,不同的手机对同一设备的连接会有不同的反应。

然而,对我来说,这是一个无问题的部分。 通常,当用户在后台连接应用程序时取消配对设备时,蓝牙堆栈似乎会崩溃。 我还没弄清楚如何正确管理ACTION_BOND_STATE_CHANGED事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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