6

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

4

3 回答 3

3

我设法做到了 -在这里查看我的答案。

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

于 2016-07-19T13:23:49.910 回答
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");
               }
           }
       }
   };
于 2015-08-26T15:39:45.577 回答
-1

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

于 2015-08-06T16:29:21.290 回答