在媒體應用程式中新增通知

建構處理音訊或影片的媒體應用程式時,請務必使用正確的通知和通知管道。這可確保通知具有下列實用功能:

  • 設定通知優先順序
  • 無法關閉
  • 使用鈴聲的音訊屬性

使用 NotificationChannel.Builder 設定兩個通知管道:一個用於來電,另一個用於進行中的通話。

internal companion object {
    const val TELECOM_NOTIFICATION_ID = 200
    const val TELECOM_NOTIFICATION_ACTION = "telecom_action"
    const val TELECOM_NOTIFICATION_INCOMING_CHANNEL_ID = "telecom_incoming_channel"
    const val TELECOM_NOTIFICATION_ONGOING_CHANNEL_ID = "telecom_ongoing_channel"

    private val ringToneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
}

如要在任何位置顯示通知,並允許通知播放鈴聲,請將來電通知管道的重要性設為高。

val incomingChannel = NotificationChannelCompat.Builder(
    TELECOM_NOTIFICATION_INCOMING_CHANNEL_ID,
    NotificationManagerCompat.IMPORTANCE_HIGH,
).setName("Incoming calls")
    .setDescription("Handles the notifications when receiving a call")
    .setVibrationEnabled(true).setSound(
        ringToneUri,
        AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setLegacyStreamType(AudioManager.STREAM_RING)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(),
    ).build()

只有進行中的通話需要將重要性設為預設。請使用下列來電樣式,讓來電通知無法關閉。

val ongoingChannel = NotificationChannelCompat.Builder(
    TELECOM_NOTIFICATION_ONGOING_CHANNEL_ID,
    NotificationManagerCompat.IMPORTANCE_DEFAULT,
)
    .setName("Ongoing calls")
    .setDescription("Displays the ongoing call notifications")
    .build()

如要處理使用者裝置在來電時鎖定的情況,請使用全螢幕通知顯示活動,讓使用者接聽來電。

// on the notification
val contentIntent = PendingIntent.getActivity(
    /* context = */ context,
    /* requestCode = */ 0,
    /* intent = */ Intent(context, TelecomCallActivity::class.java),
    /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)

請參閱「為通話應用程式建立通話樣式通知」,瞭解如何使用 CallStyle 區分來電通知和其他類型的通知。