建立通知

通知功能可在應用程式處於閒置狀態時,為使用者提供簡短且即時的應用程式事件資訊。本文將說明如何建立具有各種功能的通知。如要瞭解 Android 上的通知顯示方式,請參閱「通知總覽」。如需使用通知的程式碼範例,請參閱 GitHub 上的 SociaLite 範例

本頁中的程式碼使用 AndroidX 程式庫的 NotificationCompat API。這些 API 可讓您新增僅適用於較新 Android 版本的相關功能,同時仍提供回溯相容性,支援 Android 9 (API 級別 28)。不過,部分功能 (例如內嵌回覆動作) 在舊版中會導致無作業。

新增 AndroidX Core 程式庫

雖然使用 Android Studio 建立的大多數專案都包含使用 NotificationCompat 的必要依附元件,但請確認模組層級 build.gradle 檔案包含下列依附元件:

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.16.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.16.0")
}

建立基本通知

最基本且精簡的通知形式 (也稱為「摺疊形式」) 會顯示圖示、標題和少量文字內容。本節說明如何建立通知,讓使用者輕觸通知即可啟動應用程式中的活動。

圖 1. 含有圖示、標題和部分文字的通知。

如要進一步瞭解通知的各個部分,請參閱通知結構

宣告執行階段權限

Android 13 (API 級別 33) 以上版本支援執行階段權限,以便從應用程式發布非豁免 (包括前景服務 (FGS)) 通知。

以下程式碼片段顯示您必須在應用程式資訊清單檔案中宣告的權限:

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

如要進一步瞭解執行階段權限,請參閱「通知執行階段權限」。

設定通知內容

如要開始,請使用 NotificationCompat.Builder 物件設定通知內容和管道。下列範例說明如何建立通知,並包含以下項目:

  • 小型圖示,由 setSmallIcon() 設定。這是唯一必要的使用者可見內容。

  • 標題,由 setContentTitle()設定。

  • 內文,由 setContentText() 設定。

  • 通知優先順序,由 setPriority()設定。 在 Android 7.1 和舊版中,優先順序會決定通知的干擾程度。如果是 Android 8.0 以上版本,請改為設定管道重要性,如下一節所示。

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationCompat.Builder 建構函式需要您提供頻道 ID。這是為了與 Android 8.0 (API 級別 26) 以上版本相容,但較舊版本會忽略這項設定。

根據預設,通知的文字內容會遭到截斷,以便在單行顯示所有內容。您可以建立可展開的通知,顯示額外資訊。

圖 2. 可展開的通知,分別以收合和展開形式顯示。

如要增加通知長度,可以新增含有 setStyle() 的樣式範本,啟用可展開的通知。舉例來說,下列程式碼會建立較大的文字區域:

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

如要進一步瞭解其他大型通知樣式,包括如何新增圖片和媒體播放控制項,請參閱「建立可展開通知」。

建立管道並設定重要性

如要在 Android 8.0 以上版本中傳送通知,請將 NotificationChannel 的執行個體傳遞至 createNotificationChannel(),向系統註冊應用程式的通知管道。下列程式碼會因 SDK_INT 版本條件而遭到封鎖:

Kotlin

private fun createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system.
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

Java

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this.
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

由於您必須先建立通知管道,才能在 Android 8.0 以上版本發布任何通知,因此請在應用程式啟動後立即執行這段程式碼。重複呼叫此方法是安全的,因為建立現有的通知管道不會執行任何作業。

NotificationChannel 建構函式需要 importance,並使用 NotificationManager 類別中的其中一個常數。這個參數會決定如何中斷使用者操作,以顯示屬於這個管道的任何通知。如上例所示,請使用 setPriority() 設定優先順序,支援 Android 7.1 以下版本。

雖然您必須按照下列範例設定通知重要性或優先順序,但系統不保證會提供您想要的警示行為。在某些情況下,系統可能會根據其他因素變更重要性層級,使用者隨時可以重新定義特定管道的重要性層級。

如要進一步瞭解不同等級的意義,請參閱通知重要性等級

設定通知的輕觸動作

每則通知都必須回應輕觸動作,通常是開啟應用程式中與通知相應的活動。如要這麼做,請指定以 PendingIntent 物件定義的內容意圖,並將其傳遞至 setContentIntent()

下列程式碼片段說明如何建立基本意圖,讓使用者輕觸通知時開啟活動:

Kotlin

