在Android上以编程方式通过Hands Free Profile连接到蓝牙设备

时间:2014-07-11 16:12:41

标签: android bluetooth hfp

我们有一个Bluegiga蓝牙模块,可以作为免提设备使用。 初始配对后,我需要我的应用程序通过HFP以编程方式启动它的连接。这可以在Android中实现吗?

1 个答案:

答案 0 :(得分:1)

使用隐藏的api对我有效!

// 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);
相关问题