Android 以编程方式配对后自动连接蓝牙设备

2023-11-23

在我的应用程序中,我需要配对蓝牙设备并立即与其连接。

我有以下功能来配对设备:

public boolean createBond(BluetoothDevice btDevice)
{
    try {
        Log.d("pairDevice()", "Start Pairing...");
        Method m = btDevice.getClass().getMethod("createBond", (Class[]) null);
        Boolean returnValue = (Boolean) m.invoke(btDevice, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
        return returnValue;

    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
    return false;
}

我按以下方式使用它:

Boolean isBonded = false;
try {
    isBonded = createBond(bdDevice);
    if(isBonded)
    {
         //Connect with device
    }
}

它向我显示了配对设备并输入 PIN 码的对话框。

问题是 createBond 函数总是返回 true,并且它会等到我输入引脚并与设备配对,所以我没有正确使用:

isBonded = createBond(bdDevice);
if(isBonded) {...}

所以问题是如何与设备配对以及配对后如何连接到它?

P.D 我的代码基于以下线程的第一个答案:Android + 以编程方式通过蓝牙配对设备


我找到了解决方案。

首先我需要一个BroadcastReceiver like:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                // CONNECT
            }
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Discover new device
        }
    }
};

然后我需要按如下方式注册接收器:

IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(myReceiver, intentFilter);

通过这种方式,接收器正在监听ACTION_FOUND(发现新设备)和ACTION_BOND_STATE_CHANGED(设备更改其绑定状态),然后我检查新状态是否为BOND_BOUNDED如果是我连接设备。

现在当我打电话时createBond方法(问题中描述)并输入密码,ACTION_BOND_STATE_CHANGED会开火并且device.getBondState() == BluetoothDevice.BOND_BONDEDTrue它将连接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 以编程方式配对后自动连接蓝牙设备 的相关文章

随机推荐