4

We have a Bluegiga Bluetooth module that is set up to work as hands free device. After initial pairing, I need my application to initiate connection to it via HFP programmatically. Can this be achieved in Android?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

1 Answers1

1

Using hidden api works for me!

// get default bluetooth adapter
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
// get bounded device on Android
Set<BluetoothDevice> devices = mAdapter.getBondedDevices();
if (devices.size() > 0) {
    for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext();) {
        BluetoothDevice device = it.next();
        // treat the device the default buletooth device you needed
        mCurrentDevice = device;
        // break;
    }
} else {
    return;
}

// another method to get headset(HFP) profile
mAdapter.getProfileProxy(mContext, new BluetoothProfile.ServiceListener() {
    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        Log.e("log", "headset proxy connected");
        try {
            BluetoothHeadset mCurrentHeadset = (BluetoothHeadset) proxy;
            // check whether or not current device hfp is connected or not, if not, 
            // try to connect the channel between phone and device using hidden api
            if (mCurrentHeadset.getConnectionState(mCurrentDevice) != BluetoothHeadset.STATE_CONNECTED) {
                Method connectMethod = mCurrentHeadset.getClass().getMethod("connect", mCurrentDevice.getClass());
                connectMethod.setAccessible(true);
                Boolean returnValue = (Boolean) connectMethod.invoke(proxy, mCurrentDevice);
                Log.e("log", "headset proxy connected " + returnValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(int profile) {
        Log.e(LogTag.TAG, "headset profile disconnected");
    }
}, BluetoothA2dp.HEADSET);
tianyuac
  • 11
  • 3
  • Could you explain a bit more about the code you posted so other can learn from it? – Skami Sep 24 '17 at 16:00
  • 1
    I will vote up this answer, but first correct 'profile.getClass()' to 'mCurrentHeadset.getClass()' and in log change 'value' to 'returnValue'. – Neeraj Nama Apr 19 '18 at 09:44