How to Change the Scan Mode of Bluetooth Adapter in android.?

Amritpal Singh picture Amritpal Singh · Feb 6, 2013 · Viewed 8.7k times · Source

Currently i am working on a Bluetooth app where i need to change the Scan Mode from SCAN_MODE_CONNECTABLE_DISCOVERABLE to SCAN_MODE_CONNECTABLE on click of a button.

i am setting it Discoverable using following Intent:

Intent discoverableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent .putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISOVERABLE_DURATION);
startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT);

where i have set DISOVERABLE_DURATION=300;

Now i want to skip the Discoverability in between and want to change its state to SCAN_MODE_CONNECTABLE only.

Kindly provide me an appropriate solution../

Answer

tkrz picture tkrz · Jan 27, 2016

Well it is quite old question, however you can switch scan mode of bluetooth without any permission of user and (for as far as i have tested) unlimited time. This will require using reflections on Android API, so this is not an official api. Of course, you are using it on your own risk :) Below is code i am using to make BT adapter discoverable:

private boolean setBluetoothScanMode(int scanMode){
    Method method = null;
    final BluetoothAdapter btAdapter = btManager.getAdapter();

    if(!btAdapter.isEnabled()){
        Log.d(LCAT, "BT adapter is off, turning on");
        btAdapter.enable();
    }

    try {
        method = btAdapter.getClass().getMethod("setScanMode", int.class);
    } catch (SecurityException e) {
        return false;
    } catch (NoSuchMethodException e) {
        return false;
    }

    try {
      method.invoke(btAdapter, scanMode);
    } catch (IllegalArgumentException e) {
        return false;
    } catch (IllegalAccessException e) {
        return false;
    } catch (InvocationTargetException e) {
        return false;
    }
    return true;
}

Also you need permissions:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

After this device should be in scan mode you choose by passing the int scanMode argument. It is working on Android API 23.