目前我正在开发一个蓝牙应用程序,我需要通过单击按钮将扫描模式从 SCAN_MODE_CONNECTABLE_DISCOVERABLE
更改为 SCAN_MODE_CONNECTABLE
。
我使用以下 Intent 将其设置为可发现:
Intent discoverableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent .putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISOVERABLE_DURATION);
startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT);
我设置的位置DISOVERABLE_DURATION=300
;
现在我想跳过中间的可发现性,只想将其状态更改为 SCAN_MODE_CONNECTABLE
。
请给我一个合适的解决方案../
最佳答案
嗯,这是一个相当老的问题,但是您可以在没有用户许可的情况下切换蓝牙的扫描模式,并且(据我测试)无限时间。 这需要在 Android API 上使用反射,因此这不是官方 api。当然,您使用它的风险由您自己承担:) 下面是我用来使 BT 适配器可发现的代码:
private boolean setBluetoothScanMode(int scanMode){
Method method = null;
final BluetoothAdapter btAdapter = btManager.getAdapter();
if(!btAdapter.isEnabled()){
Log.d(LCAT, "BT adapter is off, turning on");
btAdapter.enable();
}
try {
method = btAdapter.getClass().getMethod("setScanMode", int.class);
} catch (SecurityException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
}
try {
method.invoke(btAdapter, scanMode);
} catch (IllegalArgumentException e) {
return false;
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
}
return true;
}
您还需要权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
此设备应处于扫描模式后,您可以通过传递 int scanMode 参数来选择。它正在 Android API 23 上运行。
关于android - 如何在android中更改蓝牙适配器的扫描模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14723790/