且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用蓝牙耳机 API 获取蓝牙连接设备

更新时间:2023-01-24 10:22:34

终于有了解决方案.下面是一些使用 BluetoothHeadset API 获取蓝牙音频连接设备的代码片段.

Finally got the solution. Below are a few code snippets for getting Bluetooth audio connected devices using BluetoothHeadset API.

BluetoothHeadset mBluetoothHeadset;

// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);


// Define Service Listener of BluetoothProfile
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = (BluetoothHeadset) proxy;
        }
    }
    public void onServiceDisconnected(int profile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null;
        }
    }
};


// call functions on mBluetoothHeadset to check if Bluetooth SCO audio is connected.
List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();                        
for ( final BluetoothDevice dev : devices ) {           
     return mBluetoothHeadset.isAudioConnected(dev);
}


// finally Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);