android - 如何在android中更改蓝牙适配器的扫描模式?

标签 android android-intent bluetooth discoverability

目前我正在开发一个蓝牙应用程序,我需要通过单击按钮将扫描模式从 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/

相关文章:

android - IllegalStateException 与 ListActivity

android - android "nexus 7"2013 的哪个版本的 adb 接口(interface)

java - 将值插入 Sqlite 数据库。安卓

android - REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 触发但无提示

android - 将模型对象传递给另一个 Activity

java - 通过 Java Android 撰写电子邮件 - 尝试定位设备管理客户端

android - 后台扫描中的华为蓝牙行为

Android 市场 - 在没有蓝牙的情况下无法在特定设备上找到应用程序

android - 修改蓝牙聊天示例代码以连接非安卓设备

android - J2MEPolish 是否有将 J2ME 应用程序转换为 Android 的基准测试?