【问题标题】:BLE - First connection with app is not workingBLE - 与应用程序的第一次连接不起作用
【发布时间】:2019-03-04 08:15:55
【问题描述】:

我正在使用设备 Texas,在我的自定义 Android 应用中管理 LED。设备已启用与默认密码000000 的配对。在我的应用程序代码中,我有这部分代码用于读取配对的设备。

    private void getpaireddevices(){
    Set<BluetoothDevice> devicesArray = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    if(devicesArray.size() > 0) {
        for(BluetoothDevice device : devicesArray) {
            device.getName();
            device.getAddress();
        }
    }
}

此时,当我启用 BLE 时,应用程序找到了设备,它可以连接但无法正常工作。为此,我应该退出并重新连接我的设备。为什么?

【问题讨论】:

    标签: android bluetooth-lowenergy texas-instruments


    【解决方案1】:

    如果设备已经绑定,这是可能的。调用removeBond()方法清除之前的绑定状态。

    device.removeBond();
    

    要检查蓝牙设备的绑定状态,请使用getBondState()

    Ble gatt 连接成功率因设备而异。如果您的连接连续失败,您可能需要通过隐藏的方法断开连接。

    请阅读: BLE Device Bonding Remove Automatically in Android

    unpairDevice()方法会解除蓝牙连接。

    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    
    for (BluetoothDevice bt : pairedDevices) {
            if (bt.getName().contains("String you know has to be in device name")) {
                unpairDevice(bt);
            }
    }
    
    // Function to unpair from passed in device
    private void unpairDevice(BluetoothDevice device) {
        try {
    
            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) { Log.e(TAG, e.getMessage()); }
    }
    

    【讨论】:

    • 嗨,斯坦利,如果我使用你写的这个......我应该在每次我想与设备连接时配对。对吗?
    • @MarioCas 嗯,是的。哦,你在使用 ble gatt 连接吗?你希望它始终保持连接吗?
    • 您似乎需要等到您的设备准备好进行通信。我建议你在运行你的代码之前给一些延迟(可能是 3 秒?)。
    • 好的,完美。抱歉@Stanley Kou,我发现了另一个问题。如果我用我的三星 S8 测试我的应用程序,它运行得非常好。如果我用另一部智能手机三星 A8 测试该应用程序,我就会遇到问题。我点击连接,连接,它不起作用。我出去重新连接并要求我进行另一个配对。什么可能导致这种情况?
    • @MarioCas 欢迎来到硬件世界!!!每个硬件都有自己的特点。这可能不是所有三星 A8 的问题。一定是设备的问题。你能把你的 A8 设备换成另一台 A8 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2019-12-20
    • 2019-02-21
    • 1970-01-01
    • 2022-10-12
    • 2018-09-12
    • 2014-11-03
    相关资源
    最近更新 更多