简体   繁体   English

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

[英]Connect to bluetooth device via Hands Free Profile programatically on Android

We have a Bluegiga Bluetooth module that is set up to work as hands free device. 我们有一个Bluegiga蓝牙模块,可以作为免提设备使用。 After initial pairing, I need my application to initiate connection to it via HFP programmatically. 初始配对后,我需要我的应用程序通过HFP以编程方式启动它的连接。 Can this be achieved in Android? 这可以在Android中实现吗?

Using hidden api works for me! 使用隐藏的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM