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

问题描述 投票:3回答:1

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

android bluetooth hfp
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.