gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:15:30 27 4
gpt4 key购买 nike

我正在编写一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com