使用 Telecom API 管理通话

本指南介绍了如何使用Telecom API为蓝牙设备路由音频,以及如何设置 VoIP 通话的连接。在继续之前,请阅读构建呼叫应用指南。

通过使用ConnectionServiceConnection类,您可以访问音频状态和可用蓝牙设备列表,并将音频路由到选定的蓝牙设备。

VoIP Connection 和 ConnectionService

创建一个继承自ConnectionVoIPConnection类。此类控制当前呼叫的状态。正如构建呼叫应用指南所述,将其设为自管理应用,并为 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>

通过这些自定义的ConnectionConnectionService类,您可以控制在通话期间使用哪个设备和哪种类型的音频路由。

获取当前音频状态

要获取当前音频状态,请调用getCallAudioState()getCallAudioState()返回设备是否正在使用蓝牙、听筒、有线或扬声器进行流式传输。

mAudioState = connection.getCallAudioState()

On State Changed

通过覆盖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

Collection availableBluetoothDevices = mAudioState.getSupportedBluetoothDevices();

路由呼叫音频

使用requestBluetoothAudio(BluetoothDevice)将呼叫音频路由到可用的蓝牙设备

requestBluetoothAudio(availableBluetoothDevices[0]);

使用 API 级别 23 及更高版本

使用setAudioRoute(int)启用ROUTE_BLUETOOTH,但不指定设备。在 Android 9 及更高版本上,这将默认路由到当前活动的蓝牙设备。

setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);