【问题标题】:Reaction to Bluetooth Pairing dialog input对蓝牙配对对话框输入的反应
【发布时间】:2015-02-23 08:12:30
【问题描述】:

我正在开发一个通过蓝牙将 android 设备与另一个设备(CAN 模块)连接的应用程序。

我像这样配对以前未配对的设备:

Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);

这就像一个魅力。

但是有一个问题。 CAN 模块的设置方式不需要引脚或任何其他形式的配对确认,您只需说您想与设备配对,它就会这样做。现在,如果我的应用尝试连接到不是 CAN 模块的蓝牙设备(例如手机)会发生什么?

在这种情况下,会出现一个对话框,要求用户确认配对。我不介意对话框,但我想以某种方式对“取消”按钮做出反应。

总结一下: 当用户在蓝牙配对确认对话框上按下Cancel 时,我想调用方法doSomething()。这可能吗?

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

    你应该听ACTION_BOND_STATE_CHANGED Intent(希望你知道如何注册BroadcastReceiver并使用它们)。

    在系统(BluetoothService)广播的动作之上,它还包含Current Bond StatePrevious Bond State

    共有三种债券状态。

    BOND_BONDED 表示远程设备已绑定(配对)。

    BOND_BONDING 表示正在与远程设备进行绑定(配对)。

    BOND_NONE 表示远程设备未绑定(配对)。

    在您的情况下,您将收到BOND_BONDING >> BOND_NONE(如果密码对话框上的取消按钮)和BOND_BONDING >> BOND_BONDED(密码对话框上的配对按钮)

    【讨论】:

    • 太好了,我自己想出来的,但这是一个很好的答案。
    • @DodgerThud 是的,我在下面看到了你的答案,对不起,我花了一些时间来写答案并提供链接,以使答案切中要害。
    • 使用 BOND_NONE,我们是否能够区分用户按下取消键和用户输入错误的 pin 或发生其他故障?
    【解决方案2】:

    我找到了这个Question 的解决方案/解决方法。

    要对用户取消配对请求做出反应,我们需要查找以下操作:BluetoothDevice.ACTION_BOND_STATE_CHANGED 以及设备的绑定状态通过EXTRA_BOND_STATE

    这是一个例子:

    private void pairDevice(BluetoothDevice device){
            try{
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                ctx.registerReceiver(receiver, filter);
    
                Method m = device.getClass().getMethod("createBond", (Class[]) null);
                m.invoke(device, (Object[]) null);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    

    在您的广播接收器中

    public void onReceive(Context context, Intent intent){
        String action = intent.getAction();
        if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED){
            int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
    
            if(state < 0){
                //we should never get here
            }
            else if(state == BluetoothDevice.BOND_BONDING){
                //bonding process is still working
                //essentially this means that the Confirmation Dialog is still visible
            }
            else if(state == BluetoothDevice.BOND_BONDED){
                //bonding process was successful
                //also means that the user pressed OK on the Dialog
            }
            else if(state == BluetoothDevice.BOND_NONE){
                //bonding process failed
                //which also means that the user pressed CANCEL on the Dialog
                doSomething(); //we can finally call the method
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 2015-02-14
      • 2016-09-14
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多