建立通知

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

本頁中的程式碼使用 AndroidX 程式庫的 NotificationCompat API。這些 API 可讓您新增僅在較新版本的 Android 上使用的功能,同時仍提供與 Android 9 (API 級別 28) 的相容性。不過,有些功能 (例如內嵌回覆動作) 會導致在舊版本中免人工管理。

新增 AndroidX 核心程式庫

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

Groovy

dependencies {
    implementation "androidx.core:core:2.2.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:2.2.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(),當使用者輕觸通知時,會自動移除通知

上述範例中顯示的 setFlags() 方法可在使用者使用通知開啟應用程式後,保留預期的導覽體驗。建議您根據要啟動的活動類型使用這項設定,可以是下列其中一種:

  • 僅為回應通知的活動。使用者沒有理由在正常使用應用程式時前往這個活動,因此活動會啟動新的任務,而不是新增至應用程式現有的工作和返回堆疊。這是在上述範例中建立的意圖類型。

  • 應用程式一般應用程式流程中的活動。在此情況下,啟動活動會建立返回堆疊,藉此保留使用者對於「返回」和「向上」按鈕的期望。

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

顯示通知

如要顯示通知,請呼叫 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(),將其Intent傳送至BroadcastReceiver

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;
 }

處理文字後,請呼叫具有相同 ID 和標記 (如有) 的 NotificationManagerCompat.notify() 來更新通知。您必須隱藏直接回覆 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(),將回覆附加至通知底部。不過,如果您正在建構訊息應用程式,請建立訊息樣式通知,並將新訊息附加到對話中。

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

新增進度列

通知可以包含動畫進度指標,向使用者顯示正在執行作業的狀態。

圖 5. 作業期間的進度列。

如果您能夠隨時估算作業完成的進度,請透過呼叫 setProgress(max, progress, false) 使用「確定」指標 (如圖 5 所示)。第一個參數是「complete」值,例如 100。第二項是完成時間最後一項表示這是明確的進度列

此時,請持續呼叫 setProgress(max, progress, false),並提供 progress 的更新值,然後重新發出通知,如以下範例所示。

Kotlin

val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
    setContentTitle("Picture Download")
    setContentText("Download in progress")
    setSmallIcon(R.drawable.ic_notification)
    setPriority(NotificationCompat.PRIORITY_LOW)
}
val PROGRESS_MAX = 100
val PROGRESS_CURRENT = 0
NotificationManagerCompat.from(this).apply {
    // Issue the initial notification with zero progress.
    builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
    notify(notificationId, builder.build())

    // Do the job that tracks the progress here.
    // Usually, this is in a worker thread.
    // To show progress, update PROGRESS_CURRENT and update the notification with:
    // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
    // notificationManager.notify(notificationId, builder.build());

    // When done, update the notification once more to remove the progress bar.
    builder.setContentText("Download complete")
            .setProgress(0, 0, false)
    notify(notificationId, builder.build())
}

Java

...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentTitle("Picture Download")
        .setContentText("Download in progress")
        .setSmallIcon(R.drawable.ic_notification)
        .setPriority(NotificationCompat.PRIORITY_LOW);

// Issue the initial notification with zero progress.
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
notificationManager.notify(notificationId, builder.build());

// Do the job that tracks the progress here.
// Usually, this is in a worker thread.
// To show progress, update PROGRESS_CURRENT and update the notification with:
// builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
// notificationManager.notify(notificationId, builder.build());

// When done, update the notification once more to remove the progress bar.
builder.setContentText("Download complete")
        .setProgress(0,0,false);
notificationManager.notify(notificationId, builder.build());

作業結束時,progress 必須等於 max。您可以離開進度列顯示作業已完成,也可以移除該作業。無論是哪一種情況,請更新通知文字,以顯示作業已完成。如要移除進度列,請呼叫 setProgress(0, 0, false)

如要顯示未確定的進度列 (不含完成百分比的列),請呼叫 setProgress(0, 0, true)。結果是一個指標,其樣式與先前的進度列相同,唯一差別在於前者是不表示完成的連續動畫。進度動畫會持續執行,直到您呼叫 setProgress(0, 0, false) 為止,然後更新通知以移除活動指標。

請記得變更通知文字,以表示作業已完成。

設定系統通用的類別

當使用者啟用零打擾模式時,Android 會使用預先定義的系統層級類別,判斷是否要透過指定的通知幹擾使用者。

如果您的通知屬於 NotificationCompat 定義的其中一個通知類別 (例如 CATEGORY_ALARMCATEGORY_REMINDERCATEGORY_EVENTCATEGORY_CALL),請將適當類別傳遞至 setCategory() 進行宣告:

Kotlin

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

Java

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

系統會根據通知類別相關資訊,在裝置處於「零打擾」模式時顯示通知。不過,您不一定要設定系統通用的類別。只有在通知符合 NotificationCompat 定義的其中一個類別時,才需要執行這項操作。

顯示緊急訊息

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

叫用通知時,使用者會根據裝置的鎖定狀態看到下列其中一種內容:

  • 如果使用者的裝置處於鎖定狀態,系統會顯示全螢幕活動並遮住螢幕鎖定畫面。
  • 如果使用者的裝置已解鎖,通知會以展開的形式顯示,其中包含處理或關閉通知的選項。

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

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 通知提供的結構定義產生,不會將資料上傳至網際網路以產生回應。

新增通知中繼資料