使用 Telecom API 管理通話

本指南說明如何使用 Telecom API 為藍牙裝置轉送音訊,以及設定 VoIP 呼叫的連線。請先詳閱「建構呼叫應用程式」指南,再繼續操作。

使用 ConnectionServiceConnection 類別即可存取音訊狀態和可用藍牙裝置清單,並且將音訊轉送至特定藍牙裝置。

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>

使用這些自訂 ConnectionConnectionService 類別,您可以控制在通話期間要使用的裝置及音訊轉送類型。

取得目前的音訊狀態

如要取得目前的音訊狀態,請呼叫 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

Collection availableBluetoothDevices = mAudioState.getSupportedBluetoothDevices();

轉接通話音訊

使用 requestBluetoothAudio(BluetoothDevice) 將通話音訊轉送至可用的藍牙裝置:

requestBluetoothAudio(availableBluetoothDevices[0]);

使用 API 級別 23 以上版本

啟用 ROUTE_BLUETOOTH,而無須使用 setAudioRoute(int) 指定裝置。根據預設,Android 9 以上版本會在目前啟用的藍牙裝置之間轉送到裝置上。

setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);