android 获取手机蓝牙是否与其他设备蓝牙配对连接成功,android开发获取手机已连接的蓝牙设备(包括已链接的设备和已经配对绑定的设备)...

本文介绍如何在Android应用开发中利用反射API提升效率,获取蓝牙设备的连接状态(包括是否绑定和链接),并区分10(无绑定无链接)、11(绑定)和12(链接)的不同情况。通过实例演示了如何通过`BluetoothAdapter`和`BluetoothDevice`类的反射方法获取和解析设备状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

//获取已连接的蓝牙设备

private void getConnectedBtDevice(){

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

ClassbluetoothAdapterClass = 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");

Setdevices = 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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值