在应用开发中有时会碰到操作蓝牙设备的需求,这时就需要获取手机已连接的蓝牙设备,其中"已连接"是广泛含义,其实蓝牙设备分为可链接设备(比如:蓝牙音箱 蓝牙耳机) 和可绑定设备(比如:手机 蓝牙自拍杆 蓝牙手表 蓝牙键盘等设备) 其中的区别就是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();
}
}