概述
BluetoothA2dpSink
用于控制蓝牙A2DP接收器配置文件的公共API。简单而言,它是蓝牙音箱端的操作代理,可以控制蓝牙A2DP协议的连接断开,以及配置信息的查询等。
初始化
BluetoothA2dpSink
的实例通过BluetoothAdapter
的getProfileProxy
获取。
示例:
public void getA2DPSinkProxy(Context context){
BluetoothAdapter.getDefaultAdapter().getProfileProxy(context, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
BluetoothA2dpSink bluetoothA2dpSink = (BluetoothA2dpSink) proxy;
//此处拿到的代理实例为bluetoothA2dpSink。
}
@Override
public void onServiceDisconnected(int profile) {
}
},BluetoothProfile.A2DP_SINK);
}
A2DP协议连接与断开
connect
方法用于A2DP协议连接。
入参为蓝牙设备实例(通过BlueToothAdapter
获取)。
目前,系统仅支持一个A2DP协议连接。API将在连接之前自动断开已连接的设备。
在设备上的配置文件已连接或蓝牙未打开等情况下,此API返回false。当此API返回true时,可通过BluetoothA2dpSink.ACTION_CONNECTION_STATE_CHANGED
广播监听连接状态。(关于蓝牙相关广播,后续单独开一篇文章来讲。)
disconnect
方法用于A2DP协议断开。
入参为蓝牙设备实例(通过BlueToothAdapter
获取)。
在蓝牙设备上的配置文件未处于连接状态等情况下,此API将返回false。当此API返回true时,可通过BluetoothA2dpSink.ACTION_CONNECTION_STATE_CHANGED
广播监听断开状态。
如果断开连接是由远程设备启动的,则状态变化为STATE_CONNECTED
->STATE_DISCONNECTED
。
如果断开连接是由主机(本地)设备启动的,则状态为STATE_CONNECTED
->STATE_DISCONNECTING
->STATE_DISCONNECTED
。
获取配置及状态信息
getConnectedDevices
方法:
可以获取连接了A2DP协议的当前设备实例
getDevicesMatchingConnectionStates
方法:
获取满足连接状态的所有设备列表。
连接状态为BluetoothProfile.STATE_CONNECTING
、BluetoothProfile.STATE_DISCONNECTED
、BluetoothProfile.STATE_DISCONNECTING
中的一种。
getConnectionState
方法:
获取当前A2DP协议连接状态。状态包括BluetoothPrifile.STATE_CONNECTED
、BluetoothPrifile.STATE_CONNECTING
、BluetoothPrifile.STATE_DISCONNECTED
、BluetoothPrifile.STATE_DISCONNECTING
四种。
getAudioConfig
方法:
获取A2DP源设备的当前音频配置,如果设备没有音频配置,则为空。
音频配置信息在BluetoothAudioConfig
类中,包含音频格式等信息。
setPriority
方法:
设置权限。入参为需要设置的远端设备实例以及权限能力。
权限为 BluetoothA2dpSink.PRIORITY_ON
和BluetoothA2dpSink.PRIORITY_OFF
中的一种。
PRIORITY_ON
:可以连接A2DP。
PRIORITY_OFF
:不可连接A2DP。
设备权限可通过getPriority
方法获取。
setConnectionPolicy
方法:
设置协议连接策略。入参为需设置的设备及连接策略。
连接策略为BluetoothProfile.CONNECTION_POLICY_ALLOWED
, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
, BluetoothProfile.CONNECTION_POLICY_UNKNOWN
中的一种。
CONNECTION_POLICY_ALLOWED
:默认连接A2DP
CONNECTION_POLICY_FORBIDDEN
:默认不连接A2DP
CONNECTION_POLICY_UNKNOWN
:连接策略未知(设备没设置或设备未配对)
连接策略可通过getConnectionPolicy
方法获取。
isAudioPlaying
方法:
返回设备是否正在通过A2DP播放音频。
结语:
蓝牙音频协议不止用于车机。音频接收端如果是安卓设备,都可以使用该代理来进行操作(例:安卓智能音箱)。