本指南介绍如何使用 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= mAudioState.getSupportedBluetoothDevices()
Java
CollectionavailableBluetoothDevices = mAudioState.getSupportedBluetoothDevices();
转接通话音频
使用 API 级别 28 及更高级别(推荐)
使用 requestBluetoothAudio(BluetoothDevice)
将通话音频路由到可用的蓝牙设备:
requestBluetoothAudio(availableBluetoothDevices[0]);
使用 API 级别 23 及更高级别
启用 ROUTE_BLUETOOTH
,而无需使用 setAudioRoute(int)
指定设备。此设置默认路由到 Android 9 及更高版本上当前有效的蓝牙设备。
setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);