Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluetooth discovery without prompt in Android

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.

More Info

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.

like image 647
shantanu Avatar asked May 14 '15 19:05

shantanu


People also ask

How do I turn off Discovery Bluetooth on my Android phone?

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.

How do I give Bluetooth permission on Android?

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 .

What is discovery in Bluetooth?

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.


1 Answers

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.

like image 70
shantanu Avatar answered Sep 23 '22 03:09

shantanu