在做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();
}
}
经过测试可以搜索到蓝牙了。