// Create an explicit intent for an Activity in your app.
val intent = Intent(this, AlertDetails::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)

Java

// Create an explicit intent for an Activity in your app.
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

這段程式碼會呼叫 setAutoCancel(),在使用者輕觸通知時自動移除通知

在上例中,意圖標記會在使用者透過通知開啟應用程式後,保留使用者預期的導覽體驗。視您要啟動的活動類型而定,您可能需要使用這項功能。活動類型可以是下列其中一種:

  • 專門用於回覆通知的活動。使用者在正常使用應用程式時,沒有理由要瀏覽這項活動,因此這項活動會啟動新工作,而不是新增至應用程式的現有工作和返回堆疊。這是前一個範例中建立的意圖類型。

  • 應用程式一般流程中的活動。在此情況下,啟動活動會建立返回堆疊,確保使用者對「返回」和「向上」按鈕的預期行為不會改變。

如要進一步瞭解設定通知意圖的不同方式,請參閱「從通知啟動活動」。

顯示通知

如要顯示通知,請呼叫 NotificationManagerCompat.notify(),並傳遞通知的專屬 ID 和 NotificationCompat.Builder.build() 的結果。例如:

Kotlin

with(NotificationManagerCompat.from(this)) {
    if (ActivityCompat.checkSelfPermission(
            this@MainActivity,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Consider calling
        // ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        // public fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
        //                                        grantResults: IntArray)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        return@with
    }
    // notificationId is a unique int for each notification that you must define.
    notify(NOTIFICATION_ID, builder.build())
}

Java

with(NotificationManagerCompat.from(this)) {
   if (ActivityCompat.checkSelfPermission(
           this@MainActivity,
           Manifest.permission.POST_NOTIFICATIONS
       ) != PackageManager.PERMISSION_GRANTED
   ) {
       // TODO: Consider calling
       // ActivityCompat#requestPermissions
       // here to request the missing permissions, and then overriding
       // public void onRequestPermissionsResult(int requestCode, String[] permissions,
       //                                        int[] grantResults)
       // to handle the case where the user grants the permission. See the documentation
       // for ActivityCompat#requestPermissions for more details.

       return
   }
   // notificationId is a unique int for each notification that you must define.
   notify(NOTIFICATION_ID, builder.build())
}

請儲存傳遞至 NotificationManagerCompat.notify() 的通知 ID,因為您需要這個 ID 來更新移除通知

此外,如要在搭載 Android 13 以上版本的裝置上測試基本通知,請手動開啟通知,或建立對話方塊來要求通知。

新增動作按鈕

通知最多可提供三個動作按鈕,讓使用者快速回應,例如延後提醒或回覆簡訊。但這些動作按鈕不得重複使用者輕觸通知時執行的動作。

圖 3. 含有一個動作按鈕的通知。

如要新增動作按鈕,請將 PendingIntent 傳遞至 addAction() 方法。這與設定通知的預設輕觸動作類似,但您可以執行其他動作,例如啟動 BroadcastReceiver 在背景執行工作,這樣動作就不會中斷已開啟的應用程式。

舉例來說,下列程式碼顯示如何將廣播傳送至特定接收器:

Kotlin

val ACTION_SNOOZE = "snooze"

val snoozeIntent = Intent(this, MyBroadcastReceiver::class.java).apply {
    action = ACTION_SNOOZE
    putExtra(EXTRA_NOTIFICATION_ID, 0)
}
val snoozePendingIntent: PendingIntent =
    PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent)

Java

String ACTION_SNOOZE = "snooze"

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

如要進一步瞭解如何建構 BroadcastReceiver 來執行背景工作,請參閱「廣播總覽」。

如果您想改為建立含有媒體播放按鈕的通知 (例如暫停及跳過曲目),請參閱如何建立含有媒體控制項的通知

新增直接回覆動作

Android 7.0 (API 級別 24) 推出的直接回覆動作,可讓使用者直接在通知中輸入文字。接著,系統會將文字傳送至應用程式,不必開啟活動。舉例來說,您可以透過直接回覆動作,讓使用者在通知中回覆簡訊或更新工作清單。

圖 4. 輕觸「回覆」按鈕即可開啟文字輸入畫面。

直接回覆動作會顯示為通知中的額外按鈕,開啟文字輸入畫面。使用者完成輸入後,系統會將文字回覆附加至您為通知動作指定的意圖,並將意圖傳送至應用程式。

