获取当前链接的蓝牙设备
目前Android提供的API只能获取已经链接的设备,但是不能获取当前蓝牙链接的设备。
利用反射可以获取当前蓝牙连接的设备,跟去getBondedDevices获取已绑定的蓝牙连接,然后遍历BluetoothDevice,同样利用反射的方法调用BluetoothDevice的isConnected方法。成功获取。代码如下:
BluetoothAdapter _bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
void initBlue () throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
//得到蓝牙状态的方法
Method method = bluetoothAdapterClass.getDeclaredMethod(“getConnectionState", (Class[]) null);
//打开权限
method.setAccessible(true);
int state = (int) method.invoke(_bluetoothAdapter, (Object[]) null);
if (state == BluetoothAdapter.STATE_CONNECTED) {
Set<BluetoothDevice> devices = _bluetoothAdapter.getBondedDevices();
Log.d("LUYU", "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.d(“LUYU”, “connected:”+device.getName());
//return device.getAddress();
}
}
}else {
Log.d(“LUYU”, “initBlue: “);
}
}