根据公司最近一个项目的需求,我们的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(); -
}
转载连接:https://blog.youkuaiyun.com/gh8609123/article/details/66969006

本文介绍了一种通过反射机制获取已连接蓝牙设备的方法,解决了APP无法显示系统已连接蓝牙设备的问题。利用BluetoothAdapter类的反射调用,可以获取到当前已连接的蓝牙设备列表。
1万+

被折叠的 条评论
为什么被折叠?



