Reputation: 2418
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.
Upvotes: 5
Views: 3172
Reputation: 2418
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.
Upvotes: 17