Android开发 获取系统已连接蓝牙设备

   根据公司最近一个项目的需求,我们的APP要与蓝牙低功耗设备进行连接,不过有些情况下系统蓝牙会默认连接已配对的设备,这样就会导致我们的APP搜索不到这些系统已连接的设备,从而导致APP无法与之进行连接并进行接下来的操作。其实系统连接与我们的APP连接并不冲突,问题就在于如何找到并显示出系统已连接的设备。网上搜索了一堆方法都不行,要么是只能找到已绑定的设备,要么就是操作无效。好在后来终于找到有人通过反射获取系统已连接设备的方法,特此记录,如果谁有更好的方法还请指教。

 
  1. BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

  2. Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象

  3. try {//得到连接状态的方法

  4. Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);

  5. //打开权限

  6. method.setAccessible(true);

  7. int state = (int) method.invoke(adapter, (Object[]) null);

  8.  
  9. if(state == BluetoothAdapter.STATE_CONNECTED){

  10. Log.i("BLUETOOTH","BluetoothAdapter.STATE_CONNECTED");

  11. Set<BluetoothDevice> devices = adapter.getBondedDevices();

  12. Log.i("BLUETOOTH","devices:"+devices.size());

  13.  
  14. for(BluetoothDevice device : devices){

  15. Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);

  16. method.setAccessible(true);

  17. boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);

  18. if(isConnected){

  19. Log.i("BLUETOOTH","connected:"+device.getName());

  20. deviceList.add(device);

  21. }

  22. }

  23. }

  24.  
  25. } catch (Exception e) {

  26. e.printStackTrace();

  27. }

转载连接:https://blog.csdn.net/gh8609123/article/details/66969006

猜你喜欢

转载自blog.csdn.net/yijiaodingqiankun/article/details/82587300