android开发获取手机已连接的蓝牙设备(包括已链接的设备和已经配对绑定的设备)

在应用开发中有时会碰到操作蓝牙设备的需求,这时就需要获取手机已连接的蓝牙设备,其中"已连接"是广泛含义,其实蓝牙设备分为可链接设备(比如:蓝牙音箱 蓝牙耳机) 和可绑定设备(比如:手机 蓝牙自拍杆 蓝牙手表 蓝牙键盘等设备) 其中的区别就是connected状态,用int表示其区别共有三个值 10表示无绑定也无链接  11表示绑定 12表示链接。

如果通过标准协议api获取已连接的设备由于其实现机制返回结果会比较慢,可通过如下反射方式来获取:

//获取已连接的蓝牙设备
private void getConnectedBtDevice(){
    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){ //根据状态来区分是已连接的还是已绑定的,isConnected为true表示是已连接状态。
                    Log.i("BLUETOOTH-dh","connected:"+device.getName());
                    //deviceList.add(device);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值