赞
踩
在做Android蓝牙开发过程中,发现虽然设备的蓝牙和定位权限都打开了,但是扫描不到设备(除非以前配对过)。只有进入蓝牙页面,才能被扫描搜索到。这个就涉及到蓝牙的可见性,为了保护隐私默认是不可见的,需要打开蓝牙可见性,才能被别的设备扫描搜索到。目前Android的API中没有直接设置蓝牙永久可见性的接口。有一个方法可以实现,不过会弹出一个确定的窗口:
- //启动修改蓝牙可见性的Intent
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- //设置蓝牙可见性的时间,方法本身规定最多可见300秒
- intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
- startActivity(intent);
查看BluetoothAdapter.setDiscoverableTimeout()源码,可以用反射的方法打开蓝牙可见性:
- public static void setDiscoverableTimeout() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- try {
- Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
- setDiscoverableTimeout.setAccessible(true);
- Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
- setScanMode.setAccessible(true);
- setDiscoverableTimeout.invoke(adapter, 0);
- setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 0);
- } catch (Exception e) {
- e.printStackTrace();
- Log.e("Bluetooth", "setDiscoverableTimeout failure:" + e.getMessage());
- }
- }
- 关闭可见性的方法:
-
- public static void closeDiscoverableTimeout() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- try {
- Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
- setDiscoverableTimeout.setAccessible(true);
- Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
- setScanMode.setAccessible(true);
- setDiscoverableTimeout.invoke(adapter, 1);
- setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE, 1);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }

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