Android蓝牙低功耗(BLE):如何检查已配对的BLE设备是否可连接

4

我目前正在测试BLE的葡萄糖剖面。为了获取葡萄糖记录,必须首先绑定BLE葡萄糖仪。设备绑定后,在执行startLeScan时,我无法再通过onLeScan回调函数获取此设备。

然而,我可以使用BluetoothAdapter.getDefaultAdapter().getBondedDevices();获取所有已绑定的BLE设备列表。

现在,我想对已绑定的设备进行过滤,以筛选出当前处于范围内/可用的设备。

1个回答

4

要检查是否有设备处于范围内/可用,您需要进行扫描,因此,鉴于您说它们由于某种原因未被检测到,这不是您的解决方案。

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

    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;
        }

    }

或者根据我的观点,最合适的近似值:

  • Implement a broadcast receiver that detect bonding and connect when the device bonding is complete:

        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;
        }     
    };
    
  • Register it properly:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接