Android 中没有提示的蓝牙发现
Bluetooth discovery without prompt in Android
我可以使用以下代码在没有任何提示的情况下打开 on/off 蓝牙。它需要 BLUETOOTH
和 BLUETOOTH_ADMIN
权限。
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
} else if (!enable && isEnabled) {
return bluetoothAdapter.disable();
}
但没有找到任何方法来设置蓝牙在没有用户提示的情况下可发现。它每次都会提示用户。恐怕没有“不要再问我”功能。有没有什么好方法可以让蓝牙设备被发现?我不在乎持续时间。我的设备也没有 root。
更多信息
我找到了 BluetoothAdapter.java 的源代码,它有一个名为 setDiscoverableDuration
的 public 方法。但为什么我无法访问它?为什么某些 public 方法隐藏在 Api 文档中?他们是怎么做到的?所有方法都是 public.
最后我找到了一种使用反射来完成此操作的方法。
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();
}
警告:以上方法试图调用隐藏方法。所以以后可能就不行了。
我可以使用以下代码在没有任何提示的情况下打开 on/off 蓝牙。它需要 BLUETOOTH
和 BLUETOOTH_ADMIN
权限。
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
} else if (!enable && isEnabled) {
return bluetoothAdapter.disable();
}
但没有找到任何方法来设置蓝牙在没有用户提示的情况下可发现。它每次都会提示用户。恐怕没有“不要再问我”功能。有没有什么好方法可以让蓝牙设备被发现?我不在乎持续时间。我的设备也没有 root。
更多信息
我找到了 BluetoothAdapter.java 的源代码,它有一个名为 setDiscoverableDuration
的 public 方法。但为什么我无法访问它?为什么某些 public 方法隐藏在 Api 文档中?他们是怎么做到的?所有方法都是 public.
最后我找到了一种使用反射来完成此操作的方法。
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();
}
警告:以上方法试图调用隐藏方法。所以以后可能就不行了。