新增回覆按鈕

如要建立支援直接回覆的通知動作,請按照下列步驟操作:

  1. 建立 RemoteInput.Builder 的執行個體,並新增至通知動作。這個類別的建構函式會接受字串,系統會將該字串做為文字輸入的鍵。應用程式稍後會使用該鍵擷取輸入內容的文字。

    Kotlin

      // Key for the string that's delivered in the action's intent.
      private val KEY_TEXT_REPLY = "key_text_reply"
      var replyLabel: String = resources.getString(R.string.reply_label)
      var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run {
          setLabel(replyLabel)
          build()
      }
      

    Java

      // Key for the string that's delivered in the action's intent.
      private static final String KEY_TEXT_REPLY = "key_text_reply";
    
      String replyLabel = getResources().getString(R.string.reply_label);
      RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
              .setLabel(replyLabel)
              .build();
      
  2. 為回覆動作建立 PendingIntent

    Kotlin

      // Build a PendingIntent for the reply action to trigger.
      var replyPendingIntent: PendingIntent =
          PendingIntent.getBroadcast(applicationContext,
              conversation.getConversationId(),
              getMessageReplyIntent(conversation.getConversationId()),
              PendingIntent.FLAG_UPDATE_CURRENT)
      

    Java

      // Build a PendingIntent for the reply action to trigger.
      PendingIntent replyPendingIntent =
              PendingIntent.getBroadcast(getApplicationContext(),
                      conversation.getConversationId(),
                      getMessageReplyIntent(conversation.getConversationId()),
                      PendingIntent.FLAG_UPDATE_CURRENT);
      
  3. 使用 addRemoteInput()RemoteInput 物件附加至動作。

    Kotlin

      // Create the reply action and add the remote input.
      var action: NotificationCompat.Action =
          NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
              getString(R.string.label), replyPendingIntent)
              .addRemoteInput(remoteInput)
              .build()
      

    Java

      // Create the reply action and add the remote input.
      NotificationCompat.Action action =
              new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                      getString(R.string.label), replyPendingIntent)
                      .addRemoteInput(remoteInput)
                      .build();
      
  4. 將動作套用至通知,然後發出通知。

    Kotlin

      // Build the notification and add the action.
      val newMessageNotification = Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build()
    
      // Issue the notification.
      with(NotificationManagerCompat.from(this)) {
          notificationManager.notify(notificationId, newMessageNotification)
      }
      

    Java

      // Build the notification and add the action.
      Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build();
    
      // Issue the notification.
      NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
      notificationManager.notify(notificationId, newMessageNotification);
      

使用者觸發通知動作時,系統會提示他們輸入回覆,如圖 4 所示。

從回覆中擷取使用者輸入內容

如要從通知的回覆 UI 接收使用者輸入內容,請呼叫 RemoteInput.getResultsFromIntent(),並將 BroadcastReceiver 收到的 Intent 傳遞給該函式:

Kotlin

private fun getMessageText(intent: Intent): CharSequence? {
    return RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_TEXT_REPLY)
}

Java

private CharSequence getMessageText(Intent intent) {
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput != null) {
        return remoteInput.getCharSequence(KEY_TEXT_REPLY);
    }
    return null;
 }

處理完文字後,請呼叫 NotificationManagerCompat.notify() 更新通知,並使用相同的 ID 和標記 (如有)。這是必要步驟,可隱藏直接回覆 UI,並向使用者確認系統已收到回覆並正確處理。

Kotlin

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
val repliedNotification = Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build()

// Issue the new notification.
NotificationManagerCompat.from(this).apply {
    notificationManager.notify(notificationId, repliedNotification)
}

Java

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
Notification repliedNotification = new Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build();

// Issue the new notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, repliedNotification);

處理這項新通知時,請使用傳遞至接收端 onReceive() 方法的內容。

呼叫 setRemoteInputHistory(),將回覆內容附加到通知底部。不過,如果您要建構訊息應用程式,請建立訊息樣式的通知,並將新訊息附加至對話。

如需即時通訊應用程式通知的更多建議,請參閱「即時通訊應用程式最佳做法」一節。

顯示緊急訊息

應用程式可能需要顯示緊急或時效性高的訊息,例如來電或鬧鐘響鈴。在這種情況下,您可以將全螢幕意圖與通知建立關聯。

