程序化配对后,如何自动连接Android蓝牙设备

6

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

我有以下函数来配对设备:

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
    }
}

它向我显示对话框以配对设备并输入密码。

问题在于createBond函数总是返回true,并且它不等待我输入密码并与设备配对,因此我无法正确使用:

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

所以问题是如何与设备配对,当它配对后如何连接?
附注:我的代码基于以下线程的第一个答案:Android + Pair devices via bluetooth programmatically
1个回答

4
我来翻译一下:

我找到了解决方法。

首先,我需要一个像这样的 BroadcastReceiver

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方法(在问题中描述)并输入PIN码时,ACTION_BOND_STATE_CHANGED将触发,并且device.getBondState() == BluetoothDevice.BOND_BONDED将为True,然后它将连接。


1
你用了哪些方法来编程连接蓝牙设备?我知道如何编程配对,但在广播接收器中连接很困难。 - waylonion
为了进行SPP连接,我使用以下代码行:BluetoothDevice device = adapter.getRemoteDevice(mac); final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); out = socket.getOutputStream(); in = socket.getInputStream(); 其中adapterBluetoothAdapter的一个实例,mac是一个字符串。 - RdlP
为什么不直接使用mmSocket.connect()来连接和与另一个设备进行通信呢? - LiangWang
首先,我需要创建Socket对象,我使用第1、2和3行来创建socket对象,然后我使用socket.connect(); - RdlP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接