Enable bluetooth tethering android programmatically

Bek picture Bek · Apr 4, 2014 · Viewed 8.5k times · Source

I am trying to make an application like "Bluetooth auto tethering" on play store. I read on the forum that Android is very security-aware and will not enable this setting without user interaction.

I need some explanations about how enable bluetooth tethering.

Thank you

Answer

Jaws86 picture Jaws86 · Jul 2, 2014

I don't know if this is still an issue or not, but I found that using the connect method in the reflection call works. Working off of the code that pmont used from the link in Lorelorelore's answer:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Class<?> classBluetoothPan = null;
Constructor<?> BTPanCtor = null;
Object BTSrvInstance = null;
Method mBTPanConnect;

try {
    classBluetoothPan = Class.forName("android.bluetooth.BluetoothPan");
    mBTPanConnect = classBluetoothPan.getDeclaredMethod("connect", BluetoothDevice.class);
    BTPanCtor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class);
    BTPanCtor.setAccessible(true);
    BTSrvInstance = BTPanCtor.newInstance(myContext, new BTPanServiceListener(myContext));
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
    // Loop through paired devices
    for (BluetoothDevice device : pairedDevices) {
        try{
            mBTPanConnect.invoke(BTSrvInstance, device);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Of course, this assumes that the bluetooth is enabled, and you only have one paired device. But enabling bluetooth is pretty straightforward using standard (not reflection) calls, and you can just check for the paired device that you want to connect to in the for loop. Also, don't forget the BTPanServiceListener class from the other answer as well.

Hope this helps.