建立通知

通知功能可在使用者當機時,提供簡短的應用程式內事件資訊 並沒有使用中的資源本文件說明如何建立通知 各項功能如果想瞭解 Android 如何顯示通知, 請參閱通知總覽。 如需使用通知的程式碼範例,請參閱人員 範例

本網頁中的程式碼使用 NotificationCompat敬上 來自 AndroidX 程式庫的 API這些 API 可讓您新增 ,同時仍為 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")
}

建立基本通知

以最基本和精簡形式呈現的通知,也稱為「收合」 form:顯示圖示、標題和少量文字內容。這個 一節說明如何建立通知,讓使用者輕觸即可啟動 在應用程式中的活動。

圖 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 建構函式會要求您提供管道 編號。此為與 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 以上版本中傳送通知,請先註冊 應用程式的通知管道,其中包含 方法是傳送 NotificationChannelcreateNotificationChannel()。 下列程式碼因 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, 因為在您更新移除 通知。

此外,如要在執行以下作業系統的裝置上測試基本通知, 在 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)</span>
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);</span>

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. RemoteInput 將物件對應至動作 addRemoteInput()

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

處理完文字後,請透過 具有相同 ID 和標記的 NotificationManagerCompat.notify() (如有使用)。這是 隱藏直接回覆使用者介面,並向使用者確認該則回覆。 正確接收及處理的資料。

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. 期間的進度列 一項作業

如果您能隨時估算作業完成的進度,請使用 「確定」指標形式 (如圖 5 所示),方法是呼叫 setProgress(max, progress, false)。 第一個參數是「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 會使用預先定義的系統層級類別,判斷是否要幹擾 使用者啟用零打擾模式時,向系統顯示特定通知的使用者 模式。

如果您的通知屬於 NotificationCompatCATEGORY_ALARM, CATEGORY_REMINDER, CATEGORY_EVENT, 或 CATEGORY_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(),使用者會輕觸通知 建立通知
  • 你打電話 cancel()敬上 並針對特定通知 ID 進行查詢這個方法也會刪除持續執行的作業 通知。
  • 你打電話 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()敬上 方法,以納入媒體訊息 (例如圖片)。模式的 MIME 類型 圖片/*。

使用直接回覆

直接回覆功能可讓使用者直接在郵件中回覆郵件。

啟用智慧回覆

  • 如要啟用智慧回覆功能,請撥打 setAllowGeneratedResponses(true)敬上 回應動作。這麼做會導致智慧回覆回覆功能 使用者將通知橋接至 Wear OS 裝置時。智慧回覆 該回應是由完全監控的機器學習模型 NotificationCompat.MessagingStyle 提供的背景資訊 通知,也不會將資料上傳至網際網路,以產生 回應。

新增通知中繼資料