Android BLE:如何检查绑定的 BLE 设备是否可用于连接

Android BLE: How to check if bonded BLE Device is available to connect

我目前正在测试 BLE 的葡萄糖概况。为了获得血糖记录,必须首先绑定 BLE 血糖仪。绑定设备后,在执行 startLeScan.

时,我在 onLeScan 回调中不再获得此设备

不过,我可以使用 BluetoothAdapter.getDefaultAdapter().getBondedDevices();

获取所有绑定 BLE 设备的列表

现在我想过滤当前在 range/available 中的绑定设备。

要检查 range/available 中是否有设备,您需要扫描,因此这不是适合您的解决方案,因为您说由于某种原因未检测到它们。

因此,您可以尝试通过知道地址或名称直接连接到绑定设备。

    Set<BluetoothDevice> myBondedDevices = mBluetoothAdapter.getBondedDevices();
    String MAC = "your device Adress"
    for(BluetoothDevice mydevice:myBondedDevices ){
        Log.i("BondedInfo", MAC + "   " + mydevice.getAddress());
        if(mydevice.getAddress().equals(MAC)){
            mydevice.connectGatt(mycontext,true,mygattcallback);
            break;
        }

    }

或者最合适的近似值(根据我自己):

  • 实现检测绑定并在设备绑定完成时连接的广播接收器:

        BroadcastReceiver myServiceBroadcast = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    final int state=intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,BluetoothDevice.ERROR);
    
        switch(state){
            case BluetoothDevice.BOND_BONDING:
                Log.i("Bondind Status:"," Bonding...");
                break;
    
            case BluetoothDevice.BOND_BONDED:
                Log.i("Bondind Status:","Bonded!!");
                myBluetoothDevice.connectGatt(mycontext, true, myBluetoothGattCallBack);
                break;
    
            case BluetoothDevice.BOND_NONE:
                Log.i("Bondind Status:","Fail");
    
                break;
        }     
    };
    
  • 正确注册:

    registerReceiver(myServiceBroadcast,new IntenFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));