当前位置:   article > 正文

android只有进入蓝牙页面才能被扫描搜索到的解决办法_setdiscoverabletimeout

setdiscoverabletimeout

 在做Android蓝牙开发过程中,发现虽然设备的蓝牙和定位权限都打开了,但是扫描不到设备(除非以前配对过)。只有进入蓝牙页面,才能被扫描搜索到。这个就涉及到蓝牙的可见性,为了保护隐私默认是不可见的,需要打开蓝牙可见性,才能被别的设备扫描搜索到。目前Android的API中没有直接设置蓝牙永久可见性的接口。有一个方法可以实现,不过会弹出一个确定的窗口:

  1. //启动修改蓝牙可见性的Intent
  2. Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  3. //设置蓝牙可见性的时间,方法本身规定最多可见300
  4. intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  5. startActivity(intent);


查看BluetoothAdapter.setDiscoverableTimeout()源码,可以用反射的方法打开蓝牙可见性:

  1. public static void setDiscoverableTimeout() {
  2.     BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  3.     try {
  4.         Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
  5.         setDiscoverableTimeout.setAccessible(true);
  6.         Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
  7.         setScanMode.setAccessible(true);
  8.         setDiscoverableTimeout.invoke(adapter, 0);
  9.         setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
  10.     } catch (Exception e) {
  11.         e.printStackTrace();
  12.         Log.e("Bluetooth", "setDiscoverableTimeout failure:" + e.getMessage());
  13.     }
  14. }
  15. 关闭可见性的方法:
  16. public static void closeDiscoverableTimeout() {
  17.     BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  18.     try {
  19.         Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
  20.         setDiscoverableTimeout.setAccessible(true);
  21.         Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
  22.         setScanMode.setAccessible(true);
  23.         setDiscoverableTimeout.invoke(adapter, 1);
  24.         setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE, 1);
  25.     } catch (Exception e) {
  26.         e.printStackTrace();
  27.     }
  28. }


  经过测试可以搜索到蓝牙了。
————————————————
版权声明:本文为CSDN博主「HiWorldNice」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/pbm863521/article/details/113415616

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/956077
推荐阅读
相关标签
  

闽ICP备14008679号