使用 Telecom API 管理通话

本指南将介绍如何使用 Telecom API,并为 VoIP 通话。阅读 构建通话应用指南 然后再继续。

使用 ConnectionServiceConnection 类,您可以访问 音频状态和可用蓝牙设备的列表, 音频发送到所选蓝牙设备。

VoIP Connection 和 ConnectionService

创建一个从 VoIPConnection 扩展自 Connection。该类用于控制当前通话的状态。作为 构建通话应用指南 将此应用设为自行管理的应用,并为 VoIP 设置音频模式 应用。

KotlinJava
class VoIPConnection : Connection() {
 
init {
    setConnectionProperties
(PROPERTY_SELF_MANAGED)
    setAudioModeIsVoip
(true)
 
}
}
public class VoIPConnection extends Connection {
 
public VoIPConnection() {
    setConnectionProperties
(PROPERTY_SELF_MANAGED);
    setAudioModeIsVoip
(true);
 
}
}

接下来,在 ConnectionService, 来电或去电。

KotlinJava
class VoIPConnectionService : ConnectionService() {
 
override fun onCreateOutgoingConnection(
    connectionManagerPhoneAccount
: PhoneAccountHandle,
    request
: ConnectionRequest,
 
): Connection {
   
return VoIPConnection()
 
}
}
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>

借助这些自定义的 ConnectionConnectionService 门课程,您 可控制您在通话期间要使用的设备和音频路由类型 调用。

获取当前音频状态

要获取当前的音频状态,请调用 getCallAudioState()getCallAudioState() 返回(如果设备使用蓝牙、手机听筒、有线或 免提。

mAudioState = connection.getCallAudioState()

“开启”状态已更改

通过替换来订阅 CallAudioState 中的更改 onCallAudioStateChanged()。 此提醒功能会在状态发生变化时提醒您。

KotlinJava
fun onCallAudioStateChanged(audioState: CallAudioState) {
  mAudioState
= audioState
}
@Override
public void onCallAudioStateChanged(CallAudioState audioState) {
  mAudioState
= audioState;
}

获取当前设备

使用以下命令获取当前活跃的设备: CallAudioState.getActiveBluetoothDevice()。 此函数用于返回活动的蓝牙设备。

KotlinJava
val activeDevice: BluetoothDevice = mAudioState.getActiveBluetoothDevice()
BluetoothDevice activeDevice = mAudioState.getActiveBluetoothDevice();

获取蓝牙设备

获取可用于进行通话音频转接的蓝牙设备的列表 CallAudioState.getSupportedBluetoothDevices()

KotlinJava
val availableBluetoothDevices: Collection
Collection

转接通话音频

使用 requestBluetoothAudio(BluetoothDevice):

requestBluetoothAudio(availableBluetoothDevices[0]);

使用 API 级别 23 及更高级别

启用 ROUTE_BLUETOOTH 而无需使用 setAudioRoute(int)。 这会默认路由到搭载 Android 9 及更高版本的当前活跃蓝牙设备。

setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);