本指南介绍了如何使用 Telecom API 为蓝牙设备路由音频,以及如何为 VoIP 通话设置连接。请先阅读构建通话应用指南,然后再继续。
通过使用 ConnectionService 和 Connection 类,您可以访问音频状态和可用蓝牙设备列表,并可以将音频路由到所选蓝牙设备。
VoIP 连接和 ConnectionService
创建一个从 Connection 扩展的 VoIPConnection 类。此类用于控制当前通话的状态。如构建通话应用指南中所述,请将此应用设为自行管理的应用,并为 VoIP 应用设置音频模式。
Kotlin
class VoIPConnection : Connection() {
init {
setConnectionProperties(PROPERTY_SELF_MANAGED)
setAudioModeIsVoip(true)
}
}
Java
public class VoIPConnection extends Connection {
public VoIPConnection() {
setConnectionProperties(PROPERTY_SELF_MANAGED);
setAudioModeIsVoip(true);
}
}
接下来,在发生来电或去电时,在 ConnectionService 中返回此类的实例。
Kotlin
class VoIPConnectionService : ConnectionService() {
override fun onCreateOutgoingConnection(
connectionManagerPhoneAccount: PhoneAccountHandle,
request: ConnectionRequest,
): Connection {
return VoIPConnection()
}
}
Java
public class VoIPConnectionService extends ConnectionService {
@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
return new VoIPConnection();
}
}
确保清单正确指向 VoIPConnectionService 类。
<service android:name=".voip.TelegramConnectionService" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService"/>
</intent-filter>
</service>
借助这些自定义 Connection 和 ConnectionService 类,您可以控制在通话期间要使用哪个设备以及哪种类型的音频路由。
获取当前音频状态
如需获取当前音频状态,请调用 getCallAudioState。
getCallAudioState 会返回设备是否正在使用蓝牙、手机听筒、有线头戴式耳机或扬声器进行流式传输。
mAudioState = connection.getCallAudioState()
状态更改时
通过替换 onCallAudioStateChanged() 订阅 CallAudioState 中的更改。这会提醒您状态发生任何变化。
Kotlin
fun onCallAudioStateChanged(audioState: CallAudioState) {
mAudioState = audioState
}
Java
@Override
public void onCallAudioStateChanged(CallAudioState audioState) {
mAudioState = audioState;
}
获取当前设备
使用 CallAudioState.getActiveBluetoothDevice() 获取当前活跃的设备。此函数会返回活跃的蓝牙设备。
Kotlin
val activeDevice: BluetoothDevice = mAudioState.getActiveBluetoothDevice()
Java
BluetoothDevice activeDevice = mAudioState.getActiveBluetoothDevice();
获取蓝牙设备
使用 CallAudioState.getSupportedBluetoothDevices() 获取可用于通话音频转接的蓝牙设备列表。
Kotlin
val availableBluetoothDevices: Collection<BluetoothDevice> =
mAudioState.getSupportedBluetoothDevices()
Java
Collection<BluetoothDevice> availableBluetoothDevices = mAudioState.getSupportedBluetoothDevices();
路由通话音频
使用 API 级别 28 及更高级别(推荐)
使用 requestBluetoothAudio(BluetoothDevice) 将通话音频路由到可用的蓝牙设备:
requestBluetoothAudio(availableBluetoothDevices[0]);
使用 API 级别 23 及更高级别
使用 setAudioRoute(int) 启用 ROUTE_BLUETOOTH,而无需指定设备。在 Android 9 及更高版本中,此设置会默认将音频路由到当前处于活跃状态的蓝牙设备。
setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);