Android connect to a paired bluetooth headset

androidbluetoothheadset

I want to simulate the action of going throgh Settings->Wireless->Bluetooth and connect a paired bluetooth headset programmatically. I've done some search in Stackoverflow and Google, both indicating that there is no solution available before API level 11. However, I'm interested in working it out by peeking in the source code of bluetooth implementation of Android. The problem is that I'm not aware of which specific source code I should review. Any suggestions? Many thanks.

Best Answer

After days of struggling, I've now managed to do it, cheers :)

  1. Add android.bluetooth.IBluetoothA2dp.aidl in your /src dir of your app;
  2. Add this private method in your code:

    private IBluetoothA2dp getIBluetoothA2dp() {
    
    IBluetoothA2dp ibta = null;
    
    try {
    
        Class c2 = Class.forName("android.os.ServiceManager");
    
        Method m2 = c2.getDeclaredMethod("getService", String.class);
        IBinder b = (IBinder) m2.invoke(null, "bluetooth_a2dp");
    
        Log.d("Felix", "Test2: " + b.getInterfaceDescriptor());
    
        Class c3 = Class.forName("android.bluetooth.IBluetoothA2dp");
    
        Class[] s2 = c3.getDeclaredClasses();
    
        Class c = s2[0];
        // printMethods(c);
        Method m = c.getDeclaredMethod("asInterface", IBinder.class);
    
        m.setAccessible(true);
        ibta = (IBluetoothA2dp) m.invoke(null, b);
    
    } catch (Exception e) {
        Log.e("flowlab", "Erroraco!!! " + e.getMessage());
    }
    
  3. Test it with this:

    private void testBluetoothA2dp(BluetoothDevice device) {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    IBluetoothA2dp ibta = getIBluetoothA2dp();
    try {
        Log.d("Felix", "Here: " + ibta.getSinkPriority(device));
        ibta.connectSink(device);
    } catch (RemoteException e) {
        // * TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    }

I'm not able to provide references of these code since I've spent lots of time googling, checking out stackoverflow, and reviewing Android source code, but failed to keep track of sources. Many thanks to you guys in Stackoverflow :)