Android开发 获取系统已连接蓝牙设备

    根据公司最近一个项目的需求,我们的APP要与蓝牙低功耗设备进行连接,不过有些情况下系统蓝牙会默认连接已配对的设备,这样就会导致我们的APP搜索不到这些系统已连接的设备,从而导致APP无法与之进行连接并进行接下来的操作。其实系统连接与我们的APP连接并不冲突,问题就在于如何找到并显示出系统已连接的设备。网上搜索了一堆方法都不行,要么是只能找到已绑定的设备,要么就是操作无效。好在后来终于找到有人通过反射获取系统已连接设备的方法,特此记录,如果谁有更好的方法还请指教。

 

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {//得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(adapter, (Object[]) null);

            if(state == BluetoothAdapter.STATE_CONNECTED){
                Log.i("BLUETOOTH","BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = adapter.getBondedDevices();
                Log.i("BLUETOOTH","devices:"+devices.size());

                for(BluetoothDevice device : devices){
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if(isConnected){
                        Log.i("BLUETOOTH","connected:"+device.getName());
                        deviceList.add(device);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值