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

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

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

   根据公司最近一个项目的需求,我们的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.youkuaiyun.com/gh8609123/article/details/66969006

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值