I am able to turn on/off Bluetooth without any prompt using the following code. It requires BLUETOOTH
and BLUETOOTH_ADMIN
permissions.
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
} else if (!enable && isEnabled) {
return bluetoothAdapter.disable();
}
But didn't find any way to set Bluetooth discoverable without user prompt. It's wired to prompt every time to user. There is no "don't ask me again" feature I afraid. Is there any good way to make Bluetooth device discoverable? I don't care about the duration. Also my device is not rooted.
I found source code of BluetoothAdapter.java and it has a public method named setDiscoverableDuration
. But why I can't access it? Why some public methods are hidden in Api documentations? How did they even do that? all methods are public.
Tap Settings. Tap Bluetooth. Tap the indicator next to "Bluetooth" to turn the function on or off. Tap the indicator next to "Open detection" to turn Bluetooth visibility on or off.
If your app makes the current device discoverable to other Bluetooth devices, declare the BLUETOOTH_ADVERTISE permission. If your app communicates with already-paired Bluetooth devices, declare the BLUETOOTH_CONNECT permission. For your legacy Bluetooth-related permission declarations, set android:maxSdkVersion to 30 .
Device discovery is a scanning procedure that searches the local area for Bluetooth-enabled devices and requests some information about each one. This process is sometimes referred to as discovering, inquiring, or scanning.
Finally I have found a way to do this using reflection.
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();
}
Warning: Above method is trying to invoke hidden method. So in future maybe it will not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With