【问题标题】:Programmatically bonding to BLE device on Android以编程方式绑定到 Android 上的 BLE 设备
【发布时间】:2015-10-29 18:42:35
【问题描述】:

我正在编写一个 Android 应用程序,我想在其中以编程方式绑定到自定义 BLE 设备。我有手动绑定工作,其中用户使用标准的 Android 蓝牙配对对话框输入 PIN,但我无法找到有关如何以编程方式自动绑定 BLE 设备的任何信息,而无需用户干预。那可能吗?如果有,流程是什么?

【问题讨论】:

    标签: android bluetooth bluetooth-lowenergy pairing


    【解决方案1】:

    要避免用户交互,您所能做的就是强制 Just Works 配对。为此,请对外围设备进行编程以接受与 NoInputNoOutput IO Capability 配对。

    【讨论】:

      【解决方案2】:

      我可以通过注册一个 BroadcastReceiver 来接收 BluetoothDevice.ACTION_BOND_STATE_CHANGED 意图,然后在收到 BluetoothDevice.BOND_BONDING 消息后调用 BluetoothDevice.setPin 来完成这项工作。与 Android 中大多数 BLE 的情况一样,这似乎略有不同,具体取决于设备和 Android 版本。不幸的是,我似乎无法阻止 Android 也接收蓝牙意图,因此在绑定完成之前,PIN 输入屏幕仍然会弹出一秒钟。

         private final BroadcastReceiver mReceiver = new BroadcastReceiver()
         {
             @Override
             public void onReceive(Context context, Intent intent)
             {
                 final String action = intent.getAction();
                 Logger("Broadcast Receiver:" + action);
      
                 if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
                 {
                     final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
      
                     if(state == BluetoothDevice.BOND_BONDING)
                     {
                         Logger("Bonding...");
                          if (mDevice != null) {
                              mDevice.setPin(BONDING_CODE.getBytes());
                              Logger("Setting bonding code = " + BONDING_CODE);
                          }
                     }
                     else if(state == BluetoothDevice.BOND_BONDED)
                     {
                         Logger("Bonded!!!");
                         mOwner.unregisterReceiver(mReceiver);
                     }
                     else if(state == BluetoothDevice.BOND_NONE)
                     {
                         Logger("Not Bonded");
                     }
                 }
             }
         };
      

      【讨论】:

      【解决方案3】:

      我设法做到了 - 请参阅我的回答 here

      TL;DR 是:忘记ACTION_BOND_STATE_CHANGED;你不需要它。而是收听ACTION_PAIRING_REQUEST,然后将优先级设置为高。在广播接收器中,当您收到ACTION_PAIRING_REQUEST 时,使用您的 PIN 码拨打setPin(),然后拨打abortBroadcast(),以防止系统显示通知。

      【讨论】:

        猜你喜欢
        • 2016-10-29
        • 2017-12-30
        • 2011-05-31
        • 1970-01-01
        • 2023-04-05
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多