建立通話應用程式的通話樣式通知

在 Android 12.0 (API 級別 31) 以上版本中,系統會提供 CallStyle 通知範本,用來區分通話通知和其他類型的通知。使用這個範本建立來電或通話中通知。這個範本支援大型格式通知,其中包含來電者資訊和必要動作,例如接聽或拒接來電。

由於來電和通話中事件的優先順序較高,這些通知會在通知欄中優先顯示。系統也會根據這項排名,將優先來電轉接至其他裝置。

CallStyle 通知範本包含下列必要動作:

  • 接聽拒接來電。
  • 掛斷進行中的通話。
  • 在來電過濾期間接聽掛斷電話。

這類動作會以按鈕形式顯示,系統會自動加入適當的圖示和文字。系統不支援手動標記按鈕。 如要進一步瞭解通知設計原則,請參閱「通知」。

含有標籤按鈕的通話樣式通知
圖 1. 來電和通話中的 CallStyle 範本。

必要動作會以意圖形式傳遞,例如下列章節中的 hangupIntentanswerIntent。這些都是系統維護權杖的參照。權杖是輕量型物件,可在不同應用程式和程序之間傳遞。系統會負責管理權杖的生命週期,並確保即使建立權杖的應用程式不再執行,PendingIntent 仍可使用。授予其他應用程式 PendingIntent 時,您是授予該應用程式執行指定作業的權限,例如拒絕或接聽電話。即使建立 Intent 的應用程式未執行,系統仍會授予這項權限。詳情請參閱 PendingIntent 的參考文件。

從 Android 14 (API 級別 34) 開始,您可以將通話通知設為無法關閉。如要這麼做,請使用 CallStyle 通知,並透過 Notification.FLAG_ONGOING_EVENT Notification.Builder#setOngoing(true)

以下範例說明如何搭配 CallStyle 通知使用各種方法。

  // Create a new call, setting the user as the caller.
  val incomingCaller = Person.Builder()
      .setName("Jane Doe")
      .setImportant(true)
      .build()

來電

使用 forIncomingCall() 方法,為來電建立通話樣式的通知。

  // Create a call style notification for an incoming call.
  val builder = Notification.Builder(context, CHANNEL_ID)
      .setContentIntent(contentIntent)
      .setSmallIcon(smallIcon)
      .setStyle(
           Notification.CallStyle.forIncomingCall(caller, declineIntent, answerIntent))
      .addPerson(incomingCaller)

通話中

使用 forOngoingCall() 方法,為進行中的通話建立通話樣式的通知。

  // Create a call style notification for an ongoing call.
  val builder = Notification.Builder(context, CHANNEL_ID)
      .setContentIntent(contentIntent)
      .setSmallIcon(smallIcon)
      .setStyle(
           Notification.CallStyle.forOngoingCall(caller, hangupIntent))
      .addPerson(second_caller)

過濾來電

使用 forScreeningCall() 方法建立通話樣式的通知,以便篩選來電。

  // Create a call style notification for screening a call.
  val builder = Notification.Builder(context, CHANNEL_ID)
      .setContentIntent(contentIntent)
      .setSmallIcon(smallIcon)
      .setStyle(
           Notification.CallStyle.forScreeningCall(caller, hangupIntent, answerIntent))
      .addPerson(second_caller)

支援更多 Android 版本

在 API 級別 30 以下版本中,將 CallStyle 通知與前景服務建立關聯,以便在 API 級別 31 以上版本中,為通知指派高優先順序。此外,在 API 第 30 版或更早版本中,只要使用 setColorized() 方法將通知標示為彩色,CallStyle 通知也能獲得類似的排名。

搭配CallStyle通知使用 Telecom API。詳情請參閱「電信架構總覽」。