在Android中没有提示的蓝牙发现

sha*_*anu 3 android bluetooth

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

boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
    return bluetoothAdapter.enable();
} else if (!enable && isEnabled) {
    return bluetoothAdapter.disable();
}
Run Code Online (Sandbox Code Playgroud)

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

更多信息

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

sha*_*anu 10

最后,我找到了一种使用反射做到这一点的方法.

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();
}
Run Code Online (Sandbox Code Playgroud)

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