Android

时间:2015-05-14 19:44:32

标签: android bluetooth

我可以使用以下代码在没有任何提示的情况下打开/关闭蓝牙。它需要BLUETOOTHBLUETOOTH_ADMIN权限。

boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
    return bluetoothAdapter.enable();
} else if (!enable && isEnabled) {
    return bluetoothAdapter.disable();
}

但是没有找到任何方法可以在没有用户提示的情况下设置蓝牙。每次都向用户提示它。我害怕没有“不要再问我”的功能了。有没有什么好方法可以让蓝牙设备被发现?我不关心持续时间。我的设备也没有扎根。

更多信息

我找到了BluetoothAdapter.java的源代码,它有一个名为setDiscoverableDuration的公共方法。但为什么我无法访问它?为什么在Api文档中隐藏了一些公共方法?他们是怎么做到的?所有方法都是公开的。

1 个答案:

答案 0 :(得分:9)

最后,我找到了一种使用反射的方法。

Method method;
try {
    method = bluetoothAdapter.getClass().getMethod("setScanMode", int.class, int.class);
    method.invoke(bluetoothAdapter,BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,120);
    Log.e("invoke","method invoke successfully");
}
catch (Exception e){
    e.printStackTrace();
}

警告:上面的方法是尝试调用隐藏方法。所以将来也许它不会起作用。