我正在编写一个Android应用程序,我希望以编程方式绑定到自定义BLE设备。我有手动绑定工作,用户使用标准的Android蓝牙配对对话框输入PIN,但我无法找到任何有关如何以编程方式自动绑定BLE设备的信息,无需用户干预。那可能吗?如果是的话,这个过程是什么?
答案 0 :(得分: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");
}
}
}
};
答案 1 :(得分:1)
我设法做到了 - 请参阅我的回答here。
TL; DR是:忘记ACTION_BOND_STATE_CHANGED
;你不需要它。而是听ACTION_PAIRING_REQUEST
,设置优先级。在收到ACTION_PAIRING_REQUEST
时,在广播接收器中,使用您的个人识别码setPin()
然后abortBroadcast()
来阻止系统显示通知。
答案 2 :(得分:-1)
您可以做的就是强制Just Works配对以避免用户交互。为此,请对外设进行编程,以接受与NoInputNoOutput IO Capability的配对。