通知觸發時,使用者會看到下列其中一種情況,視裝置的鎖定狀態而定:

  • 如果使用者的裝置已鎖定,系統會顯示全螢幕活動,覆蓋螢幕鎖定畫面。
  • 如果使用者裝置已解鎖,通知會以展開形式顯示,並提供處理或關閉通知的選項。

下列程式碼片段說明如何將通知與全螢幕意圖建立關聯:

Kotlin

val fullScreenIntent = Intent(this, ImportantActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
    fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true)

Java

Intent fullScreenIntent = new Intent(this, ImportantActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
        fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true);

設定鎖定螢幕顯示內容

如要控制鎖定畫面上顯示的通知詳細資料程度,請呼叫 setVisibility(),並指定下列其中一個值:

  • VISIBILITY_PUBLIC:螢幕鎖定畫面會顯示通知的完整內容。

  • VISIBILITY_SECRET:螢幕鎖定畫面不會顯示任何通知內容。

  • VISIBILITY_PRIVATE:螢幕鎖定畫面只會顯示基本資訊,例如通知圖示和內容標題。通知不會顯示完整內容。

設定 VISIBILITY_PRIVATE 時,您也可以提供通知內容的替代版本,隱藏特定詳細資料。舉例來說,簡訊應用程式可能會顯示「您有 3 則新訊息」的通知,但隱藏訊息內容和傳送者。如要提供這類替代通知,請先照常使用 NotificationCompat.Builder 建立替代通知。然後使用 setPublicVersion() 將替代通知附加至一般通知。

請注意,使用者可以完全控管是否要在螢幕鎖定畫面上顯示通知,並根據應用程式的通知管道進行控管。

更新通知

如要在發出通知後更新通知,請再次呼叫 NotificationManagerCompat.notify(),並傳遞先前使用的相同 ID。如果先前的通知遭到關閉,系統會改為建立新通知。

您可以選擇呼叫 setOnlyAlertOnce(),讓通知在第一次顯示時中斷使用者操作 (透過音效、震動或視覺提示),之後的更新則不會中斷。

移除通知

通知會持續顯示,直到發生下列任一情況為止:

  • 使用者關閉通知。
  • 使用者輕觸通知 (如果您在建立通知時呼叫 setAutoCancel())。
  • 您會針對特定通知 ID 呼叫 cancel()。這個方法也會刪除進行中的通知。
  • 您會呼叫 cancelAll(),移除先前發布的所有通知。
  • 如果您在建立通知時設定逾時,系統會在指定時間到期後,使用 setTimeoutAfter()。如有需要,您可以在指定逾時時間經過前取消通知。

訊息應用程式最佳做法

為訊息和即時通訊應用程式建立通知時,請參考下列最佳做法。

使用 MessagingStyle

從 Android 7.0 (API 級別 24) 開始,Android 提供專為訊息內容設計的通知樣式範本。使用 NotificationCompat.MessagingStyle 類別,您可以變更通知中顯示的幾個標籤,包括對話標題、其他訊息和通知的內容檢視畫面。

下列程式碼片段說明如何使用 MessagingStyle 類別自訂通知樣式。

Kotlin

val user = Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build()

val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with $sender")
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build()

Java

Person user = new Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build();

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with " + sender)
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(new NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build();

從 Android 9.0 (API 級別 28) 開始,您也必須使用 Person 類別,才能以最佳方式算繪通知和其頭像。

使用 NotificationCompat.MessagingStyle 時,請注意下列事項:

  • 通話 MessagingStyle.setConversationTitle() 為超過兩人的群組對話設定標題。好的對話標題可以是群組即時通訊的名稱,如果沒有名稱,則可以是對話參與者清單。如果沒有這項屬性,系統可能會誤以為該訊息屬於與對話中最新訊息傳送者的私人對話。
  • 使用 MessagingStyle.setData() 方法加入圖片等媒體訊息。支援 image/* 模式的 MIME 類型。

使用直接回覆功能

使用者可以透過「直接回覆」功能,在訊息內文中回覆。

啟用智慧回覆

  • 如要啟用智慧回覆功能,請在回覆動作中呼叫 setAllowGeneratedResponses(true)。這樣一來,當通知橋接至 Wear OS 裝置時,使用者就能使用智慧回覆功能。智慧回覆功能會使用完全在手錶上執行的機器學習模型,根據NotificationCompat.MessagingStyle通知提供的內容生成回覆,且不會將任何資料上傳至網際網路。

新增通知中繼資料