android - 以编程方式绑定(bind)到 Android 上的 BLE 设备

标签 android bluetooth bluetooth-lowenergy pairing

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

最佳答案

通过注册 BroadcastReceiver 以接收 BluetoothDevice.ACTION_BOND_STATE_CHANGED Intent ,然后在接收到 BluetoothDevice.BOND_BONDING 消息后调用 BluetoothDevice.setPin,我能够在大部分时间完成这项工作。与 Android 中的大多数 BLE 事物一样,这似乎根据设备和 Android 版本的不同而略有不同。不幸的是,我似乎无法阻止 Android 也接收蓝牙 Intent ,因此在绑定(bind)完成之前 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");
               }
           }
       }
   };

关于android - 以编程方式绑定(bind)到 Android 上的 BLE 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858774/

相关文章:

android - 在android firebase中获取父节点

javascript - 在 Tizen Wearable 上设置蓝牙监听器

ios6 - 如何使用BluetoothManager正确连接Accessory?

android - BluetoothGatt.writeCharacteristic() 总是返回 false。

android - 如何通过 BLE 100 字节做广告?

android - 在 Presentation Display 中使用演示文稿上下文显示 Toast 消息

android - react-native scrollview 不滚动

Android:没有 "peripheral” 角色的 BLE?

java - 在 Robolectric 上运行第一个测试时出现问题

C# Monotouch/Xamarin - iOS 蓝牙连接到多部手机?